diff --git a/GameDev/AmbientLightTuner.xaml b/GameDev/AmbientLightTuner.xaml deleted file mode 100644 index 86495e16..00000000 --- a/GameDev/AmbientLightTuner.xaml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - diff --git a/GameDev/AmbientLightTuner.xaml.cs b/GameDev/AmbientLightTuner.xaml.cs deleted file mode 100644 index 06c10f50..00000000 --- a/GameDev/AmbientLightTuner.xaml.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for AmbientLightTuner.xaml - /// - public partial class AmbientLightTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public AmbientLightTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - float r = 1.0f; - float g = 1.0f; - float b = 1.0f; - if (att.ContainsKey("color")) - { - var color = att["color"].ToString().Split(','); - r = float.Parse(color[0]); - g = float.Parse(color[1]); - b = float.Parse(color[2]); - } - tuner_color.set_color(r, g, b); - } - - private void tuner_color_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["color"] = $"{tuner_color.r}, {tuner_color.g}, {tuner_color.b}"; - - var att = (JObject)jobj["attributes"]; - att["color"] = tuning["color"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } -} diff --git a/GameDev/AngleTuner.xaml b/GameDev/AngleTuner.xaml deleted file mode 100644 index 7c1f4ae8..00000000 --- a/GameDev/AngleTuner.xaml +++ /dev/null @@ -1,13 +0,0 @@ - - - 0.0 - - - diff --git a/GameDev/AngleTuner.xaml.cs b/GameDev/AngleTuner.xaml.cs deleted file mode 100644 index 9f789869..00000000 --- a/GameDev/AngleTuner.xaml.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Input; -using System.Windows.Controls; - -namespace GameDev -{ - /// - /// Interaction logic for AngleTuner.xaml - /// - public partial class AngleTuner : UserControl - { - private float _value = 0.0f; - public float value - { - get - { - return _value; - } - set - { - if (_value != value) - { - _value = value; - text.Text = _value.ToString(); - slider.Value = _value; - } - } - } - - public AngleTuner() - { - InitializeComponent(); - } - - public event EventHandler ValueChanged; - - private void update_value() - { - string str = text.Text; - float v = _value; - float.TryParse(str, out v); - while(v>180.0f) - { - v -= 360.0f; - } - while(v<-180.0f) - { - v += 360.0f; - } - if (v != _value) - { - value = v; - ValueChanged?.Invoke(this, null); - } - - } - - private void text_LostFocus(object sender, RoutedEventArgs e) - { - update_value(); - } - - private void text_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - update_value(); - } - } - - private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) - { - value = (float)slider.Value; - ValueChanged?.Invoke(this, null); - } - } -} diff --git a/GameDev/App.config b/GameDev/App.config deleted file mode 100644 index 56efbc7b..00000000 --- a/GameDev/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/GameDev/App.xaml b/GameDev/App.xaml deleted file mode 100644 index 07451d48..00000000 --- a/GameDev/App.xaml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/GameDev/App.xaml.cs b/GameDev/App.xaml.cs deleted file mode 100644 index 2830503d..00000000 --- a/GameDev/App.xaml.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Windows; - -namespace GameDev -{ - /// - /// Interaction logic for App.xaml - /// - public partial class App : Application - { - private MainWindow mainWnd = null; - - private void Application_Startup(object sender, StartupEventArgs e) - { - mainWnd = new MainWindow(); - this.MainWindow = mainWnd; - mainWnd.Show(); - } - - private void Application_Deactivated(object sender, EventArgs e) - { - if (mainWnd != null) - { - mainWnd.AppDeactivated(); - } - } - - private void Application_Activated(object sender, EventArgs e) - { - if (mainWnd != null) - { - mainWnd.AppActivated(); - } - } - } -} diff --git a/GameDev/BackgroundSceneTuner.xaml b/GameDev/BackgroundSceneTuner.xaml deleted file mode 100644 index a22136ec..00000000 --- a/GameDev/BackgroundSceneTuner.xaml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - Scene Path: - - - diff --git a/GameDev/ColorTuner.xaml.cs b/GameDev/ColorTuner.xaml.cs deleted file mode 100644 index c9cd2c50..00000000 --- a/GameDev/ColorTuner.xaml.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Windows.Controls; -using System.Windows.Media; - -namespace GameDev -{ - /// - /// Interaction logic for ColorTuner.xaml - /// - public partial class ColorTuner : UserControl - { - private float _r = 0.0f; - public float r - { - get - { - return _r; - } - set - { - if (_r != value) - { - _r = value; - update(); - } - } - } - - private float _g = 0.0f; - public float g - { - get - { - return _g; - } - set - { - if (_g != value) - { - _g = value; - update(); - } - } - } - - private float _b = 0.0f; - public float b - { - get - { - return _b; - } - set - { - if (_b != value) - { - _b = value; - update(); - } - } - } - - public void set_color(float r, float g, float b) - { - _r = r; - _g = g; - _b = b; - update(); - } - - private void update() - { - Color col = Color.FromScRgb(1.0f, r, g, b); - btn.Foreground = new SolidColorBrush(col); - } - - public ColorTuner() - { - InitializeComponent(); - } - - public event EventHandler ValueChanged; - - private void btn_Click(object sender, System.Windows.RoutedEventArgs e) - { - Color col_in = Color.FromScRgb(1.0f, r, g, b); - - var dlg = new System.Windows.Forms.ColorDialog(); - dlg.Color = System.Drawing.Color.FromArgb(col_in.A, col_in.R, col_in.G, col_in.B); - if (dlg.ShowDialog()== System.Windows.Forms.DialogResult.OK) - { - var col_dlg = dlg.Color; - Color col_out = Color.FromArgb(col_dlg.A, col_dlg.R, col_dlg.G, col_dlg.B); - set_color(col_out.ScR, col_out.ScG, col_out.ScB); - ValueChanged?.Invoke(this, null); - } - } - } -} diff --git a/GameDev/CubeSkyTuner.xaml b/GameDev/CubeSkyTuner.xaml deleted file mode 100644 index 5e3a91a7..00000000 --- a/GameDev/CubeSkyTuner.xaml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - File Path: - - - - File Name(+x): - - - - File Name(-x): - - - - File Name(+y): - - - - File Name(-y): - - - - File Name(+z): - - - - File Name(-z): - - - - - - - - - diff --git a/GameDev/CubeSkyTuner.xaml.cs b/GameDev/CubeSkyTuner.xaml.cs deleted file mode 100644 index 25f1761a..00000000 --- a/GameDev/CubeSkyTuner.xaml.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.IO; -using System.Windows; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; -using Microsoft.Win32; - -namespace GameDev -{ - /// - /// Interaction logic for CubeSkyTuner.xaml - /// - public partial class CubeSkyTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public CubeSkyTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - - file_path.Text = "assets/textures"; - if (att.ContainsKey("path")) - { - file_path.Text = att["path"].ToString(); - } - - name_posx.Text = "face0.jpg"; - if (att.ContainsKey("posx")) - { - name_posx.Text = att["posx"].ToString(); - } - - name_negx.Text = "face1.jpg"; - if (att.ContainsKey("negx")) - { - name_negx.Text = att["negx"].ToString(); - } - - name_posy.Text = "face2.jpg"; - if (att.ContainsKey("posy")) - { - name_posy.Text = att["posy"].ToString(); - } - - name_negy.Text = "face3.jpg"; - if (att.ContainsKey("negy")) - { - name_negy.Text = att["negy"].ToString(); - } - - name_posz.Text = "face4.jpg"; - if (att.ContainsKey("posz")) - { - name_posz.Text = att["posz"].ToString(); - } - - name_negz.Text = "face5.jpg"; - if (att.ContainsKey("negz")) - { - name_negz.Text = att["negz"].ToString(); - } - } - - private void reload() - { - JObject tuning = new JObject(); - tuning["path"] = file_path.Text; - tuning["posx"] = name_posx.Text; - tuning["negx"] = name_negx.Text; - tuning["posy"] = name_posy.Text; - tuning["negy"] = name_negy.Text; - tuning["posz"] = name_posz.Text; - tuning["negz"] = name_negz.Text; - - var att = (JObject)jobj["attributes"]; - att["path"] = tuning["path"]; - att["posx"] = tuning["posx"]; - att["negx"] = tuning["negx"]; - att["posy"] = tuning["posy"]; - att["negy"] = tuning["negy"]; - att["posz"] = tuning["posz"]; - att["negz"] = tuning["negz"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void btn_reload_Click(object sender, System.Windows.RoutedEventArgs e) - { - reload(); - } - - private void btn_browse_Click(object sender, System.Windows.RoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Multiselect = true; - dialog.Filter = "Images(*.jpg,*.png)|*.jpg;*.png"; - if (dialog.ShowDialog() != true) return; - - var mainwnd = Window.GetWindow(Application.Current.MainWindow) as MainWindow; - string cur_path = mainwnd.cur_path; - - if (dialog.FileNames.Length < 6) - { - MessageBox.Show("Exactly 6 files needed"); - return; - } - - string dir = Path.GetDirectoryName(dialog.FileNames[0]); - if (!dir.StartsWith(cur_path)) - { - MessageBox.Show("Failed to parse path"); - return; - } - - string rel_dir = dir.Substring(cur_path.Length + 1); - file_path.Text = rel_dir; - name_posx.Text = dialog.FileNames[0].Substring(dir.Length + 1); - name_negx.Text = dialog.FileNames[1].Substring(dir.Length + 1); - name_posy.Text = dialog.FileNames[2].Substring(dir.Length + 1); - name_negy.Text = dialog.FileNames[3].Substring(dir.Length + 1); - name_posz.Text = dialog.FileNames[4].Substring(dir.Length + 1); - name_negz.Text = dialog.FileNames[5].Substring(dir.Length + 1); - - reload(); - - } - } -} diff --git a/GameDev/DirectionalLightTuner.xaml b/GameDev/DirectionalLightTuner.xaml deleted file mode 100644 index a4bcc1ea..00000000 --- a/GameDev/DirectionalLightTuner.xaml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/GameDev/DirectionalLightTuner.xaml.cs b/GameDev/DirectionalLightTuner.xaml.cs deleted file mode 100644 index e720f834..00000000 --- a/GameDev/DirectionalLightTuner.xaml.cs +++ /dev/null @@ -1,272 +0,0 @@ -using System; -using System.Windows.Controls; -using System.Windows.Input; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for DirectionalLightTuner.xaml - /// - public partial class DirectionalLightTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public Object3DTuner obj3d_tuner = null; - bool initialized = false; - - public DirectionalLightTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - - tuner_intensity.step = 0.5f; - tuner_intensity.value = 1.0f; - - if (att.ContainsKey("intensity")) - { - tuner_intensity.value = float.Parse(att["intensity"].ToString()); - } - - float r = 1.0f; - float g = 1.0f; - float b = 1.0f; - if (att.ContainsKey("color")) - { - var color = att["color"].ToString().Split(','); - r = float.Parse(color[0]); - g = float.Parse(color[1]); - b = float.Parse(color[2]); - } - tuner_color.set_color(r, g, b); - - if (att.ContainsKey("target")) - { - text_target.Text = att["target"].ToString(); - } - - if (att.ContainsKey("castShadow")) - { - bool cast_shadow = att["castShadow"].ToObject(); - chk_cast_shadow.IsChecked = cast_shadow; - } - - tuner_width.value = 512; - tuner_width.step = 512; - tuner_height.value = 512; - tuner_height.step = 512; - if (att.ContainsKey("size")) - { - string size = att["size"].ToString(); - string[] values = size.Split(','); - tuner_width.value = float.Parse(values[0]); - tuner_height.value = float.Parse(values[1]); - } - - tuner_left.value = -1.0f; - tuner_right.value = 1.0f; - tuner_bottom.value = -1.0f; - tuner_top.value = 1.0f; - tuner_near.value = 0.0f; - tuner_far.value = 10.0f; - if (att.ContainsKey("area")) - { - string area = att["area"].ToString(); - string[] values = area.Split(','); - tuner_left.value = float.Parse(values[0]); - tuner_right.value = float.Parse(values[1]); - tuner_bottom.value = float.Parse(values[2]); - tuner_top.value = float.Parse(values[3]); - tuner_near.value = float.Parse(values[4]); - tuner_far.value = float.Parse(values[5]); - } - - tuner_radius.value = 0.0f; - tuner_radius.step = 0.05f; - if (att.ContainsKey("radius")) - { - tuner_radius.value = float.Parse(att["radius"].ToString()); - } - - tuner_bias.value = 0.001f; - tuner_bias.step = 0.001f; - if (att.ContainsKey("bias")) - { - tuner_bias.value = float.Parse(att["bias"].ToString()); - } - - bool force_cull = true; - if (att.ContainsKey("force_cull")) - { - force_cull = att["force_cull"].ToObject(); - } - chk_force_cull.IsChecked = force_cull; - - obj3d_tuner = new Object3DTuner(game_player, jobj); - stack.Children.Add(obj3d_tuner); - - obj3d_tuner.tuner_rot.IsEnabled = false; - obj3d_tuner.tuner_scale.IsEnabled = false; - - initialized = true; - } - - private void tuner_intensity_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["intensity"] = $"{tuner_intensity.value}"; - - var att = (JObject)jobj["attributes"]; - att["intensity"] = tuning["intensity"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_color_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["color"] = $"{tuner_color.r}, {tuner_color.g}, {tuner_color.b}"; - - var att = (JObject)jobj["attributes"]; - att["color"] = tuning["color"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void update_target() - { - JObject tuning = new JObject(); - tuning["target"] = text_target.Text; - - var att = (JObject)jobj["attributes"]; - att["target"] = tuning["target"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void text_target_LostFocus(object sender, System.Windows.RoutedEventArgs e) - { - update_target(); - } - - private void text_target_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) - { - if (e.Key == Key.Return) - { - update_target(); - } - } - - private void update_shadow() - { - JObject tuning = new JObject(); - var att = (JObject)jobj["attributes"]; - - tuning["castShadow"] = $"{chk_cast_shadow.IsChecked == true}"; - tuning["size"] = $"{tuner_width.value}, {tuner_height.value}"; - - att["castShadow"] = tuning["castShadow"]; - att["size"] = tuning["size"]; - - if (chk_cast_shadow.IsChecked == true) - { - tuning["area"] = $"{tuner_left.value}, {tuner_right.value}, {tuner_bottom.value}, {tuner_top.value}, {tuner_near.value}, {tuner_far.value}"; - tuning["radius"] = $"{tuner_radius.value}"; - tuning["bias"] = $"{tuner_bias.value}"; - tuning["force_cull"] = $"{chk_force_cull.IsChecked == true}"; - - att["area"] = tuning["area"]; - att["radius"] = tuning["radius"]; - } - - game_player.SendMessageToUser("tuning", tuning.ToString()); - - } - - private void chk_cast_shadow_Checked(object sender, System.Windows.RoutedEventArgs e) - { - grp_shadow.IsEnabled = chk_cast_shadow.IsChecked == true; - - if (initialized) - { - update_shadow(); - } - } - - private void tuner_size_ValueChanged(object sender, EventArgs e) - { - update_shadow(); - } - - private void tuner_area_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - var att = (JObject)jobj["attributes"]; - - tuning["area"] = $"{tuner_left.value}, {tuner_right.value}, {tuner_bottom.value}, {tuner_top.value}, {tuner_near.value}, {tuner_far.value}"; - att["area"] = tuning["area"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_radius_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - var att = (JObject)jobj["attributes"]; - - tuning["radius"] = $"{tuner_radius.value}"; - att["radius"] = tuning["radius"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - - } - - private void tuner_bias_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - var att = (JObject)jobj["attributes"]; - - tuning["bias"] = $"{tuner_bias.value}"; - att["bias"] = tuning["bias"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void btn_auto_detect_Click(object sender, System.Windows.RoutedEventArgs e) - { - JObject tuning = new JObject(); - tuning["auto_area"] = "auto"; - var ret = JObject.Parse(game_player.SendMessageToUser("tuning", tuning.ToString())); - - var att = (JObject)jobj["attributes"]; - att["area"] = ret["area"]; - string area = ret["area"].ToString(); - string[] values = area.Split(','); - tuner_left.value = float.Parse(values[0]); - tuner_right.value = float.Parse(values[1]); - tuner_bottom.value = float.Parse(values[2]); - tuner_top.value = float.Parse(values[3]); - tuner_near.value = float.Parse(values[4]); - tuner_far.value = float.Parse(values[5]); - } - - private void chk_force_cull_Checked(object sender, System.Windows.RoutedEventArgs e) - { - if (initialized) - { - JObject tuning = new JObject(); - var att = (JObject)jobj["attributes"]; - - tuning["force_cull"] = $"{chk_force_cull.IsChecked == true}"; - att["force_cull"] = tuning["force_cull"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } - } -} diff --git a/GameDev/DlgEditTarget.xaml b/GameDev/DlgEditTarget.xaml deleted file mode 100644 index 64dda2f8..00000000 --- a/GameDev/DlgEditTarget.xaml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - Name: - - - - Input File: - - - - - Output File: - - - - Default Size: - - x - - - - - diff --git a/GameDev/DlgEditTarget.xaml.cs b/GameDev/DlgEditTarget.xaml.cs deleted file mode 100644 index d9536cc6..00000000 --- a/GameDev/DlgEditTarget.xaml.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Windows; -using Microsoft.Win32; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for DlgEditTarget.xaml - /// - public partial class DlgEditTarget : Window - { - private string root; - public JObject jTarget; - - public DlgEditTarget(Window owner, JObject jTarget, string root) - { - this.root = root; - this.Owner = owner; - InitializeComponent(); - - if (jTarget != null ) - { - Title = "Edit Target"; - this.jTarget = jTarget; - } - else - { - Title = "Add Target"; - this.jTarget = new JObject(); - this.jTarget["name"] = "Target"; - this.jTarget["input"] = "index.js"; - this.jTarget["output"] = "bundle_index.js"; - this.jTarget["dirty"] = true; - } - - text_name.Text = this.jTarget["name"].ToString(); - text_input.Text = this.jTarget["input"].ToString(); - text_output.Text = this.jTarget["output"].ToString(); - - if (this.jTarget.ContainsKey("width")) - { - text_width.Text = this.jTarget["width"].ToString(); - } - - if (this.jTarget.ContainsKey("height")) - { - text_height.Text = this.jTarget["height"].ToString(); - } - } - - private void btn_ok_Click(object sender, RoutedEventArgs e) - { - if (text_name.Text == "" || text_input.Text == "") return; - jTarget["name"] = text_name.Text; - jTarget["input"] = text_input.Text; - jTarget["output"] = text_output.Text; - - int width = -1; - int.TryParse(text_width.Text, out width); - if (width > 0) - { - jTarget["width"] = width; - } - else if (jTarget.ContainsKey("width")) - { - jTarget.Remove("width"); - } - - int height = -1; - int.TryParse(text_height.Text, out height); - if (height>0) - { - jTarget["height"] = height; - } - else if (jTarget.ContainsKey("height")) - { - jTarget.Remove("height"); - } - - DialogResult = true; - } - - private void text_input_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) - { - if (!text_input.Text.EndsWith(".js")) - { - int idx = text_input.CaretIndex; - if (text_input.Text.EndsWith(".j")) - { - text_input.Text += "s"; - } - else if (text_input.Text.EndsWith(".")) - { - text_input.Text += "js"; - } - else - { - text_input.Text += ".js"; - } - text_input.CaretIndex = idx; - } - text_output.Text = "bundle_" + text_input.Text; - } - - private void btn_browse_Click(object sender, RoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Filter = "JavaScript(*.js)|*.js"; - if (dialog.ShowDialog() != true) return; - if (dialog.FileName.StartsWith(root)) - { - text_input.Text = dialog.FileName.Substring(root.Length + 1); - } - else - { - MessageBox.Show("File out of project scope: " + dialog.FileName, "Wrong file", MessageBoxButton.OK, MessageBoxImage.Warning); - } - } - } -} diff --git a/GameDev/DlgNewDir.xaml b/GameDev/DlgNewDir.xaml deleted file mode 100644 index b6b003f1..00000000 --- a/GameDev/DlgNewDir.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - Directory name: - - - - diff --git a/GameDev/DlgNewDir.xaml.cs b/GameDev/DlgNewDir.xaml.cs deleted file mode 100644 index 93b71475..00000000 --- a/GameDev/DlgNewDir.xaml.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Media; - - -namespace GameDev -{ - /// - /// Interaction logic for DlgNewDir.xaml - /// - public partial class DlgNewDir : Window - { - public string filename; - - public DlgNewDir(Window owner) - { - this.Owner = owner; - InitializeComponent(); - } - - private void btn_ok_Click(object sender, RoutedEventArgs e) - { - if (text_filename.Text == "") return; - filename = text_filename.Text; - DialogResult = true; - } - } -} diff --git a/GameDev/DlgNewFile.xaml b/GameDev/DlgNewFile.xaml deleted file mode 100644 index 00c92291..00000000 --- a/GameDev/DlgNewFile.xaml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - Type: - - - - - JavaScript - - - - - - XML - - - - - - Json - - - - File name: - - - - - diff --git a/GameDev/DlgNewFile.xaml.cs b/GameDev/DlgNewFile.xaml.cs deleted file mode 100644 index 7435bf19..00000000 --- a/GameDev/DlgNewFile.xaml.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Windows; - -namespace GameDev -{ - /// - /// Interaction logic for DlgNewFile.xaml - /// - public partial class DlgNewFile : Window - { - private string[] type_names = new string[] { "js", "xml", "json" }; - private string[] default_filenames = new string[] { "index.js", "scene.xml", "data.json" }; - private bool initialized = false; - - public string typename; - public string filename; - - public DlgNewFile(Window owner) - { - this.Owner = owner; - InitializeComponent(); - initialized = true; - } - - private void btn_ok_Click(object sender, RoutedEventArgs e) - { - if (lst_types.SelectedIndex < 0) return; - if (text_filename.Text == "") return; - typename = type_names[lst_types.SelectedIndex]; - filename = text_filename.Text; - DialogResult = true; - } - - private void ListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) - { - if (!initialized || lst_types.SelectedIndex < 0) return; - text_filename.Text = default_filenames[lst_types.SelectedIndex]; - } - } -} diff --git a/GameDev/DlgProjectSettings.xaml b/GameDev/DlgProjectSettings.xaml deleted file mode 100644 index 3084272e..00000000 --- a/GameDev/DlgProjectSettings.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - Project Name: - - - - diff --git a/GameDev/DlgProjectSettings.xaml.cs b/GameDev/DlgProjectSettings.xaml.cs deleted file mode 100644 index e6bdb98d..00000000 --- a/GameDev/DlgProjectSettings.xaml.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Windows; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for DlgProjectSettings.xaml - /// - public partial class DlgProjectSettings : Window - { - private JObject projectData; - - public DlgProjectSettings(Window owner, JObject projectData) - { - this.Owner = owner; - InitializeComponent(); - this.projectData = projectData; - text_project_name.Text = projectData["project_name"].ToString(); - } - - private void btn_ok_Click(object sender, RoutedEventArgs e) - { - if (text_project_name.Text=="") return; - projectData["project_name"] = text_project_name.Text; - DialogResult = true; - } - - } -} diff --git a/GameDev/Editor.cs b/GameDev/Editor.cs deleted file mode 100644 index 6bf3f304..00000000 --- a/GameDev/Editor.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace GameDev -{ - internal interface EditorBase - { - void cleanup(); - Task doc_close(); - } - - internal interface Editor : EditorBase - { - Task doc_save_as(); - Task doc_save(); - Task doc_fresh(); - - void undo(); - void redo(); - void comment(); - void upper(); - void lower(); - void find(); - void findnext(); - void findprev(); - void replace(); - void gotoline(); - - } -} diff --git a/GameDev/EnvLightTuner.xaml b/GameDev/EnvLightTuner.xaml deleted file mode 100644 index 7736e48a..00000000 --- a/GameDev/EnvLightTuner.xaml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - Uniform - Hemisphere - Cube - Probe-Grid - LOD Probe-Grid - - - - - - - diff --git a/GameDev/EnvLightTuner.xaml.cs b/GameDev/EnvLightTuner.xaml.cs deleted file mode 100644 index c14b5069..00000000 --- a/GameDev/EnvLightTuner.xaml.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for EnvLightTuner.xaml - /// - public partial class EnvLightTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - private bool initialized = false; - - public EnvLightTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - - if (att.ContainsKey("dynamic_map")) - { - bool dynamic_map = att["dynamic_map"].ToObject(); - chk_dynamic.IsChecked = dynamic_map; - } - - string type = "hemisphere"; - if (att.ContainsKey("type")) - { - type = att["type"].ToString(); - } - - if (type == "uniform") - { - lst_types.SelectedIndex = 0; - } - else if (type == "hemisphere") - { - lst_types.SelectedIndex = 1; - } - else if (type == "cube") - { - lst_types.SelectedIndex = 2; - } - else if (type == "probe_grid") - { - lst_types.SelectedIndex = 3; - } - else if (type == "lod_probe_grid") - { - lst_types.SelectedIndex = 4; - } - load_type(type); - - initialized = true; - } - - private void load_type(string type) - { - property_area.Children.Clear(); - if (type == "uniform") - { - var tuner = new AmbientLightTuner(game_player, jobj); - property_area.Children.Add(tuner); - } - else if (type == "hemisphere") - { - var tuner = new HemisphereLightTuner(game_player, jobj); - property_area.Children.Add(tuner); - } - else if (type == "cube") - { - var tuner = new EnvMapTuner(game_player, jobj); - property_area.Children.Add(tuner); - } - else if (type == "probe_grid") - { - var tuner = new ProbeGridTuner(game_player, jobj); - property_area.Children.Add(tuner); - } - else if (type == "lod_probe_grid") - { - var tuner = new LODProbeGridTuner(game_player, jobj); - property_area.Children.Add(tuner); - } - } - - private void lst_types_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - if (!initialized) return; - if (lst_types.SelectedIndex < 0) return; - - string type = ((ComboBoxItem)lst_types.SelectedItem).Tag.ToString(); - - var att = (JObject)jobj["attributes"]; - att.RemoveAll(); - att["type"] = type; - - jobj["attributes"] = JObject.Parse(game_player.SendMessageToUser("tuning", att.ToString())); - load_type(type); - - } - - private void chk_dynamic_Checked(object sender, System.Windows.RoutedEventArgs e) - { - if (initialized) - { - JObject tuning = new JObject(); - tuning["dynamic_map"] = $"{chk_dynamic.IsChecked == true}"; - - var att = (JObject)jobj["attributes"]; - att["dynamic_map"] = tuning["dynamic_map"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } - } -} diff --git a/GameDev/EnvMapTuner.xaml b/GameDev/EnvMapTuner.xaml deleted file mode 100644 index 68f9842e..00000000 --- a/GameDev/EnvMapTuner.xaml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - File Path: - - - - File Name(+x): - - - - File Name(-x): - - - - File Name(+y): - - - - File Name(-y): - - - - File Name(+z): - - - - File Name(-z): - - - - - - - - - - - diff --git a/GameDev/EnvMapTuner.xaml.cs b/GameDev/EnvMapTuner.xaml.cs deleted file mode 100644 index a9fa81a2..00000000 --- a/GameDev/EnvMapTuner.xaml.cs +++ /dev/null @@ -1,260 +0,0 @@ -using System; -using System.IO; -using System.Windows; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; -using Microsoft.Win32; -using System.Windows.Input; - -namespace GameDev -{ - /// - /// Interaction logic for EnvMapTuner.xaml - /// - public partial class EnvMapTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - private bool initialized = false; - - public EnvMapTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - tuner_probe_pos.tuner_x.step = 0.5f; - tuner_probe_pos.tuner_y.step = 0.5f; - tuner_probe_pos.tuner_z.step = 0.5f; - - var att = (JObject)jobj["attributes"]; - - if (att.ContainsKey("irradiance_only")) - { - bool irradiance_only = att["irradiance_only"].ToObject(); - chk_irr_only.IsChecked = irradiance_only; - grp_cubemap.IsEnabled = !irradiance_only; - grp_sh.IsEnabled = irradiance_only; - } - - file_path.Text = "assets/textures"; - if (att.ContainsKey("path")) - { - file_path.Text = att["path"].ToString(); - } - - name_posx.Text = "env_face0.jpg"; - if (att.ContainsKey("posx")) - { - name_posx.Text = att["posx"].ToString(); - } - - name_negx.Text = "env_face1.jpg"; - if (att.ContainsKey("negx")) - { - name_negx.Text = att["negx"].ToString(); - } - - name_posy.Text = "env_face2.jpg"; - if (att.ContainsKey("posy")) - { - name_posy.Text = att["posy"].ToString(); - } - - name_negy.Text = "env_face3.jpg"; - if (att.ContainsKey("negy")) - { - name_negy.Text = att["negy"].ToString(); - } - - name_posz.Text = "env_face4.jpg"; - if (att.ContainsKey("posz")) - { - name_posz.Text = att["posz"].ToString(); - } - - name_negz.Text = "env_face5.jpg"; - if (att.ContainsKey("negz")) - { - name_negz.Text = att["negz"].ToString(); - } - - fn_sh.Text = "assets/sh.json"; - if (att.ContainsKey("path_sh")) - { - fn_sh.Text = att["path_sh"].ToString(); - } - - if (att.ContainsKey("probe_position")) - { - string probe_position = att["probe_position"].ToString(); - string[] values = probe_position.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_probe_pos.set_value(x, y, z); - } - initialized = true; - } - - private void tuner_probe_pos_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["probe_position"] = $"{tuner_probe_pos.x},{tuner_probe_pos.y},{tuner_probe_pos.z}"; - - var att = (JObject)jobj["attributes"]; - att["probe_position"] = tuning["probe_position"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void reload() - { - JObject tuning = new JObject(); - tuning["path"] = file_path.Text; - tuning["posx"] = name_posx.Text; - tuning["negx"] = name_negx.Text; - tuning["posy"] = name_posy.Text; - tuning["negy"] = name_negy.Text; - tuning["posz"] = name_posz.Text; - tuning["negz"] = name_negz.Text; - - var att = (JObject)jobj["attributes"]; - att["path"] = tuning["path"]; - att["posx"] = tuning["posx"]; - att["negx"] = tuning["negx"]; - att["posy"] = tuning["posy"]; - att["negy"] = tuning["negy"]; - att["posz"] = tuning["posz"]; - att["negz"] = tuning["negz"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void btn_reload_Click(object sender, System.Windows.RoutedEventArgs e) - { - reload(); - } - - private void btn_generate_Click(object sender, System.Windows.RoutedEventArgs e) - { - JObject tuning = new JObject(); - tuning["path"] = file_path.Text; - tuning["posx"] = name_posx.Text; - tuning["negx"] = name_negx.Text; - tuning["posy"] = name_posy.Text; - tuning["negy"] = name_negy.Text; - tuning["posz"] = name_posz.Text; - tuning["negz"] = name_negz.Text; - - var att = (JObject)jobj["attributes"]; - att["path"] = tuning["path"]; - att["posx"] = tuning["posx"]; - att["negx"] = tuning["negx"]; - att["posy"] = tuning["posy"]; - att["negy"] = tuning["negy"]; - att["posz"] = tuning["posz"]; - att["negz"] = tuning["negz"]; - game_player.SendMessageToUser("generate", tuning.ToString()); - } - - private void btn_browse_Click(object sender, System.Windows.RoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Multiselect = true; - dialog.Filter = "Images(*.jpg,*.png,*.hdr)|*.jpg;*.png;*.hdr"; - if (dialog.ShowDialog() != true) return; - - var mainwnd = Window.GetWindow(Application.Current.MainWindow) as MainWindow; - string cur_path = mainwnd.cur_path; - - if (dialog.FileNames.Length<6) - { - MessageBox.Show("Exactly 6 files needed"); - return; - } - - string dir = Path.GetDirectoryName(dialog.FileNames[0]); - if (!dir.StartsWith(cur_path)) - { - MessageBox.Show("Failed to parse path"); - return; - } - - string rel_dir = dir.Substring(cur_path.Length + 1); - file_path.Text = rel_dir; - name_posx.Text = dialog.FileNames[0].Substring(dir.Length + 1); - name_negx.Text = dialog.FileNames[1].Substring(dir.Length + 1); - name_posy.Text = dialog.FileNames[2].Substring(dir.Length + 1); - name_negy.Text = dialog.FileNames[3].Substring(dir.Length + 1); - name_posz.Text = dialog.FileNames[4].Substring(dir.Length + 1); - name_negz.Text = dialog.FileNames[5].Substring(dir.Length + 1); - - reload(); - - } - - private void load_sh() - { - JObject tuning = new JObject(); - tuning["path_sh"] = fn_sh.Text; - - var att = (JObject)jobj["attributes"]; - att["path_sh"] = tuning["path_sh"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void text_LostFocus(object sender, System.Windows.RoutedEventArgs e) - { - load_sh(); - } - - private void text_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - load_sh(); - } - } - - private void btn_browse_sh_Click(object sender, RoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Filter = "JSON(*.json)"; - if (dialog.ShowDialog() != true) return; - - var mainwnd = Window.GetWindow(Application.Current.MainWindow) as MainWindow; - string cur_path = mainwnd.cur_path; - - string path = dialog.FileName; - if (!path.StartsWith(cur_path)) - { - MessageBox.Show("Failed to parse path"); - return; - } - - string rel_path = path.Substring(cur_path.Length + 1); - fn_sh.Text = rel_path; - load_sh(); - } - - private void chk_irr_only_Checked(object sender, RoutedEventArgs e) - { - if (!initialized) return; - - bool irradiance_only = chk_irr_only.IsChecked== true; - grp_cubemap.IsEnabled = !irradiance_only; - grp_sh.IsEnabled = irradiance_only; - - JObject tuning = new JObject(); - tuning["irradiance_only"] = $"{irradiance_only}"; - - var att = (JObject)jobj["attributes"]; - att["irradiance_only"] = tuning["irradiance_only"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } -} diff --git a/GameDev/FogTuner.xaml b/GameDev/FogTuner.xaml deleted file mode 100644 index 7537150a..00000000 --- a/GameDev/FogTuner.xaml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - diff --git a/GameDev/FogTuner.xaml.cs b/GameDev/FogTuner.xaml.cs deleted file mode 100644 index ab2fad1c..00000000 --- a/GameDev/FogTuner.xaml.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for FogTuner.xaml - /// - public partial class FogTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public FogTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - tuner_density.exponential = true; - - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - - tuner_density.exponential = true; - tuner_density.step = 1.1f; - tuner_density.value = 0.1f; - - if (att.ContainsKey("density")) - { - tuner_density.value = float.Parse(att["density"].ToString()); - } - - float r = 1.0f; - float g = 1.0f; - float b = 1.0f; - if (att.ContainsKey("color")) - { - var color = att["color"].ToString().Split(','); - r = float.Parse(color[0]); - g = float.Parse(color[1]); - b = float.Parse(color[2]); - } - tuner_color.set_color(r, g, b); - } - - private void tuner_density_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["density"] = $"{tuner_density.value}"; - - var att = (JObject)jobj["attributes"]; - att["density"] = tuning["density"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_color_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["color"] = $"{tuner_color.r}, {tuner_color.g}, {tuner_color.b}"; - - var att = (JObject)jobj["attributes"]; - att["color"] = tuning["color"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } -} diff --git a/GameDev/GameDev.csproj b/GameDev/GameDev.csproj deleted file mode 100644 index 2fb54b3d..00000000 --- a/GameDev/GameDev.csproj +++ /dev/null @@ -1,434 +0,0 @@ - - - - - Debug - AnyCPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1} - WinExe - GameDev - GameDev - v4.7.2 - 512 - {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 4 - true - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x64 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - 4.0 - - - - - - - - - MSBuild:Compile - Designer - - - AmbientLightTuner.xaml - - - AngleTuner.xaml - - - BackgroundSceneTuner.xaml - - - BoxTuner.xaml - - - ColorTuner.xaml - - - CubeSkyTuner.xaml - - - DirectionalLightTuner.xaml - - - DlgNewDir.xaml - - - EnvLightTuner.xaml - - - EnvMapTuner.xaml - - - FogTuner.xaml - - - GroupTuner.xaml - - - - HelpPage.xaml - - - HemisphereLightTuner.xaml - - - HemisphereSkyTuner.xaml - - - LODProbeGridTuner.xaml - - - ModelTuner.xaml - - - NumberTuner.xaml - - - Object3DTuner.xaml - - - PlaneTuner.xaml - - - ProbeGridTuner.xaml - - - RotationTuner.xaml - - - ScaleTuner.xaml - - - SceneTuner.xaml - - - SimpleMaterialTuner.xaml - - - SkyTuner.xaml - - - SphereTuner.xaml - - - UniformSkyTuner.xaml - - - Vec3Tuner.xaml - - - XMLEditor.xaml - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - App.xaml - Code - - - DlgEditTarget.xaml - - - DlgNewFile.xaml - - - DlgProjectSettings.xaml - - - - JSEditor.xaml - - - - JsonEditor.xaml - - - MainWindow.xaml - Code - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - - - Code - - - True - True - Resources.resx - - - True - Settings.settings - True - - - ResXFileCodeGenerator - Resources.Designer.cs - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - - - - - - - - - - - - - - - - 1.0.1518.46 - - - 13.0.2 - - - - - - - - - - - {8accb6bd-c7b1-4a80-91d5-53cf222b716a} - Three.V8.CLR - - - - - {F935DC20-1CF0-11D0-ADB9-00C04FD58A0B} - 1 - 0 - 0 - tlbimp - False - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/GameDev/GroupTuner.xaml b/GameDev/GroupTuner.xaml deleted file mode 100644 index 2bce8378..00000000 --- a/GameDev/GroupTuner.xaml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - diff --git a/GameDev/GroupTuner.xaml.cs b/GameDev/GroupTuner.xaml.cs deleted file mode 100644 index b4d58566..00000000 --- a/GameDev/GroupTuner.xaml.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - - -namespace GameDev -{ - /// - /// Interaction logic for GroupTuner.xaml - /// - public partial class GroupTuner : UserControl - { - public Object3DTuner obj3d_tuner = null; - - public GroupTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - obj3d_tuner = new Object3DTuner(game_player, jobj); - stack.Children.Add(obj3d_tuner); - } - } -} diff --git a/GameDev/HackedTabControl.cs b/GameDev/HackedTabControl.cs deleted file mode 100644 index d83625a8..00000000 --- a/GameDev/HackedTabControl.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Windows.Controls; -using System.Windows.Input; - -namespace GameDev -{ - internal class HackedTabControl : TabControl - { - protected override void OnKeyDown(KeyEventArgs e) - { - - } - } -} diff --git a/GameDev/HelpPage.xaml b/GameDev/HelpPage.xaml deleted file mode 100644 index f93dd55d..00000000 --- a/GameDev/HelpPage.xaml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - diff --git a/GameDev/HelpPage.xaml.cs b/GameDev/HelpPage.xaml.cs deleted file mode 100644 index 6bcd616b..00000000 --- a/GameDev/HelpPage.xaml.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Text; -using System.IO; -using System.Diagnostics; -using System.Windows.Controls; -using System.Threading.Tasks; -using Newtonsoft.Json; -using System.Windows; -using Microsoft.Win32; -using System.Windows.Shapes; - -namespace GameDev -{ - /// - /// Interaction logic for HelpPage.xaml - /// - public partial class HelpPage : UserControl, EditorBase - { - public HelpPage(string path) - { - InitializeComponent(); - webView.Source = new Uri(path); - } - - public void Goto(string path) - { - webView.Source = new Uri(path); - } - - public void cleanup() - { - - } - - public async Task doc_close() - { - return true; - } - } -} diff --git a/GameDev/HemisphereLightTuner.xaml b/GameDev/HemisphereLightTuner.xaml deleted file mode 100644 index 423118ce..00000000 --- a/GameDev/HemisphereLightTuner.xaml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/GameDev/HemisphereLightTuner.xaml.cs b/GameDev/HemisphereLightTuner.xaml.cs deleted file mode 100644 index 8293b6b6..00000000 --- a/GameDev/HemisphereLightTuner.xaml.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for HemisphereLightTuner.xaml - /// - public partial class HemisphereLightTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public HemisphereLightTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - - { - float r = 0.318f; - float g = 0.318f; - float b = 0.318f; - if (att.ContainsKey("skyColor")) - { - var color = att["skyColor"].ToString().Split(','); - r = float.Parse(color[0]); - g = float.Parse(color[1]); - b = float.Parse(color[2]); - } - tuner_sky_color.set_color(r, g, b); - } - { - float r = 0.01f; - float g = 0.025f; - float b = 0.025f; - if (att.ContainsKey("groundColor")) - { - var color = att["groundColor"].ToString().Split(','); - r = float.Parse(color[0]); - g = float.Parse(color[1]); - b = float.Parse(color[2]); - } - tuner_ground_color.set_color(r, g, b); - } - } - - private void tuner_sky_color_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["skyColor"] = $"{tuner_sky_color.r}, {tuner_sky_color.g}, {tuner_sky_color.b}"; - - var att = (JObject)jobj["attributes"]; - att["skyColor"] = tuning["skyColor"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_ground_color_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["groundColor"] = $"{tuner_ground_color.r}, {tuner_ground_color.g}, {tuner_ground_color.b}"; - - var att = (JObject)jobj["attributes"]; - att["groundColor"] = tuning["groundColor"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } -} diff --git a/GameDev/HemisphereSkyTuner.xaml b/GameDev/HemisphereSkyTuner.xaml deleted file mode 100644 index 2bc26988..00000000 --- a/GameDev/HemisphereSkyTuner.xaml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/GameDev/HemisphereSkyTuner.xaml.cs b/GameDev/HemisphereSkyTuner.xaml.cs deleted file mode 100644 index 767546c8..00000000 --- a/GameDev/HemisphereSkyTuner.xaml.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for HemisphereSkyTuner.xaml - /// - public partial class HemisphereSkyTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public HemisphereSkyTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - - { - float r = 0.318f; - float g = 0.318f; - float b = 0.318f; - if (att.ContainsKey("skyColor")) - { - var color = att["skyColor"].ToString().Split(','); - r = float.Parse(color[0]); - g = float.Parse(color[1]); - b = float.Parse(color[2]); - } - tuner_sky_color.set_color(r, g, b); - } - { - float r = 0.01f; - float g = 0.025f; - float b = 0.025f; - if (att.ContainsKey("groundColor")) - { - var color = att["groundColor"].ToString().Split(','); - r = float.Parse(color[0]); - g = float.Parse(color[1]); - b = float.Parse(color[2]); - } - tuner_ground_color.set_color(r, g, b); - } - - } - - private void tuner_sky_color_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["skyColor"] = $"{tuner_sky_color.r}, {tuner_sky_color.g}, {tuner_sky_color.b}"; - - var att = (JObject)jobj["attributes"]; - att["skyColor"] = tuning["skyColor"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_ground_color_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["groundColor"] = $"{tuner_ground_color.r}, {tuner_ground_color.g}, {tuner_ground_color.b}"; - - var att = (JObject)jobj["attributes"]; - att["groundColor"] = tuning["groundColor"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } -} diff --git a/GameDev/JSEditor.xaml b/GameDev/JSEditor.xaml deleted file mode 100644 index b02f8666..00000000 --- a/GameDev/JSEditor.xaml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - diff --git a/GameDev/JSEditor.xaml.cs b/GameDev/JSEditor.xaml.cs deleted file mode 100644 index d84997e8..00000000 --- a/GameDev/JSEditor.xaml.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Text; -using System.IO; -using System.Diagnostics; -using System.Windows.Controls; -using System.Threading.Tasks; -using Newtonsoft.Json; -using System.Windows; -using Microsoft.Win32; - -namespace GameDev -{ - /// - /// Interaction logic for JSEditor.xaml - /// - public partial class JSEditor : UserControl, Editor - { - private string file_path; - public JSEditor(string file_path) - { - InitializeComponent(); - this.file_path = file_path; - - string local_path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); - webView.Source = new Uri($"{local_path}/editor/js_editor.html"); - webView.NavigationCompleted += (sender, e) => - { - _doc_open(file_path); - }; - } - - public void cleanup() - { - - } - - private async Task _doc_save(string filename) - { - string text = await GetText(); - File.WriteAllText(filename, text, Encoding.UTF8); - } - - private void _doc_open(string filename) - { - string text = File.ReadAllText(filename, Encoding.UTF8); - SetText(text); - } - - public async Task doc_save_as() - { - var dialog = new SaveFileDialog(); - dialog.Filter = "Javascript(*.js)|*.js"; - if (dialog.ShowDialog() != true) - { - return ""; - } - file_path = dialog.FileName; - await _doc_save(file_path); - return file_path; - } - - public async Task doc_save() - { - await _doc_save(file_path); - } - - public async Task doc_close() - { - bool changed = await TextChanged(); - if (changed) - { - var result = MessageBox.Show("File has been modified. Save it?", "Save file", MessageBoxButton.YesNoCancel); - if (result == MessageBoxResult.Yes) - { - doc_save(); - return true; - } - else if (result == MessageBoxResult.No) - { - return true; - } - else - { - return false; - } - } - else - { - return true; - } - } - - public async Task doc_fresh() - { - if (await doc_close()) - { - _doc_open(file_path); - } - - } - - - private async Task TextChanged() - { - string response = await webView.ExecuteScriptAsync("doc_modified()"); - return (bool)JsonConvert.DeserializeObject(response); - } - - private async Task GetText() - { - string response = await webView.ExecuteScriptAsync("doc_get_text()"); - return JsonConvert.DeserializeObject(response).ToString(); - } - - private async void SetText(string text) - { - string para = JsonConvert.SerializeObject(text); - await webView.ExecuteScriptAsync($"doc_set_text({para})"); - } - - - public void undo() - { - webView.ExecuteScriptAsync("editor.execCommand('undo');"); - } - - public void redo() - { - webView.ExecuteScriptAsync("editor.execCommand('redo');"); - } - - public void comment() - { - webView.ExecuteScriptAsync("editor.execCommand('togglecomment');"); - } - - public void upper() - { - webView.ExecuteScriptAsync("editor.execCommand('touppercase');"); - } - - public void lower() - { - webView.ExecuteScriptAsync("editor.execCommand('tolowercase');"); - } - - public void find() - { - webView.ExecuteScriptAsync("editor.execCommand('find');"); - } - - public void findnext() - { - webView.ExecuteScriptAsync("editor.execCommand('findnext');"); - } - - public void findprev() - { - webView.ExecuteScriptAsync("editor.execCommand('findprevious');"); - } - - public void replace() - { - webView.ExecuteScriptAsync("editor.execCommand('replace');"); - } - - public void gotoline() - { - webView.ExecuteScriptAsync("editor.execCommand('gotoline');"); - } - } -} diff --git a/GameDev/JsonData.cs b/GameDev/JsonData.cs deleted file mode 100644 index 9b575666..00000000 --- a/GameDev/JsonData.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.IO; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - public class JsonData - { - public String filename = ""; - public JToken data = null; - - public void Clear() - { - filename = ""; - data = null; - } - - public void Load() - { - data = JToken.Parse(File.ReadAllText(filename)); - } - - public void Save() - { - File.WriteAllText(filename, data.ToString()); - } - - } -} diff --git a/GameDev/JsonEditor.xaml b/GameDev/JsonEditor.xaml deleted file mode 100644 index 0a1162bd..00000000 --- a/GameDev/JsonEditor.xaml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - diff --git a/GameDev/JsonEditor.xaml.cs b/GameDev/JsonEditor.xaml.cs deleted file mode 100644 index bd4ae1cb..00000000 --- a/GameDev/JsonEditor.xaml.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Text; -using System.IO; -using System.Diagnostics; -using System.Windows.Controls; -using System.Threading.Tasks; -using Newtonsoft.Json; -using System.Windows; -using Microsoft.Win32; - -namespace GameDev -{ - /// - /// Interaction logic for JsonEditor.xaml - /// - public partial class JsonEditor : UserControl, Editor - { - private string file_path; - public JsonEditor(string file_path) - { - InitializeComponent(); - this.file_path = file_path; - - string local_path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); - webView.Source = new Uri($"{local_path}/editor/json_editor.html"); - webView.NavigationCompleted += (sender, e) => - { - _doc_open(file_path); - }; - } - - public void cleanup() - { - - } - - private async Task _doc_save(string filename) - { - string text = await GetText(); - File.WriteAllText(filename, text, Encoding.UTF8); - } - - private void _doc_open(string filename) - { - string text = File.ReadAllText(filename, Encoding.UTF8); - SetText(text); - } - - public async Task doc_save_as() - { - var dialog = new SaveFileDialog(); - dialog.Filter = "JSON(*.json)|*.json"; - if (dialog.ShowDialog() != true) - { - return ""; - } - file_path = dialog.FileName; - await _doc_save(file_path); - return file_path; - } - - public async Task doc_save() - { - await _doc_save(file_path); - } - - public async Task doc_close() - { - bool changed = await TextChanged(); - if (changed) - { - var result = MessageBox.Show("File has been modified. Save it?", "Save file", MessageBoxButton.YesNoCancel); - if (result == MessageBoxResult.Yes) - { - doc_save(); - return true; - } - else if (result == MessageBoxResult.No) - { - return true; - } - else - { - return false; - } - } - else - { - return true; - } - } - - public async Task doc_fresh() - { - if (await doc_close()) - { - _doc_open(file_path); - } - - } - - - private async Task TextChanged() - { - string response = await webView.ExecuteScriptAsync("doc_modified()"); - return (bool)JsonConvert.DeserializeObject(response); - } - - private async Task GetText() - { - string response = await webView.ExecuteScriptAsync("doc_get_text()"); - return JsonConvert.DeserializeObject(response).ToString(); - } - - private async void SetText(string text) - { - string para = JsonConvert.SerializeObject(text); - await webView.ExecuteScriptAsync($"doc_set_text({para})"); - } - - - public void undo() - { - webView.ExecuteScriptAsync("editor.execCommand('undo');"); - } - - public void redo() - { - webView.ExecuteScriptAsync("editor.execCommand('redo');"); - } - - public void comment() - { - webView.ExecuteScriptAsync("editor.execCommand('togglecomment');"); - } - - public void upper() - { - webView.ExecuteScriptAsync("editor.execCommand('touppercase');"); - } - - public void lower() - { - webView.ExecuteScriptAsync("editor.execCommand('tolowercase');"); - } - - public void find() - { - webView.ExecuteScriptAsync("editor.execCommand('find');"); - } - - public void findnext() - { - webView.ExecuteScriptAsync("editor.execCommand('findnext');"); - } - - public void findprev() - { - webView.ExecuteScriptAsync("editor.execCommand('findprevious');"); - } - - public void replace() - { - webView.ExecuteScriptAsync("editor.execCommand('replace');"); - } - - public void gotoline() - { - webView.ExecuteScriptAsync("editor.execCommand('gotoline');"); - } - } -} diff --git a/GameDev/LODProbeGridTuner.xaml b/GameDev/LODProbeGridTuner.xaml deleted file mode 100644 index c053dd57..00000000 --- a/GameDev/LODProbeGridTuner.xaml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/GameDev/LODProbeGridTuner.xaml.cs b/GameDev/LODProbeGridTuner.xaml.cs deleted file mode 100644 index 3385d9ff..00000000 --- a/GameDev/LODProbeGridTuner.xaml.cs +++ /dev/null @@ -1,305 +0,0 @@ -using System; -using System.IO; -using System.Windows; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; -using Microsoft.Win32; -using System.Windows.Input; - - -namespace GameDev -{ - /// - /// Interaction logic for LODProbeGridTuner.xaml - /// - public partial class LODProbeGridTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - private bool initialized = false; - - public LODProbeGridTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - fn_probe_data.Text = "assets/lod_probes.dat"; - if (att.ContainsKey("probe_data")) - { - fn_probe_data.Text = att["probe_data"].ToString(); - } - - tuner_divisions.set_value(10, 5, 10); - if (att.ContainsKey("base_divisions")) - { - string divisions = att["base_divisions"].ToString(); - string[] values = divisions.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_divisions.set_value(x, y, z); - } - - tuner_coverage_min.set_value(-10, 0, -10); - if (att.ContainsKey("coverage_min")) - { - string coverage_min = att["coverage_min"].ToString(); - string[] values = coverage_min.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_min.set_value(x, y, z); - } - - tuner_coverage_max.set_value(10, 10, 10); - if (att.ContainsKey("coverage_max")) - { - string coverage_max = att["coverage_max"].ToString(); - string[] values = coverage_max.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_max.set_value(x, y, z); - } - - tuner_sub_div.value = 2; - if (att.ContainsKey("sub_division_level")) - { - tuner_sub_div.value = float.Parse(att["sub_division_level"].ToString()); - } - - tuner_normal_bias.value = 0.2f; - tuner_normal_bias.step = 0.05f; - if (att.ContainsKey("normal_bias")) - { - tuner_normal_bias.value = float.Parse(att["normal_bias"].ToString()); - } - - if (att.ContainsKey("per_primitive")) - { - bool per_primitive = att["per_primitive"].ToObject(); - chk_per_primitive.IsChecked = per_primitive; - } - - tuner_iterations.value = 6; - tuner_num_rays.value = 8192; - tuner_num_rays.step = 2; - tuner_num_rays.exponential = true; - - initialized = true; - } - - private void load_data() - { - JObject tuning = new JObject(); - tuning["probe_data"] = fn_probe_data.Text; - - var att = (JObject)jobj["attributes"]; - att["probe_data"] = tuning["probe_data"]; - - var res = JObject.Parse(game_player.SendMessageToUser("tuning", tuning.ToString())); - - if (res.ContainsKey("base_divisions")) - { - att["base_divisions"] = res["base_divisions"]; - string divisions = res["base_divisions"].ToString(); - string[] values = divisions.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_divisions.set_value(x, y, z); - } - - if (res.ContainsKey("coverage_min")) - { - att["coverage_min"] = res["coverage_min"]; - string coverage_min = res["coverage_min"].ToString(); - string[] values = coverage_min.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_min.set_value(x, y, z); - } - - if (res.ContainsKey("coverage_max")) - { - att["coverage_max"] = res["coverage_max"]; - string coverage_max = res["coverage_max"].ToString(); - string[] values = coverage_max.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_max.set_value(x, y, z); - } - - if (res.ContainsKey("sub_division_level")) - { - att["sub_division_level"] = res["sub_division_level"]; - tuner_sub_div.value = float.Parse(res["sub_division_level"].ToString()); - } - - } - - private void text_LostFocus(object sender, System.Windows.RoutedEventArgs e) - { - load_data(); - } - - private void text_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - load_data(); - } - } - - private void btn_browse_Click(object sender, System.Windows.RoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Filter = "Data File(*.dat)|*.dat"; - if (dialog.ShowDialog() != true) return; - - var mainwnd = Window.GetWindow(Application.Current.MainWindow) as MainWindow; - string cur_path = mainwnd.cur_path; - - string path = dialog.FileName; - if (!path.StartsWith(cur_path)) - { - MessageBox.Show("Failed to parse path"); - return; - } - - string rel_path = path.Substring(cur_path.Length + 1); - fn_probe_data.Text = rel_path; - load_data(); - } - - private void tuner_divisions_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["base_divisions"] = $"{tuner_divisions.x},{tuner_divisions.y},{tuner_divisions.z}"; - - var att = (JObject)jobj["attributes"]; - att["base_divisions"] = tuning["base_divisions"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_coverage_min_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["coverage_min"] = $"{tuner_coverage_min.x},{tuner_coverage_min.y},{tuner_coverage_min.z}"; - - var att = (JObject)jobj["attributes"]; - att["coverage_min"] = tuning["coverage_min"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - - } - - private void tuner_coverage_max_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["coverage_max"] = $"{tuner_coverage_max.x},{tuner_coverage_max.y},{tuner_coverage_max.z}"; - - var att = (JObject)jobj["attributes"]; - att["coverage_max"] = tuning["coverage_max"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_sub_div_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["sub_division_level"] = $"{tuner_sub_div.value}"; - - var att = (JObject)jobj["attributes"]; - att["sub_division_level"] = tuning["sub_division_level"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void btn_initialize_Click(object sender, RoutedEventArgs e) - { - int num_probes = int.Parse(game_player.SendMessageToUser("initialize", "{}")); - text_num_probes.Text = $"Number of probes: {num_probes}"; - } - - private void tuner_normal_bias_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["normal_bias"] = $"{tuner_normal_bias.value}"; - - var att = (JObject)jobj["attributes"]; - att["normal_bias"] = tuning["normal_bias"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void btn_start_Click(object sender, RoutedEventArgs e) - { - JObject tuning = new JObject(); - tuning["iterations"] = tuner_iterations.value; - tuning["num_rays"] = tuner_num_rays.value; - game_player.SendMessageToUser("generate", tuning.ToString()); - } - - private void btn_auto_detect_Click(object sender, RoutedEventArgs e) - { - JObject tuning = new JObject(); - tuning["auto_area"] = "auto"; - var ret = JObject.Parse(game_player.SendMessageToUser("tuning", tuning.ToString())); - - var att = (JObject)jobj["attributes"]; - { - att["base_divisions"] = ret["base_divisions"]; - string divisions = ret["base_divisions"].ToString(); - string[] values = divisions.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_divisions.set_value(x, y, z); - } - { - att["coverage_min"] = ret["coverage_min"]; - string coverage_min = ret["coverage_min"].ToString(); - string[] values = coverage_min.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_min.set_value(x, y, z); - } - { - att["coverage_max"] = ret["coverage_max"]; - string coverage_max = ret["coverage_max"].ToString(); - string[] values = coverage_max.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_max.set_value(x, y, z); - } - { - att["sub_division_level"] = ret["sub_division_level"]; - tuner_sub_div.value = float.Parse(ret["sub_division_level"].ToString()); - } - } - - private void chk_per_primitive_Checked(object sender, RoutedEventArgs e) - { - if (initialized) - { - JObject tuning = new JObject(); - tuning["per_primitive"] = $"{chk_per_primitive.IsChecked == true}"; - - var att = (JObject)jobj["attributes"]; - att["per_primitive"] = tuning["per_primitive"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - - } - } - } -} diff --git a/GameDev/MainWindow.xaml b/GameDev/MainWindow.xaml deleted file mode 100644 index c0f485c5..00000000 --- a/GameDev/MainWindow.xaml +++ /dev/null @@ -1,190 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/GameDev/MainWindow.xaml.cs b/GameDev/MainWindow.xaml.cs deleted file mode 100644 index 87d6dd87..00000000 --- a/GameDev/MainWindow.xaml.cs +++ /dev/null @@ -1,1335 +0,0 @@ -using System; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections.Generic; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Input; -using Microsoft.Win32; -using Newtonsoft.Json.Linq; -using System.Diagnostics; -using System.Threading.Tasks; -using Microsoft.VisualBasic.FileIO; - -namespace GameDev -{ - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainWindow : Window - { - public static RoutedCommand RoutedCommandNewProject = new RoutedCommand(); - public static RoutedCommand RoutedCommandOpenProject = new RoutedCommand(); - public static RoutedCommand RoutedCommandCloseFile = new RoutedCommand(); - public static RoutedCommand RoutedCommandCloseProject = new RoutedCommand(); - public static RoutedCommand RoutedCommandSaveAll = new RoutedCommand(); - public static RoutedCommand RoutedCommandReopen = new RoutedCommand(); - public static RoutedCommand RoutedCommandReopenAll = new RoutedCommand(); - - public static RoutedCommand RoutedCommandComment = new RoutedCommand(); - public static RoutedCommand RoutedCommandUpper = new RoutedCommand(); - public static RoutedCommand RoutedCommandLower = new RoutedCommand(); - public static RoutedCommand RoutedCommandFind = new RoutedCommand(); - public static RoutedCommand RoutedCommandFindNext = new RoutedCommand(); - public static RoutedCommand RoutedCommandFindPrev = new RoutedCommand(); - public static RoutedCommand RoutedCommandReplace = new RoutedCommand(); - public static RoutedCommand RoutedCommandGoto = new RoutedCommand(); - - public static RoutedCommand RoutedCommandProjectSettings = new RoutedCommand(); - public static RoutedCommand RoutedCommandAPI = new RoutedCommand(); - - public string cur_path = ""; - private JsonData project = new JsonData(); - private HashSet target_outputs = new HashSet(); - private Dictionary opened_tabs = new Dictionary(); - - private List RecentFiles = new List(); - private List RecentProjects = new List(); - - private ContextMenu ctxMenu_dir =null; - private ContextMenu ctxMenu_file = null; - private ContextMenu ctxMenu_target = null; - - private void CreateContextMenus() - { - ctxMenu_dir = new ContextMenu(); - { - var item_add = new MenuItem(); - item_add.Header = "_New File"; - ctxMenu_dir.Items.Add(item_add); - item_add.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - TreeViewItem node = (TreeViewItem)cm.PlacementTarget; - string dir_path = (string)node.Tag; - NewFile(dir_path); - } - }; - - var item_add_dir = new MenuItem(); - item_add_dir.Header = "_New Directory"; - ctxMenu_dir.Items.Add(item_add_dir); - item_add_dir.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - TreeViewItem node = (TreeViewItem)cm.PlacementTarget; - string dir_path = (string)node.Tag; - NewDirectory(dir_path); - } - }; - - var item_delete = new MenuItem(); - item_delete.Header = "_Delete"; - ctxMenu_dir.Items.Add(item_delete); - item_delete.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - TreeViewItem node = (TreeViewItem)cm.PlacementTarget; - string dir_path = (string)node.Tag; - - if (MessageBox.Show($"Delete directory\"{dir_path}\"?", "Delete Directory", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) - { - FileSystem.DeleteDirectory(dir_path, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); - update_cur_path(); - } - } - }; - } - - ctxMenu_file = new ContextMenu(); - { - var item_open = new MenuItem(); - item_open.Header = "_Open"; - ctxMenu_file.Items.Add(item_open); - item_open.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - TreeViewItem node = (TreeViewItem)cm.PlacementTarget; - string file_path = (string)node.Tag; - OpenFile(file_path); - } - }; - - var item_delete = new MenuItem(); - item_delete.Header = "_Delete"; - ctxMenu_file.Items.Add(item_delete); - item_delete.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - TreeViewItem node = (TreeViewItem)cm.PlacementTarget; - string file_path = (string)node.Tag; - - if (MessageBox.Show($"Delete file\"{file_path}\"?", "Delete File", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) - { - FileSystem.DeleteFile(file_path, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); - update_cur_path(); - } - } - }; - } - - ctxMenu_target = new ContextMenu(); - { - var item_run = new MenuItem(); - item_run.Header = "_Run"; - ctxMenu_target.Items.Add(item_run); - item_run.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - ListViewItem item = (ListViewItem)cm.PlacementTarget; - JObject jTarget = (JObject)item.Tag; - RunTarget(jTarget); - } - }; - - var item_shortcut = new MenuItem(); - item_shortcut.Header = "Create _shortcut"; - ctxMenu_target.Items.Add(item_shortcut); - item_shortcut.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - ListViewItem item = (ListViewItem)cm.PlacementTarget; - JObject jTarget = (JObject)item.Tag; - CreateTargetShortcut(jTarget); - } - }; - - var item_edit = new MenuItem(); - item_edit.Header = "_Edit"; - ctxMenu_target.Items.Add(item_edit); - item_edit.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - ListViewItem item = (ListViewItem)cm.PlacementTarget; - JObject jTarget = (JObject)item.Tag; - EditTarget(jTarget); - } - }; - - - var item_remove = new MenuItem(); - item_remove.Header = "_Remove"; - ctxMenu_target.Items.Add(item_remove); - item_remove.Click += (sender, e) => - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - ListViewItem item = (ListViewItem)cm.PlacementTarget; - JObject jTarget = (JObject)item.Tag; - RemoveTarget(jTarget); - } - }; - - } - - } - - private void UpdateRecentFiles() - { - menu_recent_files.Items.Clear(); - if (RecentFiles.Count<1) - { - MenuItem item = new MenuItem(); - item.IsEnabled = false; - item.Header = "None"; - menu_recent_files.Items.Add(item); - return; - } - - for (int i =0; i< RecentFiles.Count; i++) - { - string filename = RecentFiles[i]; - MenuItem item = new MenuItem(); - item.Header = $"{i+1} {filename}"; - item.Click += (sender, e) => - { - OpenFile(filename); - }; - menu_recent_files.Items.Add(item); - } - } - - private void LoadRecentFiles() - { - RecentFiles.Clear(); - const string reg_path = "HKEY_CURRENT_USER\\Software\\GameDev\\recent_files"; - for (int i = 0; i < 10; i++) - { - string key = i.ToString(); - string filename = (string)Registry.GetValue(reg_path, key, ""); - if (filename== null || filename == "") break; - RecentFiles.Add(filename); - } - UpdateRecentFiles(); - } - - private void SaveRecentFiles() - { - const string reg_path = "HKEY_CURRENT_USER\\Software\\GameDev\\recent_files"; - for (int i=0; i= 10) - { - RecentFiles.RemoveAt(i); - i--; - } - } - UpdateRecentFiles(); - SaveRecentFiles(); - } - - private void UpdateRecentProjects() - { - menu_recent_projects.Items.Clear(); - if (RecentProjects.Count < 1) - { - MenuItem item = new MenuItem(); - item.IsEnabled = false; - item.Header = "None"; - menu_recent_projects.Items.Add(item); - return; - } - - for (int i = 0; i < RecentProjects.Count; i++) - { - string filename = RecentProjects[i]; - string path = Path.GetDirectoryName(filename); - MenuItem item = new MenuItem(); - item.Header = $"{i + 1} {filename}"; - item.Click += (sender, e) => - { - change_path(path); - }; - menu_recent_projects.Items.Add(item); - } - } - - private void LoadRecentProjects() - { - RecentProjects.Clear(); - const string reg_path = "HKEY_CURRENT_USER\\Software\\GameDev\\recent_projects"; - for (int i = 0; i < 10; i++) - { - string key = i.ToString(); - string filename = (string)Registry.GetValue(reg_path, key, ""); - if (filename == null || filename == "") break; - RecentProjects.Add(filename); - } - UpdateRecentProjects(); - } - - private void SaveRecentProjects() - { - const string reg_path = "HKEY_CURRENT_USER\\Software\\GameDev\\recent_projects"; - for (int i = 0; i < RecentProjects.Count; i++) - { - string key = i.ToString(); - string filename = RecentProjects[i]; - Registry.SetValue(reg_path, key, filename); - } - } - - private void AddRecentProject(string file_path) - { - RecentProjects.Insert(0, file_path); - for (int i = 1; i < RecentProjects.Count; i++) - { - if (RecentProjects[i] == file_path || i >= 10) - { - RecentProjects.RemoveAt(i); - i--; - } - } - UpdateRecentProjects(); - SaveRecentProjects(); - } - - private void create_default_project() - { - project.filename = $"{cur_path}\\project.json"; - - if (!File.Exists(project.filename)) - { - string project_name = Path.GetFileName(cur_path); - project.data = new JObject(); - project.data["project_name"] = project_name; - project.Save(); - } - } - - private StackPanel create_item(string name, string icon_name, int icon_size = 24) - { - var panel = new StackPanel(); - panel.Orientation = Orientation.Horizontal; - - var icon_image = new BitmapImage(new Uri($"pack://application:,,,/Icons/{icon_name}")); - var icon = new Image(); - icon.Source = icon_image; - RenderOptions.SetBitmapScalingMode(icon, BitmapScalingMode.HighQuality); - icon.Width = icon_size; - icon.Height = icon_size; - panel.Children.Add(icon); - - var label = new TextBlock(); - label.VerticalAlignment = VerticalAlignment.Center; - label.Text = name; - label.Margin = new Thickness(5.0); - panel.Children.Add(label); - return panel; - } - - private void update_dir(ItemsControl item, string path) - { - item.Items.Clear(); - if (path == "") return; - - - var list_dirs = Directory.GetDirectories(path); - foreach (var dir in list_dirs) - { - string dir_name = Path.GetFileName(dir); - var subitem = new TreeViewItem(); - subitem.Header = create_item(dir_name, "folder.png"); - subitem.Tag = dir; - subitem.ContextMenu = ctxMenu_dir; - item.Items.Add(subitem); - update_dir(subitem, dir); - } - - - var list_files = Directory.GetFiles(path); - foreach (var file in list_files) - { - string file_name = Path.GetFileName(file); - string ext = Path.GetExtension(file_name); - if (ext == ".js") - { - string rel_path = file.Substring(cur_path.Length+1); - if (target_outputs.Contains(rel_path)) continue; - } - - string icon_name = "doc.png"; - if (ext == ".js") icon_name = "js.png"; - if (ext == ".xml") icon_name = "xml.png"; - if (ext == ".json") icon_name = "json.png"; - - var subitem = new TreeViewItem(); - subitem.Header = create_item(file_name, icon_name); - subitem.Tag = file; - subitem.ContextMenu = ctxMenu_file; - - subitem.MouseDoubleClick += (sender, e) => - { - OpenFile(file); - }; - - item.Items.Add(subitem); - - } - } - - private void update_targets() - { - lst_targets.Items.Clear(); - target_outputs.Clear(); - JObject obj_proj = (JObject)project.data; - if (obj_proj != null && obj_proj.ContainsKey("targets")) - { - var jTargets = (JArray)obj_proj["targets"]; - - foreach (JObject jTarget in jTargets) - { - string name = jTarget["name"].ToString(); - var subitem = new ListViewItem(); - subitem.Content = create_item(name, "target.png", 36); - subitem.Tag = jTarget; - subitem.ContextMenu = ctxMenu_target; - subitem.MouseDoubleClick += (sender,e) => - { - RunTarget(jTarget); - }; - - lst_targets.Items.Add(subitem); - target_outputs.Add(jTarget["output"].ToString()); - } - } - - } - - private void update_cur_path() - { - if (cur_path == "") - { - project.Clear(); - this.Title = "GameDev"; - } - else - { - if (!File.Exists($"{cur_path}\\project.json")) - { - create_default_project(); - } - else - { - project.filename = $"{cur_path}\\project.json"; - project.Load(); - AddRecentProject(project.filename); - } - this.Title = $"GameDev - {project.data["project_name"]}"; - } - update_targets(); - update_dir(tree_files, cur_path); - } - - private void change_path(string path) - { - if (!Directory.Exists(path)) return; - const string reg_path = "HKEY_CURRENT_USER\\Software\\GameDev"; - Registry.SetValue(reg_path, "cur_path", path); - cur_path = path; - update_cur_path(); - - } - - public MainWindow() - { - InitializeComponent(); - CreateContextMenus(); - - const string reg_path = "HKEY_CURRENT_USER\\Software\\GameDev"; - string path = (string)Registry.GetValue(reg_path, "cur_path", ""); - if (File.Exists($"{path}\\project.json")) - { - cur_path = path; - update_cur_path(); - } - - LoadRecentFiles(); - LoadRecentProjects(); - } - - private bool no_update = false; - private bool in_background = false; - - public void AppDeactivated() - { - in_background = true; - } - - public void AppActivated() - { - if (in_background && !no_update) - { - in_background = false; - update_cur_path(); - } - } - - private void TabItem_PreviewMouseMove(object sender, MouseEventArgs e) - { - if (!(e.Source is TextBlock tb)) - { - return; - } - - TabItem tabItem = ((StackPanel)tb.Parent).Parent as TabItem; - if (tabItem == null) return; - - if (Mouse.PrimaryDevice.LeftButton == MouseButtonState.Pressed) - { - DragDrop.DoDragDrop(tabItem, tabItem, DragDropEffects.All); - } - } - - private void TabItem_Drop(object sender, DragEventArgs e) - { - if (e.Source is TextBlock tb1 && - e.Data.GetData(typeof(TabItem)) is TabItem tabItemSource) - { - TabItem tabItemTarget = (TabItem)((StackPanel)tb1.Parent).Parent; - - if (!tabItemTarget.Equals(tabItemSource) && - tabItemTarget.Parent is TabControl tabControl) - { - int targetIndex = tabControl.Items.IndexOf(tabItemTarget); - - tabControl.Items.Remove(tabItemSource); - tabControl.Items.Insert(targetIndex, tabItemSource); - tabItemSource.IsSelected = true; - } - } - - } - - protected override async void OnClosing(System.ComponentModel.CancelEventArgs e) - { - if (TabCtrl_Editor.Items.Count > 0) - { - e.Cancel = true; - while (TabCtrl_Editor.Items.Count>0) - { - TabItem tabItem = (TabItem)TabCtrl_Editor.Items[0]; - bool closed = await CloseTab(tabItem); - if (!closed) return; - } - _ = Dispatcher.BeginInvoke(new Action(() => Close())); - return; - } - - base.OnClosing(e); - } - - private void CommandNewProject(object sender, ExecutedRoutedEventArgs e) - { - var dialog = new SaveFileDialog(); - dialog.Filter = "Project|project.json"; - dialog.FileName = "project.json"; - if (dialog.ShowDialog() != true) return; - - cur_path = Path.GetDirectoryName(dialog.FileName); - create_default_project(); - - change_path(cur_path); - } - - private void CommandOpenProject(object sender, ExecutedRoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Filter = "Project|project.json"; - dialog.FileName = "project.json"; - if (dialog.ShowDialog() != true) return; - - string path = Path.GetDirectoryName(dialog.FileName); - change_path(path); - } - - private void NewFile(string path_dir) - { - var dialog = new DlgNewFile(this); - if (dialog.ShowDialog() != true) return; - - string path = $"{path_dir}\\{dialog.filename}"; - if (!File.Exists(path)) - { - if (dialog.typename == "js") - { - File.WriteAllText(path, ""); - } - else if (dialog.typename == "xml") - { - File.WriteAllText(path, "\n\n\t\n\t\n\n"); - } - else if (dialog.typename == "json") - { - File.WriteAllText(path, "{}"); - } - update_cur_path(); - } - - OpenFile(path); - - } - - private void NewDirectory(string path_dir) - { - var dialog = new DlgNewDir(this); - if (dialog.ShowDialog() != true) return; - - string path = $"{path_dir}\\{dialog.filename}"; - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - update_cur_path(); - } - } - - private void CommandNewFile(object sender, ExecutedRoutedEventArgs e) - { - NewFile(cur_path); - } - - private void CommandOpenFile(object sender, ExecutedRoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Filter = "All Supported(*.js;*.json;*.xml)|*.js;*.json;*.xml|JavaScript(*.js)|*.js|JSON(*.json)|*.json|XML(*.xml)|*.xml"; - if (dialog.ShowDialog() != true) return; - OpenFile(dialog.FileName); - } - - private async Task CloseTab(TabItem tabItem) - { - var editor = tabItem.Content as EditorBase; - if (editor != null) - { - bool closed = await editor.doc_close(); - if (closed) - { - editor.cleanup(); - string filepath = (string)tabItem.Tag; - TabCtrl_Editor.Items.Remove(tabItem); - opened_tabs.Remove(filepath); - return true; - } - } - return false; - } - - - private void CommandCloseFile(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx>=0) - { - CloseTab((TabItem)TabCtrl_Editor.Items[idx]); - } - } - - private void CommandCloseProject(object sender, ExecutedRoutedEventArgs e) - { - change_path(""); - } - - private void SetDirty() - { - if (project.data == null) return; - JObject obj_proj = (JObject)project.data; - if (!obj_proj.ContainsKey("targets")) return; - JArray targets = (JArray)obj_proj["targets"]; - foreach(JObject target in targets) - { - target["dirty"] = true; - } - project.Save(); - } - - private async void SaveTab(TabItem tabItem) - { - var editor = tabItem.Content as Editor; - if (editor != null) - { - await editor.doc_save(); - string filepath = (string)tabItem.Tag; - string ext = Path.GetExtension(filepath); - string filename = Path.GetFileName(filepath); - - if (filepath.StartsWith(cur_path)) - { - if (filename == "project.json") - { - update_cur_path(); - } - if (ext == ".js") - { - SetDirty(); - } - } - } - } - - private void CommandSave(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - SaveTab(tabItem); - } - } - - private async void SaveAsTab(TabItem tabItem) - { - var editor = tabItem.Content as Editor; - if (editor != null) - { - string new_path = await editor.doc_save_as(); - if (new_path != "") - { - opened_tabs.Remove((string)tabItem.Tag); - opened_tabs[new_path] = tabItem; - tabItem.Tag = new_path; - StackPanel header = (StackPanel)tabItem.Header; - TextBlock text = (TextBlock)header.Children[0]; - text.Text = Path.GetFileName(new_path); - update_cur_path(); - } - } - - } - - private void CommandSaveAs(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - SaveAsTab(tabItem); - } - } - - private void CommandSaveAll(object sender, ExecutedRoutedEventArgs e) - { - foreach (TabItem tabItem in TabCtrl_Editor.Items) - { - SaveTab(tabItem); - } - } - - private async void ReopenTab(TabItem tabItem) - { - var editor = tabItem.Content as Editor; - if (editor != null) - { - await editor.doc_fresh(); - } - } - - private void CommandReopen(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - ReopenTab(tabItem); - } - - } - - private void CommandReopenAll(object sender, ExecutedRoutedEventArgs e) - { - foreach (TabItem tabItem in TabCtrl_Editor.Items) - { - ReopenTab(tabItem); - } - } - - private void CommandExit(object sender, ExecutedRoutedEventArgs e) - { - Close(); - } - - private void CommandUndo(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.undo(); - } - } - } - - private void CommandRedo(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.redo(); - } - } - } - - private void CommandComment(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.comment(); - } - } - } - - private void CommandUpper(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.upper(); - } - } - } - - private void CommandLower(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.lower(); - } - } - } - - private void CommandFind(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.find(); - } - } - } - - private void CommandFindNext(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.findnext(); - } - } - } - - private void CommandFindPrev(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.findprev(); - } - } - } - - private void CommandReplace(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.replace(); - } - } - } - - private void CommandGoto(object sender, ExecutedRoutedEventArgs e) - { - int idx = TabCtrl_Editor.SelectedIndex; - if (idx >= 0) - { - var tabItem = (TabItem)TabCtrl_Editor.Items[idx]; - var editor = tabItem.Content as Editor; - if (editor != null) - { - editor.gotoline(); - } - } - } - - - private void CommandProjectSettings(object sender, ExecutedRoutedEventArgs e) - { - if (project.data == null) return; - - var dlg = new DlgProjectSettings(this, (JObject)project.data); - if (dlg.ShowDialog() == true) - { - project.Save(); - update_cur_path(); - } - } - - private void CommandHelp(object sender, ExecutedRoutedEventArgs e) - { - string local_path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); - string help_path = $"{local_path}/help/index.html"; - - TabItem item = NewTabItem(help_path, "Help"); - if (item.Content == null) - { - HelpPage help_page = new HelpPage(help_path); - item.Content = help_page; - } - else - { - HelpPage help_page = item.Content as HelpPage; - if (help_page != null) - { - help_page.Goto(help_path); - } - } - } - - private void CommandAPIDoc(object sender, ExecutedRoutedEventArgs e) - { - string local_path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); - string help_path = $"{local_path}/help/api/index.html"; - - TabItem item = NewTabItem(help_path, "Help"); - if (item.Content == null) - { - HelpPage help_page = new HelpPage(help_path); - item.Content = help_page; - } - else - { - HelpPage help_page = item.Content as HelpPage; - if (help_page != null) - { - help_page.Goto(help_path); - } - } - } - - private void AddTarget() - { - var dlg = new DlgEditTarget(this, null, cur_path); - if (dlg.ShowDialog() == true) - { - JObject obj_proj = (JObject)project.data; - JArray jTargets; - if (!obj_proj.ContainsKey("targets")) - { - jTargets = new JArray(); - obj_proj["targets"] = jTargets; - } - else - { - jTargets = (JArray)obj_proj["targets"]; - } - jTargets.Add(dlg.jTarget); - - string path_in = $"{cur_path}\\{dlg.jTarget["input"]}"; - - if (!File.Exists(path_in)) - { - File.WriteAllText(path_in, ""); - } - - project.Save(); - update_cur_path(); - lst_targets.SelectedIndex = lst_targets.Items.Count - 1; - - OpenJavaScript(path_in); - - } - } - - private void btn_add_target_Click(object sender, RoutedEventArgs e) - { - if (project.data == null) return; - AddTarget(); - } - - private void RemoveTarget(JObject jTarget) - { - if (MessageBox.Show($"Remove target\"{jTarget["name"]}\"?", "Remove Target", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) - { - jTarget.Remove(); - project.Save(); - update_cur_path(); - } - } - - private void btn_remove_target_Click(object sender, RoutedEventArgs e) - { - if (project.data == null) return; - int idx = lst_targets.SelectedIndex; - if (idx == -1) return; - var item = (ListViewItem)lst_targets.Items[idx]; - JObject jTarget = (JObject)item.Tag; - RemoveTarget(jTarget); - } - - private void EditTarget(JObject jTarget) - { - var dlg = new DlgEditTarget(this, jTarget, cur_path); - if (dlg.ShowDialog() == true) - { - project.Save(); - update_cur_path(); - } - - } - - private void btn_edit_target_Click(object sender, RoutedEventArgs e) - { - if (project.data == null) return; - int idx = lst_targets.SelectedIndex; - if (idx == -1) return; - var item = (ListViewItem)lst_targets.Items[idx]; - JObject jTarget = (JObject)item.Tag; - EditTarget(jTarget); - } - - private int GetTargetIndex(JObject jTarget) - { - JObject obj_proj = (JObject)project.data; - var jTargets = (JArray)obj_proj["targets"]; - for (int idx=0; idx<]", ""); - console_log(line, brush_blue); - } - - if (!File.Exists(output)) - { - console_log("Bundling failed!"); - console_log(""); - jTarget["dirty"] = true; - } - else - { - console_log("Bundling succeeded!"); - console_log(""); - jTarget["dirty"] = false; - } - console_scroll.ScrollToBottom(); - project.Save(); - - no_update = false; - } - - int idx = GetTargetIndex(jTarget); - string Location = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); - Process.Start($"{Location}\\GamePlayer.exe", $"\"{project.filename}\" \"{idx}\""); - } - - private void CreateTargetShortcut(JObject jTarget) - { - int idx = GetTargetIndex(jTarget); - string Location = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); - - var shell = new IWshRuntimeLibrary.WshShell(); - var shDesktop = (object)"Desktop"; - var shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + "\\" + jTarget["name"] + ".lnk"; - var shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress); - shortcut.Description = "Shortcut for Three.V8 app " + jTarget["name"]; - shortcut.TargetPath = $"{Location}\\GamePlayer.exe"; - shortcut.Arguments = $"\"{project.filename}\" \"{idx}\""; - shortcut.Save(); - - MessageBox.Show($"Created shortcut for target \"{jTarget["name"]}\""); - } - - private TabItem NewTabItem(string filepath, string name) - { - if (opened_tabs.ContainsKey(filepath)) - { - TabItem item = opened_tabs[filepath]; - TabCtrl_Editor.SelectedItem = item; - return item; - } - - TabItem tabItem = new TabItem(); - var header = new StackPanel(); - header.Orientation = Orientation.Horizontal; - var text = new TextBlock(); - text.Text = name; - header.Children.Add(text); - var btn = new Button(); - btn.Background = Brushes.Transparent; - btn.BorderBrush = Brushes.Transparent; - btn.Content = "🞨"; - btn.Padding = new Thickness(2.0, 0.0, 2.0, 0.0); - header.Children.Add(btn); - tabItem.Header = header; - TabCtrl_Editor.Items.Add(tabItem); - opened_tabs[filepath] = tabItem; - TabCtrl_Editor.SelectedItem = tabItem; - tabItem.Tag = filepath; - - btn.Click += async (sender, e) => - { - CloseTab(tabItem); - - }; - - return tabItem; - - } - - private void OpenJavaScript(string file_path) - { - string filename = Path.GetFileName(file_path); - TabItem item = NewTabItem(file_path, filename); - if (item.Content == null) - { - JSEditor editor = new JSEditor(file_path); - item.Content = editor; - } - else - { - ReopenTab(item); - } - } - - private void OpenJSON(string file_path) - { - string filename = Path.GetFileName(file_path); - TabItem item = NewTabItem(file_path, filename); - if (item.Content == null) - { - JsonEditor editor = new JsonEditor(file_path); - item.Content = editor; - } - else - { - ReopenTab(item); - } - } - - private void OpenXML(string file_path) - { - string filename = Path.GetFileName(file_path); - TabItem item = NewTabItem(file_path, filename); - if (item.Content == null) - { - XMLEditor editor = new XMLEditor(file_path, cur_path, (str) =>{ - console_std(str, filename); - }, (str) =>{ - console_err(str, filename); - }); - item.Content = editor; - } - else - { - ReopenTab(item); - } - } - - private void OpenFile(string file_path) - { - if (!File.Exists(file_path)) return; - string ext = Path.GetExtension(file_path); - if (ext == ".js") - { - OpenJavaScript(file_path); - } - else if (ext == ".json") - { - OpenJSON(file_path); - } - else if (ext == ".xml") - { - OpenXML(file_path); - } - else - { - return; - } - - AddRecentFile(file_path); - - } - - private void menu_clear_console_Click(object sender, RoutedEventArgs e) - { - console.Children.Clear(); - } - - private void menu_new_file_Click(object sender, RoutedEventArgs e) - { - NewFile(cur_path); - } - - private void menu_add_target_Click(object sender, RoutedEventArgs e) - { - AddTarget(); - } - } -} -; \ No newline at end of file diff --git a/GameDev/ModelTuner.xaml b/GameDev/ModelTuner.xaml deleted file mode 100644 index f18f3e40..00000000 --- a/GameDev/ModelTuner.xaml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - 0.0 - - - - diff --git a/GameDev/NumberTuner.xaml.cs b/GameDev/NumberTuner.xaml.cs deleted file mode 100644 index c2c67c07..00000000 --- a/GameDev/NumberTuner.xaml.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Input; -using System.Windows.Controls; - -namespace GameDev -{ - /// - /// Interaction logic for NumberTuner.xaml - /// - public partial class NumberTuner : UserControl - { - private float _value = 0.0f; - public float value - { - get - { - return _value; - } - set - { - if (_value != value) - { - _value = value; - text.Text = _value.ToString(); - } - } - } - - public bool exponential = false; - public float step = 1.0f; - - public NumberTuner() - { - InitializeComponent(); - } - - public event EventHandler ValueChanged; - - private void update_value() - { - string str = text.Text; - float v = _value; - float.TryParse(str, out v); - if (v != _value) - { - value = v; - ValueChanged?.Invoke(this, null); - } - - } - - private void text_LostFocus(object sender, System.Windows.RoutedEventArgs e) - { - update_value(); - } - - private void text_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - update_value(); - } - } - - private void btn_decr_Click(object sender, RoutedEventArgs e) - { - if (exponential) - { - value /= step; - } - else - { - value -= step; - } - ValueChanged?.Invoke(this, null); - } - - private void btn_incr_Click(object sender, RoutedEventArgs e) - { - if (exponential) - { - value *= step; - } - else - { - value += step; - } - ValueChanged?.Invoke(this, null); - } - } -} diff --git a/GameDev/Object3DTuner.xaml b/GameDev/Object3DTuner.xaml deleted file mode 100644 index 6236143a..00000000 --- a/GameDev/Object3DTuner.xaml +++ /dev/null @@ -1,28 +0,0 @@ - - - - Name: - - - - Position: - - - - Rotation: - - - - Scale: - - - - - diff --git a/GameDev/Object3DTuner.xaml.cs b/GameDev/Object3DTuner.xaml.cs deleted file mode 100644 index 6b2ce775..00000000 --- a/GameDev/Object3DTuner.xaml.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.Windows.Controls; -using System.Windows.Input; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for Object3DTuner.xaml - /// - public partial class Object3DTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public event EventHandler UpdateName; - - public Object3DTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - tuner_pos.tuner_x.step = 0.5f; - tuner_pos.tuner_y.step = 0.5f; - tuner_pos.tuner_z.step = 0.5f; - - var att = (JObject)jobj["attributes"]; - - if (att.ContainsKey("name")) - { - text_name.Text = att["name"].ToString(); - } - else - { - text_name.Text = jobj["tagName"].ToString(); - } - - if (att.ContainsKey("position")) - { - string position = att["position"].ToString(); - string[] values = position.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_pos.set_value(x, y, z); - } - - if (att.ContainsKey("rotation")) - { - string rotation = att["rotation"].ToString(); - string[] values = rotation.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_rot.set_value(x, y, z); - } - - if (att.ContainsKey("scale")) - { - string rotation = att["scale"].ToString(); - string[] values = rotation.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_scale.set_value(x, y, z); - } - } - - private void update_name() - { - JObject tuning = new JObject(); - tuning["name"] = text_name.Text; - - var att = (JObject)jobj["attributes"]; - att["name"] = tuning["name"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - - UpdateName?.Invoke(this, null); - } - - private void text_name_LostFocus(object sender, System.Windows.RoutedEventArgs e) - { - update_name(); - } - - private void text_name_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) - { - if (e.Key == Key.Return) - { - update_name(); - } - } - - private void tuner_pos_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["position"] = $"{tuner_pos.x},{tuner_pos.y},{tuner_pos.z}"; - - var att = (JObject)jobj["attributes"]; - att["position"] = tuning["position"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_rot_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["rotation"] = $"{tuner_rot.x},{tuner_rot.y},{tuner_rot.z}"; - - var att = (JObject)jobj["attributes"]; - att["rotation"] = tuning["rotation"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_scale_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["scale"] = $"{tuner_scale.x},{tuner_scale.y},{tuner_scale.z}"; - - var att = (JObject)jobj["attributes"]; - att["scale"] = tuning["scale"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } -} diff --git a/GameDev/PlaneTuner.xaml b/GameDev/PlaneTuner.xaml deleted file mode 100644 index 56bc6717..00000000 --- a/GameDev/PlaneTuner.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - diff --git a/GameDev/PlaneTuner.xaml.cs b/GameDev/PlaneTuner.xaml.cs deleted file mode 100644 index d7839a9a..00000000 --- a/GameDev/PlaneTuner.xaml.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - - -namespace GameDev -{ - /// - /// Interaction logic for PlaneTuner.xaml - /// - public partial class PlaneTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - public Object3DTuner obj3d_tuner = null; - private bool initialized = false; - - public PlaneTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - - tuner_width.step = 0.5f; - tuner_width.value = 1.0f; - tuner_height.step = 0.5f; - tuner_height.value = 1.0f; - - if (att.ContainsKey("size")) - { - string size = att["size"].ToString(); - string[] values = size.Split(','); - tuner_width.value = float.Parse(values[0]); - tuner_height.value = float.Parse(values[1]); - } - - if (att.ContainsKey("is_building")) - { - bool is_building = att["is_building"].ToObject(); - chk_is_building.IsChecked = is_building; - } - - obj3d_tuner = new Object3DTuner(game_player, jobj); - stack.Children.Add(obj3d_tuner); - - var material_tuner = new SimpleMaterialTuner(game_player, jobj); - stack.Children.Add(material_tuner); - - initialized = true; - } - - private void tuner_size_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["size"] = $"{tuner_width.value},{tuner_height.value}"; - - var att = (JObject)jobj["attributes"]; - att["size"] = tuning["size"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void chk_is_building_Checked(object sender, System.Windows.RoutedEventArgs e) - { - if (initialized) - { - JObject tuning = new JObject(); - tuning["is_building"] = $"{chk_is_building.IsChecked == true}"; - - var att = (JObject)jobj["attributes"]; - att["is_building"] = tuning["is_building"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - } - } -} diff --git a/GameDev/ProbeGridTuner.xaml b/GameDev/ProbeGridTuner.xaml deleted file mode 100644 index 5a9d21fb..00000000 --- a/GameDev/ProbeGridTuner.xaml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/GameDev/ProbeGridTuner.xaml.cs b/GameDev/ProbeGridTuner.xaml.cs deleted file mode 100644 index eceb5c66..00000000 --- a/GameDev/ProbeGridTuner.xaml.cs +++ /dev/null @@ -1,296 +0,0 @@ -using System; -using System.IO; -using System.Windows; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; -using Microsoft.Win32; -using System.Windows.Input; - -namespace GameDev -{ - /// - /// Interaction logic for ProbeGridTuner.xaml - /// - public partial class ProbeGridTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - private bool initialized = false; - - public ProbeGridTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - var att = (JObject)jobj["attributes"]; - fn_probe_data.Text = "assets/probes.dat"; - if (att.ContainsKey("probe_data")) - { - fn_probe_data.Text = att["probe_data"].ToString(); - } - - tuner_divisions.set_value(10, 5, 10); - if (att.ContainsKey("divisions")) - { - string divisions = att["divisions"].ToString(); - string[] values = divisions.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_divisions.set_value(x, y, z); - } - - tuner_coverage_min.set_value(-10, 0, -10); - if (att.ContainsKey("coverage_min")) - { - string coverage_min = att["coverage_min"].ToString(); - string[] values = coverage_min.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_min.set_value(x, y, z); - } - - tuner_coverage_max.set_value(10, 10, 10); - if (att.ContainsKey("coverage_max")) - { - string coverage_max = att["coverage_max"].ToString(); - string[] values = coverage_max.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_max.set_value(x, y, z); - } - - tuner_ypower.value = 1.0f; - if (att.ContainsKey("ypower")) - { - tuner_ypower.value = float.Parse(att["ypower"].ToString()); - } - - tuner_normal_bias.value = 0.2f; - tuner_normal_bias.step = 0.05f; - if (att.ContainsKey("normal_bias")) - { - tuner_normal_bias.value = float.Parse(att["normal_bias"].ToString()); - } - - if (att.ContainsKey("per_primitive")) - { - bool per_primitive = att["per_primitive"].ToObject(); - chk_per_primitive.IsChecked = per_primitive; - } - - tuner_iterations.value = 6; - tuner_num_rays.value = 8192; - tuner_num_rays.step = 2; - tuner_num_rays.exponential = true; - - initialized = true; - } - - private void load_data() - { - JObject tuning = new JObject(); - tuning["probe_data"] = fn_probe_data.Text; - - var att = (JObject)jobj["attributes"]; - att["probe_data"] = tuning["probe_data"]; - - var res = JObject.Parse(game_player.SendMessageToUser("tuning", tuning.ToString())); - - if (res.ContainsKey("divisions")) - { - att["divisions"] = res["divisions"]; - string divisions = res["divisions"].ToString(); - string[] values = divisions.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_divisions.set_value(x, y, z); - } - - if (res.ContainsKey("coverage_min")) - { - att["coverage_min"] = res["coverage_min"]; - string coverage_min = res["coverage_min"].ToString(); - string[] values = coverage_min.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_min.set_value(x, y, z); - } - - if (res.ContainsKey("coverage_max")) - { - att["coverage_max"] = res["coverage_max"]; - string coverage_max = res["coverage_max"].ToString(); - string[] values = coverage_max.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_max.set_value(x, y, z); - } - - if (res.ContainsKey("y_power")) - { - att["ypower"] = res["ypower"]; - tuner_ypower.value = float.Parse(res["ypower"].ToString()); - } - - } - - private void text_LostFocus(object sender, System.Windows.RoutedEventArgs e) - { - load_data(); - } - - private void text_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - load_data(); - } - } - - private void btn_browse_Click(object sender, System.Windows.RoutedEventArgs e) - { - var dialog = new OpenFileDialog(); - dialog.Filter = "Data File(*.dat)|*.dat"; - if (dialog.ShowDialog() != true) return; - - var mainwnd = Window.GetWindow(Application.Current.MainWindow) as MainWindow; - string cur_path = mainwnd.cur_path; - - string path = dialog.FileName; - if (!path.StartsWith(cur_path)) - { - MessageBox.Show("Failed to parse path"); - return; - } - - string rel_path = path.Substring(cur_path.Length + 1); - fn_probe_data.Text = rel_path; - load_data(); - } - - private void tuner_divisions_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["divisions"] = $"{tuner_divisions.x},{tuner_divisions.y},{tuner_divisions.z}"; - - var att = (JObject)jobj["attributes"]; - att["divisions"] = tuning["divisions"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_coverage_min_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["coverage_min"] = $"{tuner_coverage_min.x},{tuner_coverage_min.y},{tuner_coverage_min.z}"; - - var att = (JObject)jobj["attributes"]; - att["coverage_min"] = tuning["coverage_min"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - - } - - private void tuner_coverage_max_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["coverage_max"] = $"{tuner_coverage_max.x},{tuner_coverage_max.y},{tuner_coverage_max.z}"; - - var att = (JObject)jobj["attributes"]; - att["coverage_max"] = tuning["coverage_max"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_ypower_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["ypower"] = $"{tuner_ypower.value}"; - - var att = (JObject)jobj["attributes"]; - att["ypower"] = tuning["ypower"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void tuner_normal_bias_ValueChanged(object sender, EventArgs e) - { - JObject tuning = new JObject(); - tuning["normal_bias"] = $"{tuner_normal_bias.value}"; - - var att = (JObject)jobj["attributes"]; - att["normal_bias"] = tuning["normal_bias"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - } - - private void btn_start_Click(object sender, RoutedEventArgs e) - { - JObject tuning = new JObject(); - tuning["iterations"] = tuner_iterations.value; - tuning["num_rays"] = tuner_num_rays.value; - game_player.SendMessageToUser("generate", tuning.ToString()); - } - - private void btn_auto_detect_Click(object sender, RoutedEventArgs e) - { - JObject tuning = new JObject(); - tuning["auto_area"] = "auto"; - var ret = JObject.Parse(game_player.SendMessageToUser("tuning", tuning.ToString())); - - var att = (JObject)jobj["attributes"]; - { - att["divisions"] = ret["divisions"]; - string divisions = ret["divisions"].ToString(); - string[] values = divisions.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_divisions.set_value(x, y, z); - } - { - att["coverage_min"] = ret["coverage_min"]; - string coverage_min = ret["coverage_min"].ToString(); - string[] values = coverage_min.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_min.set_value(x, y, z); - } - { - att["coverage_max"] = ret["coverage_max"]; - string coverage_max = ret["coverage_max"].ToString(); - string[] values = coverage_max.Split(','); - float x = float.Parse(values[0]); - float y = float.Parse(values[1]); - float z = float.Parse(values[2]); - tuner_coverage_max.set_value(x, y, z); - } - - - } - - private void chk_per_primitive_Checked(object sender, RoutedEventArgs e) - { - if (initialized) - { - JObject tuning = new JObject(); - tuning["per_primitive"] = $"{chk_per_primitive.IsChecked == true}"; - - var att = (JObject)jobj["attributes"]; - att["per_primitive"] = tuning["per_primitive"]; - - game_player.SendMessageToUser("tuning", tuning.ToString()); - - } - } - } -} diff --git a/GameDev/Properties/AssemblyInfo.cs b/GameDev/Properties/AssemblyInfo.cs deleted file mode 100644 index e8712216..00000000 --- a/GameDev/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Windows; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("GameDev")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("微软中国")] -[assembly: AssemblyProduct("GameDev")] -[assembly: AssemblyCopyright("Copyright © 微软中国 2023")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -//In order to begin building localizable applications, set -//CultureYouAreCodingWith in your .csproj file -//inside a . For example, if you are using US english -//in your source files, set the to en-US. Then uncomment -//the NeutralResourceLanguage attribute below. Update the "en-US" in -//the line below to match the UICulture setting in the project file. - -//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] - - -[assembly: ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) -)] - - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/GameDev/Properties/Resources.Designer.cs b/GameDev/Properties/Resources.Designer.cs deleted file mode 100644 index ed86df43..00000000 --- a/GameDev/Properties/Resources.Designer.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace GameDev.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GameDev.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { - return resourceCulture; - } - set - { - resourceCulture = value; - } - } - } -} diff --git a/GameDev/Properties/Resources.resx b/GameDev/Properties/Resources.resx deleted file mode 100644 index af7dbebb..00000000 --- a/GameDev/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/GameDev/Properties/Settings.Designer.cs b/GameDev/Properties/Settings.Designer.cs deleted file mode 100644 index 075c50d6..00000000 --- a/GameDev/Properties/Settings.Designer.cs +++ /dev/null @@ -1,30 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace GameDev.Properties -{ - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { - return defaultInstance; - } - } - } -} diff --git a/GameDev/Properties/Settings.settings b/GameDev/Properties/Settings.settings deleted file mode 100644 index 033d7a5e..00000000 --- a/GameDev/Properties/Settings.settings +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/GameDev/RotationTuner.xaml b/GameDev/RotationTuner.xaml deleted file mode 100644 index 90233f51..00000000 --- a/GameDev/RotationTuner.xaml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - diff --git a/GameDev/RotationTuner.xaml.cs b/GameDev/RotationTuner.xaml.cs deleted file mode 100644 index f6df1597..00000000 --- a/GameDev/RotationTuner.xaml.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Windows.Controls; - -namespace GameDev -{ - /// - /// Interaction logic for RotationTuner.xaml - /// - public partial class RotationTuner : UserControl - { - public float x - { - get - { - return tuner_x.value; - } - set - { - tuner_x.value = value; - } - } - - public float y - { - get - { - return tuner_y.value; - } - set - { - tuner_y.value = value; - } - } - - public float z - { - get - { - return tuner_z.value; - } - set - { - tuner_z.value = value; - } - } - - public void set_value(float x, float y, float z) - { - this.x = x; - this.y = y; - this.z = z; - } - - public RotationTuner() - { - InitializeComponent(); - } - - public event EventHandler ValueChanged; - - private void tuner_ValueChanged(object sender, EventArgs e) - { - ValueChanged?.Invoke(sender, e); - } - } -} diff --git a/GameDev/ScaleTuner.xaml b/GameDev/ScaleTuner.xaml deleted file mode 100644 index fde498fd..00000000 --- a/GameDev/ScaleTuner.xaml +++ /dev/null @@ -1,16 +0,0 @@ - - - - 1.0 - 1.0 - 1.0 - - - diff --git a/GameDev/ScaleTuner.xaml.cs b/GameDev/ScaleTuner.xaml.cs deleted file mode 100644 index 5fb016ef..00000000 --- a/GameDev/ScaleTuner.xaml.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Input; -using System.Windows.Controls; -using static System.Net.Mime.MediaTypeNames; -using Newtonsoft.Json.Linq; - - -namespace GameDev -{ - /// - /// Interaction logic for ScaleTuner.xaml - /// - public partial class ScaleTuner : UserControl - { - private float _x = 1.0f; - public float x - { - get - { - return _x; - } - set - { - if (_x != value) - { - _x = value; - text_x.Text = _x.ToString(); - } - } - } - - private float _y = 1.0f; - public float y - { - get - { - return _y; - } - set - { - if (_y != value) - { - _y = value; - text_y.Text = _y.ToString(); - } - } - } - - private float _z = 1.0f; - public float z - { - get - { - return _z; - } - set - { - if (_z != value) - { - _z = value; - text_z.Text = _z.ToString(); - } - } - } - - public float step = 1.1f; - - public void set_value(float x, float y, float z) - { - this.x = x; - this.y = y; - this.z = z; - } - - public ScaleTuner() - { - InitializeComponent(); - } - - public event EventHandler ValueChanged; - - private void update_value_x() - { - string str = text_x.Text; - float v = _x; - float.TryParse(str, out v); - if (v != _x) - { - x = v; - ValueChanged?.Invoke(this, null); - } - } - - private void text_x_LostFocus(object sender, RoutedEventArgs e) - { - update_value_x(); - } - - private void text_x_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - update_value_x(); - } - } - - private void update_value_y() - { - string str = text_y.Text; - float v = _y; - float.TryParse(str, out v); - if (v != _y) - { - y = v; - ValueChanged?.Invoke(this, null); - } - } - - private void text_y_LostFocus(object sender, RoutedEventArgs e) - { - update_value_y(); - } - - private void text_y_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - update_value_y(); - } - } - - private void update_value_z() - { - string str = text_z.Text; - float v = _z; - float.TryParse(str, out v); - if (v != _z) - { - z = v; - ValueChanged?.Invoke(this, null); - } - } - - private void text_z_LostFocus(object sender, RoutedEventArgs e) - { - update_value_z(); - } - - private void text_z_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Return) - { - update_value_z(); - } - } - - private void btn_decr_Click(object sender, RoutedEventArgs e) - { - x /= step; - y /= step; - z /= step; - ValueChanged?.Invoke(this, null); - } - - private void btn_incr_Click(object sender, RoutedEventArgs e) - { - x *= step; - y *= step; - z *= step; - ValueChanged?.Invoke(this, null); - } - - } -} diff --git a/GameDev/SceneTuner.xaml b/GameDev/SceneTuner.xaml deleted file mode 100644 index b777a2b0..00000000 --- a/GameDev/SceneTuner.xaml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/GameDev/SceneTuner.xaml.cs b/GameDev/SceneTuner.xaml.cs deleted file mode 100644 index 7288f495..00000000 --- a/GameDev/SceneTuner.xaml.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using CLRBinding; -using Newtonsoft.Json.Linq; - -namespace GameDev -{ - /// - /// Interaction logic for SceneTuner.xaml - /// - public partial class SceneTuner : UserControl - { - private CGamePlayer game_player = null; - private JObject jobj = null; - - - public SceneTuner(CGamePlayer game_player, JObject jobj) - { - InitializeComponent(); - this.game_player = game_player; - this.jobj = jobj; - - tuner_iterations.value = 6; - tuner_num_rays.value = 2048; - tuner_num_rays.step = 2; - tuner_num_rays.exponential = true; - } - - private void btn_bake_Click(object sender, RoutedEventArgs e) - { - JObject tuning = new JObject(); - tuning["iterations"] = tuner_iterations.value; - tuning["num_rays"] = tuner_num_rays.value; - game_player.SendMessageToUser("generate", tuning.ToString()); - } - } -} diff --git a/GameDev/SimpleMaterialTuner.xaml b/GameDev/SimpleMaterialTuner.xaml deleted file mode 100644 index 765c3ebe..00000000 --- a/GameDev/SimpleMaterialTuner.xaml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - Picking - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/GameDev/XMLEditor.xaml.cs b/GameDev/XMLEditor.xaml.cs deleted file mode 100644 index 009d23e6..00000000 --- a/GameDev/XMLEditor.xaml.cs +++ /dev/null @@ -1,903 +0,0 @@ -using System; -using System.Text; -using System.IO; -using System.Timers; -using System.Diagnostics; -using System.Windows.Controls; -using System.Threading.Tasks; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Windows; -using Microsoft.Win32; -using CLRBinding; -using Newtonsoft.Json.Linq; -using System.Windows.Media.Imaging; -using System.Windows.Media; - -namespace GameDev -{ - /// - /// Interaction logic for XMLEditor.xaml - /// - public partial class XMLEditor : UserControl, Editor - { - private bool changed_cache = false; - private string text_cache = ""; - private int cur_tab = 0; - - private string file_path; - - private CGLControl glControl = null; - private CGamePlayer game_player = null; - - private JObject index = null; - private Dictionary TreeItemMap = new Dictionary(); - - private ContextMenu ctxMenu; - - public XMLEditor(string file_path, string resource_root, PrintCallback print_std, PrintCallback print_err) - { - InitializeComponent(); - this.file_path = file_path; - - glControl = new CGLControl(); - glControl.SetFramerate(60.0f); - glControl.Paint += GLControl_Paint; - glControl.Dock = System.Windows.Forms.DockStyle.Fill; - glControl.MouseDown += GLControl_MouseDown; - glControl.MouseUp += GLControl_MouseUp; - glControl.MouseMove += GLControl_MouseMove; - glControl.MouseWheel += GLControl_MouseWheel; - glControl.KeyPress += GLControl_KeyChar; - glControl.ControlKey += GLControl_ControlKey; - wf_host.Child = glControl; - - string exe_name = Process.GetCurrentProcess().ProcessName; - game_player = new CGamePlayer(exe_name, glControl); - game_player.SetPrintCallbacks(print_std, print_err); - game_player.AddUserMessageHandler("index_loaded", index_loaded); - game_player.AddUserMessageHandler("object_picked", object_picked); - game_player.AddUserMessageHandler("object_created", object_created); - game_player.AddUserMessageHandler("object_removed", object_removed); - - string local_path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); - game_player.LoadScript($"{local_path}\\xmleditor\\bundle_index.js", resource_root); - - webView.Source = new Uri($"{local_path}/editor/xml_editor.html"); - webView.NavigationCompleted += (sender, e) => - { - _doc_open(file_path); - }; - - ctxMenu = new ContextMenu(); - var item_remove = new MenuItem(); - item_remove.Header = "Remove"; - ctxMenu.Items.Add(item_remove); - item_remove.Click += remove_Click; - } - - public void cleanup() - { - glControl.MakeCurrent(); - game_player.Dispose(); - game_player = null; - } - - public void gl_pause() - { - glControl.Pause(); - } - - public void gl_resume() - { - glControl.Resume(); - } - - private void GLControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e) - { - if (game_player == null) return; - game_player.Draw(glControl.Width, glControl.Height); - } - - private MouseEventArgs convert_args(System.Windows.Forms.MouseEventArgs e) - { - int button = -1; - if (e.Button == System.Windows.Forms.MouseButtons.Left) - { - button = 0; - } - else if (e.Button == System.Windows.Forms.MouseButtons.Middle) - { - button = 1; - } - else if (e.Button == System.Windows.Forms.MouseButtons.Right) - { - button = 2; - } - else if (e.Button == System.Windows.Forms.MouseButtons.XButton1) - { - button = 3; - } - else if (e.Button == System.Windows.Forms.MouseButtons.XButton2) - { - button = 4; - } - - MouseEventArgs args; - args.button = button; - args.clicks = e.Clicks; - args.delta = e.Delta; - args.x = e.X; - args.y = e.Y; - return args; - } - - private Timer press_timer = null; - private int x_down; - private int y_down; - - private void GLControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.Focus(); - glControl.MakeCurrent(); - game_player.OnMouseDown(convert_args(e)); - - if (e.Button == System.Windows.Forms.MouseButtons.Left) - { - x_down = e.X; - y_down = e.Y; - - press_timer = new Timer(); - press_timer.Elapsed += (source, timer_event) => - { - Dispatcher.Invoke(() => - { - press_timer = null; - game_player.OnLongPress(x_down, y_down); - }); - - }; - press_timer.AutoReset = false; - press_timer.Interval = 500.0; - press_timer.Start(); - } - } - - private void GLControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseUp(convert_args(e)); - - if (press_timer != null) - { - press_timer.Stop(); - press_timer = null; - } - } - - private void GLControl_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseMove(convert_args(e)); - - if (press_timer != null) - { - int x = e.X; - int y = e.Y; - - int dx = x - x_down; - int dy = y - y_down; - double dis = Math.Sqrt((double)(dx * dx) + (double)(dy * dy)); - if (dis > 3.0) - { - press_timer.Stop(); - press_timer = null; - } - - } - } - - private void GLControl_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseWheel(convert_args(e)); - } - - private void GLControl_ControlKey(uint code) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnControlKey(code); - } - - private void GLControl_KeyChar(object sender, System.Windows.Forms.KeyPressEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnChar(e.KeyChar); - e.Handled = true; - } - - - private async Task _doc_save(string filename) - { - string text = await GetText(); - File.WriteAllText(filename, text, Encoding.UTF8); - } - - private void _doc_open(string filename) - { - string text = File.ReadAllText(filename, Encoding.UTF8); - SetText(text); - } - - public async Task doc_save_as() - { - var dialog = new SaveFileDialog(); - dialog.Filter = "XML(*.xml)|*.xml"; - if (dialog.ShowDialog() != true) - { - return ""; - } - file_path = dialog.FileName; - await _doc_save(file_path); - return file_path; - } - - public async Task doc_save() - { - await _doc_save(file_path); - } - - public async Task doc_close() - { - bool changed = await TextChanged(); - if (changed) - { - gl_pause(); - var result = MessageBox.Show("File has been modified. Save it?", "Save file", MessageBoxButton.YesNoCancel); - if (result == MessageBoxResult.Yes) - { - await doc_save(); - gl_resume(); - return true; - } - else if (result == MessageBoxResult.No) - { - gl_resume(); - return true; - } - else - { - gl_resume(); - return false; - } - } - else - { - return true; - } - } - - public async Task doc_fresh() - { - if (await doc_close()) - { - _doc_open(file_path); - } - - } - - private async Task TextChanged_code() - { - string response = await webView.ExecuteScriptAsync("doc_modified()"); - return (bool)JsonConvert.DeserializeObject(response); - } - - private bool TextChanged_gl() - { - string ret = game_player.SendMessageToUser("isModified", ""); - return (bool)JsonConvert.DeserializeObject(ret); - } - - private async Task TextChanged() - { - if (changed_cache) return true; - if (cur_tab == 0) - { - return await TextChanged_code(); - } - else - { - return TextChanged_gl(); - } - } - - private async Task GetText_code() - { - bool changed = await TextChanged_code(); - if (changed) - { - string response = await webView.ExecuteScriptAsync("doc_get_text()"); - text_cache = JsonConvert.DeserializeObject(response).ToString(); - changed_cache = true; - } - return text_cache; - } - - private string GetText_gl() - { - bool changed = TextChanged_gl(); - if (changed) - { - text_cache = game_player.SendMessageToUser("getXML", ""); - changed_cache = true; - } - return text_cache; - } - - private async Task GetText() - { - if (cur_tab == 0) - { - await GetText_code(); - SetText_gl(text_cache); - } - else - { - GetText_gl(); - } - changed_cache = false; - return text_cache; - } - - private async Task SetText_code(string text) - { - string para = JsonConvert.SerializeObject(text); - await webView.ExecuteScriptAsync($"doc_set_text({para})"); - } - - private void SetText_gl(string text) - { - _ = game_player.SendMessageToUser("setXML", text); - } - - private async void SetText(string text) - { - text_cache = text; - changed_cache = false; - await SetText_code(text); - SetText_gl(text); - } - - - public void undo() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('undo');"); - } - } - - public void redo() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('redo');"); - } - } - - public void comment() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('togglecomment');"); - } - } - - public void upper() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('touppercase');"); - } - } - - public void lower() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('tolowercase');"); - } - } - - public void find() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('find');"); - } - } - - public void findnext() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('findnext');"); - } - } - - public void findprev() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('findprevious');"); - } - } - - public void replace() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('replace');"); - } - } - - public void gotoline() - { - if (cur_tab == 0) - { - webView.ExecuteScriptAsync("editor.execCommand('gotoline');"); - } - } - - private async void tab_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - if (tab.SelectedIndex == cur_tab) return; - - if (cur_tab == 0) - { - if (await TextChanged_code()) - { - gl_pause(); - if (MessageBox.Show("Code has changed, apply it to view?", "Apply changes", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) - { - await GetText_code(); - SetText_gl(text_cache); - } - gl_resume(); - } - } - else - { - if (tab.SelectedIndex == 0) - { - if (TextChanged_gl()) - { - GetText_gl(); - } - await SetText_code(text_cache); - } - - if (cur_tab == 1) - { - btn_picking.IsChecked = false; - } - } - - cur_tab = tab.SelectedIndex; - } - - private async void btn_apply_Click(object sender, RoutedEventArgs e) - { - await GetText_code(); - SetText_gl(text_cache); - } - - private void btn_picking_Checked(object sender, RoutedEventArgs e) - { - scene_graph.IsEnabled = false; - game_player.SendMessageToUser("picking", "on"); - } - - private void btn_picking_Unchecked(object sender, RoutedEventArgs e) - { - game_player.SendMessageToUser("picking", "off"); - scene_graph.IsEnabled = true; - } - - private StackPanel create_item(string name, string icon_name, int icon_size = 24) - { - var panel = new StackPanel(); - panel.Orientation = Orientation.Horizontal; - - var icon_image = new BitmapImage(new Uri($"pack://application:,,,/Icons/{icon_name}")); - var icon = new Image(); - icon.Source = icon_image; - RenderOptions.SetBitmapScalingMode(icon, BitmapScalingMode.HighQuality); - icon.Width = icon_size; - icon.Height = icon_size; - panel.Children.Add(icon); - - var label = new TextBlock(); - label.VerticalAlignment = VerticalAlignment.Center; - label.Text = name; - label.Margin = new Thickness(5.0); - panel.Children.Add(label); - return panel; - } - - private void update_index_item(TreeViewItem item, JObject obj) - { - JObject dict = (JObject)index["index"]; - JArray children = (JArray)obj["children"]; - foreach(string key in children) - { - JObject child = (JObject)dict[key]; - var subitem = new TreeViewItem(); - subitem.Tag = key; - TreeItemMap[key] = subitem; - string tagName = child["tagName"].ToString(); - JObject attributes = (JObject)child["attributes"]; - string name; - if (attributes.ContainsKey("name")) - { - name = attributes["name"].ToString(); - } - else - { - name = tagName; - } - - string icon_name = "object3d.png"; - if (tagName == "camera") - { - icon_name = "camera.png"; - } - else if (tagName == "fog") - { - icon_name = "fog.png"; - } - else if (tagName == "sky") - { - icon_name = "sky.png"; - } - else if (tagName == "env_light") - { - icon_name = "env_light.png"; - } - else if (tagName == "control") - { - icon_name = "control.png"; - } - else if (tagName == "group") - { - icon_name = "group.png"; - } - else if (tagName == "plane") - { - icon_name = "plane.png"; - } - else if (tagName == "box") - { - icon_name = "box.png"; - } - else if (tagName == "sphere") - { - icon_name = "sphere.png"; - } - else if (tagName == "model") - { - icon_name = "model.png"; - } - else if (tagName == "avatar") - { - icon_name = "avatar.png"; - } - else if (tagName == "directional_light") - { - icon_name = "directional_light.png"; - } - - subitem.Header = create_item(name, icon_name); - subitem.ContextMenu = ctxMenu; - item.Items.Add(subitem); - update_index_item(subitem, child); - } - - item.IsExpanded = true; - } - - private void update_index() - { - scene_graph.Items.Clear(); - TreeItemMap.Clear(); - - string key = index["root"].ToString(); - JObject dict = (JObject)index["index"]; - JObject root = (JObject)dict[key]; - var item = new TreeViewItem(); - item.Tag = key; - TreeItemMap[key] = item; - string tagName = root["tagName"].ToString(); - JObject attributes = (JObject)root["attributes"]; - string name; - if (attributes.ContainsKey("name")) - { - name = attributes["name"].ToString(); - } - else - { - name = tagName; - } - item.Header = create_item(name, "scene.png"); - scene_graph.Items.Add(item); - update_index_item(item, root); - } - - private string index_loaded(string json_str) - { - index = JObject.Parse(json_str); - update_index(); - return ""; - } - - private void update_name(object sender, EventArgs e) - { - if (picked_key == "") return; - TreeViewItem item = TreeItemMap[picked_key]; - JObject jobj = (JObject)index["index"][picked_key]; - StackPanel panel = (StackPanel)item.Header; - TextBlock txt = (TextBlock)panel.Children[1]; - txt.Text = jobj["attributes"]["name"].ToString(); - } - - private HashSet tags3d = new HashSet() { "scene", "group", "plane", "box", "sphere", "model", "avatar", "directional_light" }; - - private string picked_key = ""; - private string object_picked(string key) - { - picked_key = key; - property_area.Children.Clear(); - grp_scene_objs.IsEnabled = false; - grp_3d_objs.IsEnabled = false; - if (key != "") - { - var picked_obj = (JObject)index["index"][key]; - string tag = picked_obj["tagName"].ToString(); - if (tags3d.Contains(tag)) - { - grp_3d_objs.IsEnabled = true; - } - if (tag == "scene") - { - grp_scene_objs.IsEnabled = true; - var tuner = new SceneTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - } - else if (tag == "fog") - { - var tuner = new FogTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - } - else if (tag == "sky") - { - var tuner = new SkyTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - } - else if (tag == "env_light") - { - var tuner = new EnvLightTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - } - else if (tag == "group") - { - var tuner = new GroupTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - tuner.obj3d_tuner.UpdateName += update_name; - } - else if (tag == "plane") - { - var tuner = new PlaneTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - tuner.obj3d_tuner.UpdateName += update_name; - } - else if (tag == "box") - { - var tuner = new BoxTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - tuner.obj3d_tuner.UpdateName += update_name; - } - else if (tag == "sphere") - { - var tuner = new SphereTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - tuner.obj3d_tuner.UpdateName += update_name; - } - else if (tag == "model" || tag == "avatar") - { - var tuner = new ModelTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - tuner.obj3d_tuner.UpdateName += update_name; - } - else if (tag == "directional_light") - { - var tuner = new DirectionalLightTuner(game_player, picked_obj); - property_area.Children.Add(tuner); - tuner.obj3d_tuner.UpdateName += update_name; - } - - var treeItem = TreeItemMap[key]; - treeItem.IsSelected = true; - } - btn_picking.IsChecked = false; - return ""; - } - - private void scene_graph_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e) - { - if (btn_picking.IsChecked == true) return; - var item = (TreeViewItem)scene_graph.SelectedItem; - if (item!=null) - { - string key = (string)item.Tag; - game_player.SendMessageToUser("pick_obj", key); - } - } - - private string object_created(string json_str) - { - JObject info = JObject.Parse(json_str); - foreach (var item in info) - { - string key = item.Key; - JObject node = (JObject)item.Value; - string key_parent = node["parent"].ToString(); - JObject parent = (JObject)index["index"][key_parent]; - index["index"][key] = node; - JArray children = (JArray)parent["children"]; - children.Add(key); - } - update_index(); - return ""; - } - - private string object_removed(string key) - { - JObject node = (JObject)index["index"][key]; - ((JObject)index["index"]).Remove(key); - - string key_parent = node["parent"].ToString(); - JObject parent = (JObject)index["index"][key_parent]; - JArray children = (JArray)parent["children"]; - - foreach (var child_key in children) - { - if ((string)child_key == key) - { - children.Remove(child_key); - break; - } - } - - update_index(); - return ""; - } - - private void req_create_scene_obj(string tag) - { - JObject base_obj = (JObject)index["index"][picked_key]; - JArray children = (JArray)base_obj["children"]; - - string key_existing = ""; - foreach (string key in base_obj["children"]) - { - JObject child = (JObject)index["index"][key]; - if (child["tagName"].ToString() == tag) - { - key_existing = key; - break; - } - } - - if (key_existing!="") - { - game_player.SendMessageToUser("pick_obj", key_existing); - return; - } - - JObject req = new JObject(); - req["base_key"] = picked_key; - req["tag"] = tag; - game_player.SendMessageToUser("create", req.ToString()); - } - - private void req_create_obj3d(string tag) - { - JObject req = new JObject(); - req["base_key"] = picked_key; - req["tag"] = tag; - game_player.SendMessageToUser("create", req.ToString()); - } - - private void btn_create_fog_Click(object sender, RoutedEventArgs e) - { - req_create_scene_obj("fog"); - } - - private void btn_create_sky_Click(object sender, RoutedEventArgs e) - { - req_create_scene_obj("sky"); - } - - private void btn_create_env_light_Click(object sender, RoutedEventArgs e) - { - req_create_scene_obj("env_light"); - } - - private void btn_create_group_Click(object sender, RoutedEventArgs e) - { - req_create_obj3d("group"); - } - - private void btn_create_plane_Click(object sender, RoutedEventArgs e) - { - req_create_obj3d("plane"); - } - - private void btn_create_box_Click(object sender, RoutedEventArgs e) - { - req_create_obj3d("box"); - } - - private void btn_create_sphere_Click(object sender, RoutedEventArgs e) - { - req_create_obj3d("sphere"); - } - - private void btn_create_model_Click(object sender, RoutedEventArgs e) - { - req_create_obj3d("model"); - } - - private void btn_create_directional_light_Click(object sender, RoutedEventArgs e) - { - req_create_obj3d("directional_light"); - } - - private void remove_Click(object sender, RoutedEventArgs e) - { - MenuItem mi = sender as MenuItem; - if (mi != null) - { - ContextMenu cm = (ContextMenu)mi.Parent; - TreeViewItem item = (TreeViewItem)cm.PlacementTarget; - string key = (string)item.Tag; - JObject obj = (JObject)index["index"][key]; - string tag = (string)obj["tagName"]; - JObject att = (JObject)obj["attributes"]; - string name; - if (att.ContainsKey("name")) - { - name = (string)att["name"]; - } - else - { - name = tag; - } - - gl_pause(); - if (MessageBox.Show($"Remove {tag} object \"{name}\" and all its children from scene?", "Remove Object", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) - { - game_player.SendMessageToUser("remove", key); - } - gl_resume(); - } - - } - } -} diff --git a/GameDev/bin/Release/GamePlayer.exe b/GameDev/bin/Release/GamePlayer.exe deleted file mode 100644 index 29090a75..00000000 Binary files a/GameDev/bin/Release/GamePlayer.exe and /dev/null differ diff --git a/GameDev/bin/Release/avcodec-58.dll b/GameDev/bin/Release/avcodec-58.dll deleted file mode 100644 index fe98cee2..00000000 Binary files a/GameDev/bin/Release/avcodec-58.dll and /dev/null differ diff --git a/GameDev/bin/Release/avdevice-58.dll b/GameDev/bin/Release/avdevice-58.dll deleted file mode 100644 index 2fa0acf6..00000000 Binary files a/GameDev/bin/Release/avdevice-58.dll and /dev/null differ diff --git a/GameDev/bin/Release/avfilter-7.dll b/GameDev/bin/Release/avfilter-7.dll deleted file mode 100644 index 1e36c5ed..00000000 Binary files a/GameDev/bin/Release/avfilter-7.dll and /dev/null differ diff --git a/GameDev/bin/Release/avformat-58.dll b/GameDev/bin/Release/avformat-58.dll deleted file mode 100644 index 4f875564..00000000 Binary files a/GameDev/bin/Release/avformat-58.dll and /dev/null differ diff --git a/GameDev/bin/Release/avutil-56.dll b/GameDev/bin/Release/avutil-56.dll deleted file mode 100644 index 29fdb519..00000000 Binary files a/GameDev/bin/Release/avutil-56.dll and /dev/null differ diff --git a/GameDev/bin/Release/editor/ace/ace.js b/GameDev/bin/Release/editor/ace/ace.js deleted file mode 100644 index 60746207..00000000 --- a/GameDev/bin/Release/editor/ace/ace.js +++ /dev/null @@ -1,21402 +0,0 @@ -/* ***** BEGIN LICENSE BLOCK ***** - * Distributed under the BSD license: - * - * Copyright (c) 2010, Ajax.org B.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Ajax.org B.V. nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * ***** END LICENSE BLOCK ***** */ - -/** - * Define a module along with a payload - * @param module a name for the payload - * @param payload a function to call with (require, exports, module) params - */ - -(function() { - -var ACE_NAMESPACE = ""; - -var global = (function() { return this; })(); -if (!global && typeof window != "undefined") global = window; // strict mode - - -if (!ACE_NAMESPACE && typeof requirejs !== "undefined") - return; - - -var define = function(module, deps, payload) { - if (typeof module !== "string") { - if (define.original) - define.original.apply(this, arguments); - else { - console.error("dropping module because define wasn\'t a string."); - console.trace(); - } - return; - } - if (arguments.length == 2) - payload = deps; - if (!define.modules[module]) { - define.payloads[module] = payload; - define.modules[module] = null; - } -}; - -define.modules = {}; -define.payloads = {}; - -/** - * Get at functionality define()ed using the function above - */ -var _require = function(parentId, module, callback) { - if (typeof module === "string") { - var payload = lookup(parentId, module); - if (payload != undefined) { - callback && callback(); - return payload; - } - } else if (Object.prototype.toString.call(module) === "[object Array]") { - var params = []; - for (var i = 0, l = module.length; i < l; ++i) { - var dep = lookup(parentId, module[i]); - if (dep == undefined && require.original) - return; - params.push(dep); - } - return callback && callback.apply(null, params) || true; - } -}; - -var require = function(module, callback) { - var packagedModule = _require("", module, callback); - if (packagedModule == undefined && require.original) - return require.original.apply(this, arguments); - return packagedModule; -}; - -var normalizeModule = function(parentId, moduleName) { - // normalize plugin requires - if (moduleName.indexOf("!") !== -1) { - var chunks = moduleName.split("!"); - return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); - } - // normalize relative requires - if (moduleName.charAt(0) == ".") { - var base = parentId.split("/").slice(0, -1).join("/"); - moduleName = base + "/" + moduleName; - - while(moduleName.indexOf(".") !== -1 && previous != moduleName) { - var previous = moduleName; - moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); - } - } - return moduleName; -}; - -/** - * Internal function to lookup moduleNames and resolve them by calling the - * definition function if needed. - */ -var lookup = function(parentId, moduleName) { - moduleName = normalizeModule(parentId, moduleName); - - var module = define.modules[moduleName]; - if (!module) { - module = define.payloads[moduleName]; - if (typeof module === 'function') { - var exports = {}; - var mod = { - id: moduleName, - uri: '', - exports: exports, - packaged: true - }; - - var req = function(module, callback) { - return _require(moduleName, module, callback); - }; - - var returnValue = module(req, exports, mod); - exports = returnValue || mod.exports; - define.modules[moduleName] = exports; - delete define.payloads[moduleName]; - } - module = define.modules[moduleName] = exports || module; - } - return module; -}; - -function exportAce(ns) { - var root = global; - if (ns) { - if (!global[ns]) - global[ns] = {}; - root = global[ns]; - } - - if (!root.define || !root.define.packaged) { - define.original = root.define; - root.define = define; - root.define.packaged = true; - } - - if (!root.require || !root.require.packaged) { - require.original = root.require; - root.require = require; - root.require.packaged = true; - } -} - -exportAce(ACE_NAMESPACE); - -})(); - -define("ace/lib/fixoldbrowsers",["require","exports","module"], function(require, exports, module) { -"use strict"; -if (typeof Element != "undefined" && !Element.prototype.remove) { - Object.defineProperty(Element.prototype, "remove", { - enumerable: false, - writable: true, - configurable: true, - value: function() { this.parentNode && this.parentNode.removeChild(this); } - }); -} - - -}); - -define("ace/lib/useragent",["require","exports","module"], function(require, exports, module) { -"use strict"; -exports.OS = { - LINUX: "LINUX", - MAC: "MAC", - WINDOWS: "WINDOWS" -}; -exports.getOS = function() { - if (exports.isMac) { - return exports.OS.MAC; - } else if (exports.isLinux) { - return exports.OS.LINUX; - } else { - return exports.OS.WINDOWS; - } -}; -var _navigator = typeof navigator == "object" ? navigator : {}; - -var os = (/mac|win|linux/i.exec(_navigator.platform) || ["other"])[0].toLowerCase(); -var ua = _navigator.userAgent || ""; -var appName = _navigator.appName || ""; -exports.isWin = (os == "win"); -exports.isMac = (os == "mac"); -exports.isLinux = (os == "linux"); -exports.isIE = - (appName == "Microsoft Internet Explorer" || appName.indexOf("MSAppHost") >= 0) - ? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]) - : parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie - -exports.isOldIE = exports.isIE && exports.isIE < 9; -exports.isGecko = exports.isMozilla = ua.match(/ Gecko\/\d+/); -exports.isOpera = typeof opera == "object" && Object.prototype.toString.call(window.opera) == "[object Opera]"; -exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined; - -exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined; - -exports.isEdge = parseFloat(ua.split(" Edge/")[1]) || undefined; - -exports.isAIR = ua.indexOf("AdobeAIR") >= 0; - -exports.isAndroid = ua.indexOf("Android") >= 0; - -exports.isChromeOS = ua.indexOf(" CrOS ") >= 0; - -exports.isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream; - -if (exports.isIOS) exports.isMac = true; - -exports.isMobile = exports.isIOS || exports.isAndroid; - -}); - -define("ace/lib/dom",["require","exports","module","ace/lib/useragent"], function(require, exports, module) { -"use strict"; - -var useragent = require("./useragent"); -var XHTML_NS = "http://www.w3.org/1999/xhtml"; - -exports.buildDom = function buildDom(arr, parent, refs) { - if (typeof arr == "string" && arr) { - var txt = document.createTextNode(arr); - if (parent) - parent.appendChild(txt); - return txt; - } - - if (!Array.isArray(arr)) { - if (arr && arr.appendChild && parent) - parent.appendChild(arr); - return arr; - } - if (typeof arr[0] != "string" || !arr[0]) { - var els = []; - for (var i = 0; i < arr.length; i++) { - var ch = buildDom(arr[i], parent, refs); - ch && els.push(ch); - } - return els; - } - - var el = document.createElement(arr[0]); - var options = arr[1]; - var childIndex = 1; - if (options && typeof options == "object" && !Array.isArray(options)) - childIndex = 2; - for (var i = childIndex; i < arr.length; i++) - buildDom(arr[i], el, refs); - if (childIndex == 2) { - Object.keys(options).forEach(function(n) { - var val = options[n]; - if (n === "class") { - el.className = Array.isArray(val) ? val.join(" ") : val; - } else if (typeof val == "function" || n == "value" || n[0] == "$") { - el[n] = val; - } else if (n === "ref") { - if (refs) refs[val] = el; - } else if (n === "style") { - if (typeof val == "string") el.style.cssText = val; - } else if (val != null) { - el.setAttribute(n, val); - } - }); - } - if (parent) - parent.appendChild(el); - return el; -}; - -exports.getDocumentHead = function(doc) { - if (!doc) - doc = document; - return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement; -}; - -exports.createElement = function(tag, ns) { - return document.createElementNS ? - document.createElementNS(ns || XHTML_NS, tag) : - document.createElement(tag); -}; - -exports.removeChildren = function(element) { - element.innerHTML = ""; -}; - -exports.createTextNode = function(textContent, element) { - var doc = element ? element.ownerDocument : document; - return doc.createTextNode(textContent); -}; - -exports.createFragment = function(element) { - var doc = element ? element.ownerDocument : document; - return doc.createDocumentFragment(); -}; - -exports.hasCssClass = function(el, name) { - var classes = (el.className + "").split(/\s+/g); - return classes.indexOf(name) !== -1; -}; -exports.addCssClass = function(el, name) { - if (!exports.hasCssClass(el, name)) { - el.className += " " + name; - } -}; -exports.removeCssClass = function(el, name) { - var classes = el.className.split(/\s+/g); - while (true) { - var index = classes.indexOf(name); - if (index == -1) { - break; - } - classes.splice(index, 1); - } - el.className = classes.join(" "); -}; - -exports.toggleCssClass = function(el, name) { - var classes = el.className.split(/\s+/g), add = true; - while (true) { - var index = classes.indexOf(name); - if (index == -1) { - break; - } - add = false; - classes.splice(index, 1); - } - if (add) - classes.push(name); - - el.className = classes.join(" "); - return add; -}; -exports.setCssClass = function(node, className, include) { - if (include) { - exports.addCssClass(node, className); - } else { - exports.removeCssClass(node, className); - } -}; - -exports.hasCssString = function(id, doc) { - var index = 0, sheets; - doc = doc || document; - if ((sheets = doc.querySelectorAll("style"))) { - while (index < sheets.length) - if (sheets[index++].id === id) - return true; - } -}; - -var strictCSP; -var cssCache = []; -exports.useStrictCSP = function(value) { - strictCSP = value; - if (value == false) insertPendingStyles(); - else if (!cssCache) cssCache = []; -}; - -function insertPendingStyles() { - var cache = cssCache; - cssCache = null; - cache && cache.forEach(function(item) { - importCssString(item[0], item[1]); - }); -} - -function importCssString(cssText, id, target) { - if (typeof document == "undefined") - return; - if (cssCache) { - if (target) { - insertPendingStyles(); - } else if (target === false) { - return cssCache.push([cssText, id]); - } - } - if (strictCSP) return; - - var container = target; - if (!target || !target.getRootNode) { - container = document; - } else { - container = target.getRootNode(); - if (!container || container == target) - container = document; - } - - var doc = container.ownerDocument || container; - if (id && exports.hasCssString(id, container)) - return null; - - if (id) - cssText += "\n/*# sourceURL=ace/css/" + id + " */"; - - var style = exports.createElement("style"); - style.appendChild(doc.createTextNode(cssText)); - if (id) - style.id = id; - - if (container == doc) - container = exports.getDocumentHead(doc); - container.insertBefore(style, container.firstChild); -} -exports.importCssString = importCssString; - -exports.importCssStylsheet = function(uri, doc) { - exports.buildDom(["link", {rel: "stylesheet", href: uri}], exports.getDocumentHead(doc)); -}; -exports.scrollbarWidth = function(document) { - var inner = exports.createElement("ace_inner"); - inner.style.width = "100%"; - inner.style.minWidth = "0px"; - inner.style.height = "200px"; - inner.style.display = "block"; - - var outer = exports.createElement("ace_outer"); - var style = outer.style; - - style.position = "absolute"; - style.left = "-10000px"; - style.overflow = "hidden"; - style.width = "200px"; - style.minWidth = "0px"; - style.height = "150px"; - style.display = "block"; - - outer.appendChild(inner); - - var body = document.documentElement; - body.appendChild(outer); - - var noScrollbar = inner.offsetWidth; - - style.overflow = "scroll"; - var withScrollbar = inner.offsetWidth; - - if (noScrollbar == withScrollbar) { - withScrollbar = outer.clientWidth; - } - - body.removeChild(outer); - - return noScrollbar-withScrollbar; -}; - -exports.computedStyle = function(element, style) { - return window.getComputedStyle(element, "") || {}; -}; - -exports.setStyle = function(styles, property, value) { - if (styles[property] !== value) { - styles[property] = value; - } -}; - -exports.HAS_CSS_ANIMATION = false; -exports.HAS_CSS_TRANSFORMS = false; -exports.HI_DPI = useragent.isWin - ? typeof window !== "undefined" && window.devicePixelRatio >= 1.5 - : true; - -if (useragent.isChromeOS) exports.HI_DPI = false; - -if (typeof document !== "undefined") { - var div = document.createElement("div"); - if (exports.HI_DPI && div.style.transform !== undefined) - exports.HAS_CSS_TRANSFORMS = true; - if (!useragent.isEdge && typeof div.style.animationName !== "undefined") - exports.HAS_CSS_ANIMATION = true; - div = null; -} - -if (exports.HAS_CSS_TRANSFORMS) { - exports.translate = function(element, tx, ty) { - element.style.transform = "translate(" + Math.round(tx) + "px, " + Math.round(ty) +"px)"; - }; -} else { - exports.translate = function(element, tx, ty) { - element.style.top = Math.round(ty) + "px"; - element.style.left = Math.round(tx) + "px"; - }; -} - -}); - -define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { -"use strict"; - -exports.inherits = function(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); -}; - -exports.mixin = function(obj, mixin) { - for (var key in mixin) { - obj[key] = mixin[key]; - } - return obj; -}; - -exports.implement = function(proto, mixin) { - exports.mixin(proto, mixin); -}; - -}); - -define("ace/lib/keys",["require","exports","module","ace/lib/oop"], function(require, exports, module) { -"use strict"; - -var oop = require("./oop"); -var Keys = (function() { - var ret = { - MODIFIER_KEYS: { - 16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta', - 91: 'MetaLeft', 92: 'MetaRight', 93: 'ContextMenu' - }, - - KEY_MODS: { - "ctrl": 1, "alt": 2, "option" : 2, "shift": 4, - "super": 8, "meta": 8, "command": 8, "cmd": 8, - "control": 1 - }, - - FUNCTION_KEYS : { - 8 : "Backspace", - 9 : "Tab", - 13 : "Return", - 19 : "Pause", - 27 : "Esc", - 32 : "Space", - 33 : "PageUp", - 34 : "PageDown", - 35 : "End", - 36 : "Home", - 37 : "Left", - 38 : "Up", - 39 : "Right", - 40 : "Down", - 44 : "Print", - 45 : "Insert", - 46 : "Delete", - 96 : "Numpad0", - 97 : "Numpad1", - 98 : "Numpad2", - 99 : "Numpad3", - 100: "Numpad4", - 101: "Numpad5", - 102: "Numpad6", - 103: "Numpad7", - 104: "Numpad8", - 105: "Numpad9", - '-13': "NumpadEnter", - 112: "F1", - 113: "F2", - 114: "F3", - 115: "F4", - 116: "F5", - 117: "F6", - 118: "F7", - 119: "F8", - 120: "F9", - 121: "F10", - 122: "F11", - 123: "F12", - 144: "Numlock", - 145: "Scrolllock" - }, - - PRINTABLE_KEYS: { - 32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', - 54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a', - 66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h', - 73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o', - 80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v', - 87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.', - 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', - 219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*' - } - }; - var name, i; - for (i in ret.FUNCTION_KEYS) { - name = ret.FUNCTION_KEYS[i].toLowerCase(); - ret[name] = parseInt(i, 10); - } - for (i in ret.PRINTABLE_KEYS) { - name = ret.PRINTABLE_KEYS[i].toLowerCase(); - ret[name] = parseInt(i, 10); - } - oop.mixin(ret, ret.MODIFIER_KEYS); - oop.mixin(ret, ret.PRINTABLE_KEYS); - oop.mixin(ret, ret.FUNCTION_KEYS); - ret.enter = ret["return"]; - ret.escape = ret.esc; - ret.del = ret["delete"]; - ret[173] = '-'; - - (function() { - var mods = ["cmd", "ctrl", "alt", "shift"]; - for (var i = Math.pow(2, mods.length); i--;) { - ret.KEY_MODS[i] = mods.filter(function(x) { - return i & ret.KEY_MODS[x]; - }).join("-") + "-"; - } - })(); - - ret.KEY_MODS[0] = ""; - ret.KEY_MODS[-1] = "input-"; - - return ret; -})(); -oop.mixin(exports, Keys); - -exports.keyCodeToString = function(keyCode) { - var keyString = Keys[keyCode]; - if (typeof keyString != "string") - keyString = String.fromCharCode(keyCode); - return keyString.toLowerCase(); -}; - -}); - -define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(require, exports, module) { -"use strict"; - -var keys = require("./keys"); -var useragent = require("./useragent"); - -var pressedKeys = null; -var ts = 0; - -var activeListenerOptions; -function detectListenerOptionsSupport() { - activeListenerOptions = false; - try { - document.createComment("").addEventListener("test", function() {}, { - get passive() { - activeListenerOptions = {passive: false}; - } - }); - } catch(e) {} -} - -function getListenerOptions() { - if (activeListenerOptions == undefined) - detectListenerOptionsSupport(); - return activeListenerOptions; -} - -function EventListener(elem, type, callback) { - this.elem = elem; - this.type = type; - this.callback = callback; -} -EventListener.prototype.destroy = function() { - removeListener(this.elem, this.type, this.callback); - this.elem = this.type = this.callback = undefined; -}; - -var addListener = exports.addListener = function(elem, type, callback, destroyer) { - elem.addEventListener(type, callback, getListenerOptions()); - if (destroyer) - destroyer.$toDestroy.push(new EventListener(elem, type, callback)); -}; - -var removeListener = exports.removeListener = function(elem, type, callback) { - elem.removeEventListener(type, callback, getListenerOptions()); -}; -exports.stopEvent = function(e) { - exports.stopPropagation(e); - exports.preventDefault(e); - return false; -}; - -exports.stopPropagation = function(e) { - if (e.stopPropagation) - e.stopPropagation(); -}; - -exports.preventDefault = function(e) { - if (e.preventDefault) - e.preventDefault(); -}; -exports.getButton = function(e) { - if (e.type == "dblclick") - return 0; - if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey))) - return 2; - return e.button; -}; - -exports.capture = function(el, eventHandler, releaseCaptureHandler) { - var ownerDocument = el && el.ownerDocument || document; - function onMouseUp(e) { - eventHandler && eventHandler(e); - releaseCaptureHandler && releaseCaptureHandler(e); - - removeListener(ownerDocument, "mousemove", eventHandler); - removeListener(ownerDocument, "mouseup", onMouseUp); - removeListener(ownerDocument, "dragstart", onMouseUp); - } - - addListener(ownerDocument, "mousemove", eventHandler); - addListener(ownerDocument, "mouseup", onMouseUp); - addListener(ownerDocument, "dragstart", onMouseUp); - - return onMouseUp; -}; - -exports.addMouseWheelListener = function(el, callback, destroyer) { - if ("onmousewheel" in el) { - addListener(el, "mousewheel", function(e) { - var factor = 8; - if (e.wheelDeltaX !== undefined) { - e.wheelX = -e.wheelDeltaX / factor; - e.wheelY = -e.wheelDeltaY / factor; - } else { - e.wheelX = 0; - e.wheelY = -e.wheelDelta / factor; - } - callback(e); - }, destroyer); - } else if ("onwheel" in el) { - addListener(el, "wheel", function(e) { - var factor = 0.35; - switch (e.deltaMode) { - case e.DOM_DELTA_PIXEL: - e.wheelX = e.deltaX * factor || 0; - e.wheelY = e.deltaY * factor || 0; - break; - case e.DOM_DELTA_LINE: - case e.DOM_DELTA_PAGE: - e.wheelX = (e.deltaX || 0) * 5; - e.wheelY = (e.deltaY || 0) * 5; - break; - } - - callback(e); - }, destroyer); - } else { - addListener(el, "DOMMouseScroll", function(e) { - if (e.axis && e.axis == e.HORIZONTAL_AXIS) { - e.wheelX = (e.detail || 0) * 5; - e.wheelY = 0; - } else { - e.wheelX = 0; - e.wheelY = (e.detail || 0) * 5; - } - callback(e); - }, destroyer); - } -}; - -exports.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName, destroyer) { - var clicks = 0; - var startX, startY, timer; - var eventNames = { - 2: "dblclick", - 3: "tripleclick", - 4: "quadclick" - }; - - function onMousedown(e) { - if (exports.getButton(e) !== 0) { - clicks = 0; - } else if (e.detail > 1) { - clicks++; - if (clicks > 4) - clicks = 1; - } else { - clicks = 1; - } - if (useragent.isIE) { - var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5; - if (!timer || isNewClick) - clicks = 1; - if (timer) - clearTimeout(timer); - timer = setTimeout(function() {timer = null;}, timeouts[clicks - 1] || 600); - - if (clicks == 1) { - startX = e.clientX; - startY = e.clientY; - } - } - - e._clicks = clicks; - - eventHandler[callbackName]("mousedown", e); - - if (clicks > 4) - clicks = 0; - else if (clicks > 1) - return eventHandler[callbackName](eventNames[clicks], e); - } - if (!Array.isArray(elements)) - elements = [elements]; - elements.forEach(function(el) { - addListener(el, "mousedown", onMousedown, destroyer); - }); -}; - -var getModifierHash = function(e) { - return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0); -}; - -exports.getModifierString = function(e) { - return keys.KEY_MODS[getModifierHash(e)]; -}; - -function normalizeCommandKeys(callback, e, keyCode) { - var hashId = getModifierHash(e); - - if (!useragent.isMac && pressedKeys) { - if (e.getModifierState && (e.getModifierState("OS") || e.getModifierState("Win"))) - hashId |= 8; - if (pressedKeys.altGr) { - if ((3 & hashId) != 3) - pressedKeys.altGr = 0; - else - return; - } - if (keyCode === 18 || keyCode === 17) { - var location = "location" in e ? e.location : e.keyLocation; - if (keyCode === 17 && location === 1) { - if (pressedKeys[keyCode] == 1) - ts = e.timeStamp; - } else if (keyCode === 18 && hashId === 3 && location === 2) { - var dt = e.timeStamp - ts; - if (dt < 50) - pressedKeys.altGr = true; - } - } - } - - if (keyCode in keys.MODIFIER_KEYS) { - keyCode = -1; - } - - if (!hashId && keyCode === 13) { - var location = "location" in e ? e.location : e.keyLocation; - if (location === 3) { - callback(e, hashId, -keyCode); - if (e.defaultPrevented) - return; - } - } - - if (useragent.isChromeOS && hashId & 8) { - callback(e, hashId, keyCode); - if (e.defaultPrevented) - return; - else - hashId &= ~8; - } - if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) { - return false; - } - - return callback(e, hashId, keyCode); -} - - -exports.addCommandKeyListener = function(el, callback, destroyer) { - if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) { - var lastKeyDownKeyCode = null; - addListener(el, "keydown", function(e) { - lastKeyDownKeyCode = e.keyCode; - }, destroyer); - addListener(el, "keypress", function(e) { - return normalizeCommandKeys(callback, e, lastKeyDownKeyCode); - }, destroyer); - } else { - var lastDefaultPrevented = null; - - addListener(el, "keydown", function(e) { - pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1; - var result = normalizeCommandKeys(callback, e, e.keyCode); - lastDefaultPrevented = e.defaultPrevented; - return result; - }, destroyer); - - addListener(el, "keypress", function(e) { - if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) { - exports.stopEvent(e); - lastDefaultPrevented = null; - } - }, destroyer); - - addListener(el, "keyup", function(e) { - pressedKeys[e.keyCode] = null; - }, destroyer); - - if (!pressedKeys) { - resetPressedKeys(); - addListener(window, "focus", resetPressedKeys); - } - } -}; -function resetPressedKeys() { - pressedKeys = Object.create(null); -} - -if (typeof window == "object" && window.postMessage && !useragent.isOldIE) { - var postMessageId = 1; - exports.nextTick = function(callback, win) { - win = win || window; - var messageName = "zero-timeout-message-" + (postMessageId++); - - var listener = function(e) { - if (e.data == messageName) { - exports.stopPropagation(e); - removeListener(win, "message", listener); - callback(); - } - }; - - addListener(win, "message", listener); - win.postMessage(messageName, "*"); - }; -} - -exports.$idleBlocked = false; -exports.onIdle = function(cb, timeout) { - return setTimeout(function handler() { - if (!exports.$idleBlocked) { - cb(); - } else { - setTimeout(handler, 100); - } - }, timeout); -}; - -exports.$idleBlockId = null; -exports.blockIdle = function(delay) { - if (exports.$idleBlockId) - clearTimeout(exports.$idleBlockId); - - exports.$idleBlocked = true; - exports.$idleBlockId = setTimeout(function() { - exports.$idleBlocked = false; - }, delay || 100); -}; - -exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame - || window.mozRequestAnimationFrame - || window.webkitRequestAnimationFrame - || window.msRequestAnimationFrame - || window.oRequestAnimationFrame); - -if (exports.nextFrame) - exports.nextFrame = exports.nextFrame.bind(window); -else - exports.nextFrame = function(callback) { - setTimeout(callback, 17); - }; -}); - -define("ace/range",["require","exports","module"], function(require, exports, module) { -"use strict"; -var comparePoints = function(p1, p2) { - return p1.row - p2.row || p1.column - p2.column; -}; -var Range = function(startRow, startColumn, endRow, endColumn) { - this.start = { - row: startRow, - column: startColumn - }; - - this.end = { - row: endRow, - column: endColumn - }; -}; - -(function() { - this.isEqual = function(range) { - return this.start.row === range.start.row && - this.end.row === range.end.row && - this.start.column === range.start.column && - this.end.column === range.end.column; - }; - this.toString = function() { - return ("Range: [" + this.start.row + "/" + this.start.column + - "] -> [" + this.end.row + "/" + this.end.column + "]"); - }; - - this.contains = function(row, column) { - return this.compare(row, column) == 0; - }; - this.compareRange = function(range) { - var cmp, - end = range.end, - start = range.start; - - cmp = this.compare(end.row, end.column); - if (cmp == 1) { - cmp = this.compare(start.row, start.column); - if (cmp == 1) { - return 2; - } else if (cmp == 0) { - return 1; - } else { - return 0; - } - } else if (cmp == -1) { - return -2; - } else { - cmp = this.compare(start.row, start.column); - if (cmp == -1) { - return -1; - } else if (cmp == 1) { - return 42; - } else { - return 0; - } - } - }; - this.comparePoint = function(p) { - return this.compare(p.row, p.column); - }; - this.containsRange = function(range) { - return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; - }; - this.intersects = function(range) { - var cmp = this.compareRange(range); - return (cmp == -1 || cmp == 0 || cmp == 1); - }; - this.isEnd = function(row, column) { - return this.end.row == row && this.end.column == column; - }; - this.isStart = function(row, column) { - return this.start.row == row && this.start.column == column; - }; - this.setStart = function(row, column) { - if (typeof row == "object") { - this.start.column = row.column; - this.start.row = row.row; - } else { - this.start.row = row; - this.start.column = column; - } - }; - this.setEnd = function(row, column) { - if (typeof row == "object") { - this.end.column = row.column; - this.end.row = row.row; - } else { - this.end.row = row; - this.end.column = column; - } - }; - this.inside = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isEnd(row, column) || this.isStart(row, column)) { - return false; - } else { - return true; - } - } - return false; - }; - this.insideStart = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isEnd(row, column)) { - return false; - } else { - return true; - } - } - return false; - }; - this.insideEnd = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isStart(row, column)) { - return false; - } else { - return true; - } - } - return false; - }; - this.compare = function(row, column) { - if (!this.isMultiLine()) { - if (row === this.start.row) { - return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); - } - } - - if (row < this.start.row) - return -1; - - if (row > this.end.row) - return 1; - - if (this.start.row === row) - return column >= this.start.column ? 0 : -1; - - if (this.end.row === row) - return column <= this.end.column ? 0 : 1; - - return 0; - }; - this.compareStart = function(row, column) { - if (this.start.row == row && this.start.column == column) { - return -1; - } else { - return this.compare(row, column); - } - }; - this.compareEnd = function(row, column) { - if (this.end.row == row && this.end.column == column) { - return 1; - } else { - return this.compare(row, column); - } - }; - this.compareInside = function(row, column) { - if (this.end.row == row && this.end.column == column) { - return 1; - } else if (this.start.row == row && this.start.column == column) { - return -1; - } else { - return this.compare(row, column); - } - }; - this.clipRows = function(firstRow, lastRow) { - if (this.end.row > lastRow) - var end = {row: lastRow + 1, column: 0}; - else if (this.end.row < firstRow) - var end = {row: firstRow, column: 0}; - - if (this.start.row > lastRow) - var start = {row: lastRow + 1, column: 0}; - else if (this.start.row < firstRow) - var start = {row: firstRow, column: 0}; - - return Range.fromPoints(start || this.start, end || this.end); - }; - this.extend = function(row, column) { - var cmp = this.compare(row, column); - - if (cmp == 0) - return this; - else if (cmp == -1) - var start = {row: row, column: column}; - else - var end = {row: row, column: column}; - - return Range.fromPoints(start || this.start, end || this.end); - }; - - this.isEmpty = function() { - return (this.start.row === this.end.row && this.start.column === this.end.column); - }; - this.isMultiLine = function() { - return (this.start.row !== this.end.row); - }; - this.clone = function() { - return Range.fromPoints(this.start, this.end); - }; - this.collapseRows = function() { - if (this.end.column == 0) - return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0); - else - return new Range(this.start.row, 0, this.end.row, 0); - }; - this.toScreenRange = function(session) { - var screenPosStart = session.documentToScreenPosition(this.start); - var screenPosEnd = session.documentToScreenPosition(this.end); - - return new Range( - screenPosStart.row, screenPosStart.column, - screenPosEnd.row, screenPosEnd.column - ); - }; - this.moveBy = function(row, column) { - this.start.row += row; - this.start.column += column; - this.end.row += row; - this.end.column += column; - }; - -}).call(Range.prototype); -Range.fromPoints = function(start, end) { - return new Range(start.row, start.column, end.row, end.column); -}; -Range.comparePoints = comparePoints; - -Range.comparePoints = function(p1, p2) { - return p1.row - p2.row || p1.column - p2.column; -}; - - -exports.Range = Range; -}); - -define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { -"use strict"; - -exports.last = function(a) { - return a[a.length - 1]; -}; - -exports.stringReverse = function(string) { - return string.split("").reverse().join(""); -}; - -exports.stringRepeat = function (string, count) { - var result = ''; - while (count > 0) { - if (count & 1) - result += string; - - if (count >>= 1) - string += string; - } - return result; -}; - -var trimBeginRegexp = /^\s\s*/; -var trimEndRegexp = /\s\s*$/; - -exports.stringTrimLeft = function (string) { - return string.replace(trimBeginRegexp, ''); -}; - -exports.stringTrimRight = function (string) { - return string.replace(trimEndRegexp, ''); -}; - -exports.copyObject = function(obj) { - var copy = {}; - for (var key in obj) { - copy[key] = obj[key]; - } - return copy; -}; - -exports.copyArray = function(array){ - var copy = []; - for (var i=0, l=array.length; i Date.now() - 50) - return true; - return $cancelT = false; - }, - cancel: function() { - $cancelT = Date.now(); - } -}; - -}); - -define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang","ace/clipboard","ace/lib/keys"], function(require, exports, module) { -"use strict"; - -var event = require("../lib/event"); -var useragent = require("../lib/useragent"); -var dom = require("../lib/dom"); -var lang = require("../lib/lang"); -var clipboard = require("../clipboard"); -var BROKEN_SETDATA = useragent.isChrome < 18; -var USE_IE_MIME_TYPE = useragent.isIE; -var HAS_FOCUS_ARGS = useragent.isChrome > 63; -var MAX_LINE_LENGTH = 400; - -var KEYS = require("../lib/keys"); -var MODS = KEYS.KEY_MODS; -var isIOS = useragent.isIOS; -var valueResetRegex = isIOS ? /\s/ : /\n/; -var isMobile = useragent.isMobile; - -var TextInput = function(parentNode, host) { - var text = dom.createElement("textarea"); - text.className = "ace_text-input"; - - text.setAttribute("wrap", "off"); - text.setAttribute("autocorrect", "off"); - text.setAttribute("autocapitalize", "off"); - text.setAttribute("spellcheck", false); - - text.style.opacity = "0"; - parentNode.insertBefore(text, parentNode.firstChild); - - var copied = false; - var pasted = false; - var inComposition = false; - var sendingText = false; - var tempStyle = ''; - - if (!isMobile) - text.style.fontSize = "1px"; - - var commandMode = false; - var ignoreFocusEvents = false; - - var lastValue = ""; - var lastSelectionStart = 0; - var lastSelectionEnd = 0; - var lastRestoreEnd = 0; - try { var isFocused = document.activeElement === text; } catch(e) {} - - event.addListener(text, "blur", function(e) { - if (ignoreFocusEvents) return; - host.onBlur(e); - isFocused = false; - }, host); - event.addListener(text, "focus", function(e) { - if (ignoreFocusEvents) return; - isFocused = true; - if (useragent.isEdge) { - try { - if (!document.hasFocus()) - return; - } catch(e) {} - } - host.onFocus(e); - if (useragent.isEdge) - setTimeout(resetSelection); - else - resetSelection(); - }, host); - this.$focusScroll = false; - this.focus = function() { - if (tempStyle || HAS_FOCUS_ARGS || this.$focusScroll == "browser") - return text.focus({ preventScroll: true }); - - var top = text.style.top; - text.style.position = "fixed"; - text.style.top = "0px"; - try { - var isTransformed = text.getBoundingClientRect().top != 0; - } catch(e) { - return; - } - var ancestors = []; - if (isTransformed) { - var t = text.parentElement; - while (t && t.nodeType == 1) { - ancestors.push(t); - t.setAttribute("ace_nocontext", true); - if (!t.parentElement && t.getRootNode) - t = t.getRootNode().host; - else - t = t.parentElement; - } - } - text.focus({ preventScroll: true }); - if (isTransformed) { - ancestors.forEach(function(p) { - p.removeAttribute("ace_nocontext"); - }); - } - setTimeout(function() { - text.style.position = ""; - if (text.style.top == "0px") - text.style.top = top; - }, 0); - }; - this.blur = function() { - text.blur(); - }; - this.isFocused = function() { - return isFocused; - }; - - host.on("beforeEndOperation", function() { - var curOp = host.curOp; - var commandName = curOp && curOp.command && curOp.command.name; - if (commandName == "insertstring") - return; - var isUserAction = commandName && (curOp.docChanged || curOp.selectionChanged); - if (inComposition && isUserAction) { - lastValue = text.value = ""; - onCompositionEnd(); - } - resetSelection(); - }); - - var resetSelection = isIOS - ? function(value) { - if (!isFocused || (copied && !value) || sendingText) return; - if (!value) - value = ""; - var newValue = "\n ab" + value + "cde fg\n"; - if (newValue != text.value) - text.value = lastValue = newValue; - - var selectionStart = 4; - var selectionEnd = 4 + (value.length || (host.selection.isEmpty() ? 0 : 1)); - - if (lastSelectionStart != selectionStart || lastSelectionEnd != selectionEnd) { - text.setSelectionRange(selectionStart, selectionEnd); - } - lastSelectionStart = selectionStart; - lastSelectionEnd = selectionEnd; - } - : function() { - if (inComposition || sendingText) - return; - if (!isFocused && !afterContextMenu) - return; - inComposition = true; - - var selectionStart = 0; - var selectionEnd = 0; - var line = ""; - - if (host.session) { - var selection = host.selection; - var range = selection.getRange(); - var row = selection.cursor.row; - selectionStart = range.start.column; - selectionEnd = range.end.column; - line = host.session.getLine(row); - - if (range.start.row != row) { - var prevLine = host.session.getLine(row - 1); - selectionStart = range.start.row < row - 1 ? 0 : selectionStart; - selectionEnd += prevLine.length + 1; - line = prevLine + "\n" + line; - } - else if (range.end.row != row) { - var nextLine = host.session.getLine(row + 1); - selectionEnd = range.end.row > row + 1 ? nextLine.length : selectionEnd; - selectionEnd += line.length + 1; - line = line + "\n" + nextLine; - } - else if (isMobile && row > 0) { - line = "\n" + line; - selectionEnd += 1; - selectionStart += 1; - } - - if (line.length > MAX_LINE_LENGTH) { - if (selectionStart < MAX_LINE_LENGTH && selectionEnd < MAX_LINE_LENGTH) { - line = line.slice(0, MAX_LINE_LENGTH); - } else { - line = "\n"; - if (selectionStart == selectionEnd) { - selectionStart = selectionEnd = 0; - } - else { - selectionStart = 0; - selectionEnd = 1; - } - } - } - } - - var newValue = line + "\n\n"; - if (newValue != lastValue) { - text.value = lastValue = newValue; - lastSelectionStart = lastSelectionEnd = newValue.length; - } - if (afterContextMenu) { - lastSelectionStart = text.selectionStart; - lastSelectionEnd = text.selectionEnd; - } - if ( - lastSelectionEnd != selectionEnd - || lastSelectionStart != selectionStart - || text.selectionEnd != lastSelectionEnd // on ie edge selectionEnd changes silently after the initialization - ) { - try { - text.setSelectionRange(selectionStart, selectionEnd); - lastSelectionStart = selectionStart; - lastSelectionEnd = selectionEnd; - } catch(e){} - } - inComposition = false; - }; - this.resetSelection = resetSelection; - - if (isFocused) - host.onFocus(); - - - var isAllSelected = function(text) { - return text.selectionStart === 0 && text.selectionEnd >= lastValue.length - && text.value === lastValue && lastValue - && text.selectionEnd !== lastSelectionEnd; - }; - - var onSelect = function(e) { - if (inComposition) - return; - if (copied) { - copied = false; - } else if (isAllSelected(text)) { - host.selectAll(); - resetSelection(); - } else if (isMobile && text.selectionStart != lastSelectionStart) { - resetSelection(); - } - }; - - var inputHandler = null; - this.setInputHandler = function(cb) {inputHandler = cb;}; - this.getInputHandler = function() {return inputHandler;}; - var afterContextMenu = false; - - var sendText = function(value, fromInput) { - if (afterContextMenu) - afterContextMenu = false; - if (pasted) { - resetSelection(); - if (value) - host.onPaste(value); - pasted = false; - return ""; - } else { - var selectionStart = text.selectionStart; - var selectionEnd = text.selectionEnd; - - var extendLeft = lastSelectionStart; - var extendRight = lastValue.length - lastSelectionEnd; - - var inserted = value; - var restoreStart = value.length - selectionStart; - var restoreEnd = value.length - selectionEnd; - - var i = 0; - while (extendLeft > 0 && lastValue[i] == value[i]) { - i++; - extendLeft--; - } - inserted = inserted.slice(i); - i = 1; - while (extendRight > 0 && lastValue.length - i > lastSelectionStart - 1 && lastValue[lastValue.length - i] == value[value.length - i]) { - i++; - extendRight--; - } - restoreStart -= i-1; - restoreEnd -= i-1; - var endIndex = inserted.length - i + 1; - if (endIndex < 0) { - extendLeft = -endIndex; - endIndex = 0; - } - inserted = inserted.slice(0, endIndex); - if (!fromInput && !inserted && !restoreStart && !extendLeft && !extendRight && !restoreEnd) - return ""; - sendingText = true; - var shouldReset = false; - if (useragent.isAndroid && inserted == ". ") { - inserted = " "; - shouldReset = true; - } - - if (inserted && !extendLeft && !extendRight && !restoreStart && !restoreEnd || commandMode) { - host.onTextInput(inserted); - } else { - host.onTextInput(inserted, { - extendLeft: extendLeft, - extendRight: extendRight, - restoreStart: restoreStart, - restoreEnd: restoreEnd - }); - } - sendingText = false; - - lastValue = value; - lastSelectionStart = selectionStart; - lastSelectionEnd = selectionEnd; - lastRestoreEnd = restoreEnd; - return shouldReset ? "\n" : inserted; - } - }; - var onInput = function(e) { - if (inComposition) - return onCompositionUpdate(); - if (e && e.inputType) { - if (e.inputType == "historyUndo") return host.execCommand("undo"); - if (e.inputType == "historyRedo") return host.execCommand("redo"); - } - var data = text.value; - var inserted = sendText(data, true); - if ( - data.length > MAX_LINE_LENGTH + 100 - || valueResetRegex.test(inserted) - || isMobile && lastSelectionStart < 1 && lastSelectionStart == lastSelectionEnd - ) { - resetSelection(); - } - }; - - var handleClipboardData = function(e, data, forceIEMime) { - var clipboardData = e.clipboardData || window.clipboardData; - if (!clipboardData || BROKEN_SETDATA) - return; - var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain"; - try { - if (data) { - return clipboardData.setData(mime, data) !== false; - } else { - return clipboardData.getData(mime); - } - } catch(e) { - if (!forceIEMime) - return handleClipboardData(e, data, true); - } - }; - - var doCopy = function(e, isCut) { - var data = host.getCopyText(); - if (!data) - return event.preventDefault(e); - - if (handleClipboardData(e, data)) { - if (isIOS) { - resetSelection(data); - copied = data; - setTimeout(function () { - copied = false; - }, 10); - } - isCut ? host.onCut() : host.onCopy(); - event.preventDefault(e); - } else { - copied = true; - text.value = data; - text.select(); - setTimeout(function(){ - copied = false; - resetSelection(); - isCut ? host.onCut() : host.onCopy(); - }); - } - }; - - var onCut = function(e) { - doCopy(e, true); - }; - - var onCopy = function(e) { - doCopy(e, false); - }; - - var onPaste = function(e) { - var data = handleClipboardData(e); - if (clipboard.pasteCancelled()) - return; - if (typeof data == "string") { - if (data) - host.onPaste(data, e); - if (useragent.isIE) - setTimeout(resetSelection); - event.preventDefault(e); - } - else { - text.value = ""; - pasted = true; - } - }; - - event.addCommandKeyListener(text, host.onCommandKey.bind(host), host); - - event.addListener(text, "select", onSelect, host); - event.addListener(text, "input", onInput, host); - - event.addListener(text, "cut", onCut, host); - event.addListener(text, "copy", onCopy, host); - event.addListener(text, "paste", onPaste, host); - if (!('oncut' in text) || !('oncopy' in text) || !('onpaste' in text)) { - event.addListener(parentNode, "keydown", function(e) { - if ((useragent.isMac && !e.metaKey) || !e.ctrlKey) - return; - - switch (e.keyCode) { - case 67: - onCopy(e); - break; - case 86: - onPaste(e); - break; - case 88: - onCut(e); - break; - } - }, host); - } - var onCompositionStart = function(e) { - if (inComposition || !host.onCompositionStart || host.$readOnly) - return; - - inComposition = {}; - - if (commandMode) - return; - - if (e.data) - inComposition.useTextareaForIME = false; - - setTimeout(onCompositionUpdate, 0); - host._signal("compositionStart"); - host.on("mousedown", cancelComposition); - - var range = host.getSelectionRange(); - range.end.row = range.start.row; - range.end.column = range.start.column; - inComposition.markerRange = range; - inComposition.selectionStart = lastSelectionStart; - host.onCompositionStart(inComposition); - - if (inComposition.useTextareaForIME) { - lastValue = text.value = ""; - lastSelectionStart = 0; - lastSelectionEnd = 0; - } - else { - if (text.msGetInputContext) - inComposition.context = text.msGetInputContext(); - if (text.getInputContext) - inComposition.context = text.getInputContext(); - } - }; - - var onCompositionUpdate = function() { - if (!inComposition || !host.onCompositionUpdate || host.$readOnly) - return; - if (commandMode) - return cancelComposition(); - - if (inComposition.useTextareaForIME) { - host.onCompositionUpdate(text.value); - } - else { - var data = text.value; - sendText(data); - if (inComposition.markerRange) { - if (inComposition.context) { - inComposition.markerRange.start.column = inComposition.selectionStart - = inComposition.context.compositionStartOffset; - } - inComposition.markerRange.end.column = inComposition.markerRange.start.column - + lastSelectionEnd - inComposition.selectionStart + lastRestoreEnd; - } - } - }; - - var onCompositionEnd = function(e) { - if (!host.onCompositionEnd || host.$readOnly) return; - inComposition = false; - host.onCompositionEnd(); - host.off("mousedown", cancelComposition); - if (e) onInput(); - }; - - - function cancelComposition() { - ignoreFocusEvents = true; - text.blur(); - text.focus(); - ignoreFocusEvents = false; - } - - var syncComposition = lang.delayedCall(onCompositionUpdate, 50).schedule.bind(null, null); - - function onKeyup(e) { - if (e.keyCode == 27 && text.value.length < text.selectionStart) { - if (!inComposition) - lastValue = text.value; - lastSelectionStart = lastSelectionEnd = -1; - resetSelection(); - } - syncComposition(); - } - - event.addListener(text, "compositionstart", onCompositionStart, host); - event.addListener(text, "compositionupdate", onCompositionUpdate, host); - event.addListener(text, "keyup", onKeyup, host); - event.addListener(text, "keydown", syncComposition, host); - event.addListener(text, "compositionend", onCompositionEnd, host); - - this.getElement = function() { - return text; - }; - this.setCommandMode = function(value) { - commandMode = value; - text.readOnly = false; - }; - - this.setReadOnly = function(readOnly) { - if (!commandMode) - text.readOnly = readOnly; - }; - - this.setCopyWithEmptySelection = function(value) { - }; - - this.onContextMenu = function(e) { - afterContextMenu = true; - resetSelection(); - host._emit("nativecontextmenu", {target: host, domEvent: e}); - this.moveToMouse(e, true); - }; - - this.moveToMouse = function(e, bringToFront) { - if (!tempStyle) - tempStyle = text.style.cssText; - text.style.cssText = (bringToFront ? "z-index:100000;" : "") - + (useragent.isIE ? "opacity:0.1;" : "") - + "text-indent: -" + (lastSelectionStart + lastSelectionEnd) * host.renderer.characterWidth * 0.5 + "px;"; - - var rect = host.container.getBoundingClientRect(); - var style = dom.computedStyle(host.container); - var top = rect.top + (parseInt(style.borderTopWidth) || 0); - var left = rect.left + (parseInt(rect.borderLeftWidth) || 0); - var maxTop = rect.bottom - top - text.clientHeight -2; - var move = function(e) { - dom.translate(text, e.clientX - left - 2, Math.min(e.clientY - top - 2, maxTop)); - }; - move(e); - - if (e.type != "mousedown") - return; - - host.renderer.$isMousePressed = true; - - clearTimeout(closeTimeout); - if (useragent.isWin) - event.capture(host.container, move, onContextMenuClose); - }; - - this.onContextMenuClose = onContextMenuClose; - var closeTimeout; - function onContextMenuClose() { - clearTimeout(closeTimeout); - closeTimeout = setTimeout(function () { - if (tempStyle) { - text.style.cssText = tempStyle; - tempStyle = ''; - } - host.renderer.$isMousePressed = false; - if (host.renderer.$keepTextAreaAtCursor) - host.renderer.$moveTextAreaToCursor(); - }, 0); - } - - var onContextMenu = function(e) { - host.textInput.onContextMenu(e); - onContextMenuClose(); - }; - event.addListener(text, "mouseup", onContextMenu, host); - event.addListener(text, "mousedown", function(e) { - e.preventDefault(); - onContextMenuClose(); - }, host); - event.addListener(host.renderer.scroller, "contextmenu", onContextMenu, host); - event.addListener(text, "contextmenu", onContextMenu, host); - - if (isIOS) - addIosSelectionHandler(parentNode, host, text); - - function addIosSelectionHandler(parentNode, host, text) { - var typingResetTimeout = null; - var typing = false; - - text.addEventListener("keydown", function (e) { - if (typingResetTimeout) clearTimeout(typingResetTimeout); - typing = true; - }, true); - - text.addEventListener("keyup", function (e) { - typingResetTimeout = setTimeout(function () { - typing = false; - }, 100); - }, true); - var detectArrowKeys = function(e) { - if (document.activeElement !== text) return; - if (typing || inComposition || host.$mouseHandler.isMousePressed) return; - - if (copied) { - return; - } - var selectionStart = text.selectionStart; - var selectionEnd = text.selectionEnd; - - var key = null; - var modifier = 0; - if (selectionStart == 0) { - key = KEYS.up; - } else if (selectionStart == 1) { - key = KEYS.home; - } else if (selectionEnd > lastSelectionEnd && lastValue[selectionEnd] == "\n") { - key = KEYS.end; - } else if (selectionStart < lastSelectionStart && lastValue[selectionStart - 1] == " ") { - key = KEYS.left; - modifier = MODS.option; - } else if ( - selectionStart < lastSelectionStart - || ( - selectionStart == lastSelectionStart - && lastSelectionEnd != lastSelectionStart - && selectionStart == selectionEnd - ) - ) { - key = KEYS.left; - } else if (selectionEnd > lastSelectionEnd && lastValue.slice(0, selectionEnd).split("\n").length > 2) { - key = KEYS.down; - } else if (selectionEnd > lastSelectionEnd && lastValue[selectionEnd - 1] == " ") { - key = KEYS.right; - modifier = MODS.option; - } else if ( - selectionEnd > lastSelectionEnd - || ( - selectionEnd == lastSelectionEnd - && lastSelectionEnd != lastSelectionStart - && selectionStart == selectionEnd - ) - ) { - key = KEYS.right; - } - - if (selectionStart !== selectionEnd) - modifier |= MODS.shift; - - if (key) { - var result = host.onCommandKey({}, modifier, key); - if (!result && host.commands) { - key = KEYS.keyCodeToString(key); - var command = host.commands.findKeyCommand(modifier, key); - if (command) - host.execCommand(command); - } - lastSelectionStart = selectionStart; - lastSelectionEnd = selectionEnd; - resetSelection(""); - } - }; - document.addEventListener("selectionchange", detectArrowKeys); - host.on("destroy", function() { - document.removeEventListener("selectionchange", detectArrowKeys); - }); - } -}; - -exports.TextInput = TextInput; -exports.$setUserAgentForTests = function(_isMobile, _isIOS) { - isMobile = _isMobile; - isIOS = _isIOS; -}; -}); - -define("ace/mouse/default_handlers",["require","exports","module","ace/lib/useragent"], function(require, exports, module) { -"use strict"; - -var useragent = require("../lib/useragent"); - -var DRAG_OFFSET = 0; // pixels -var SCROLL_COOLDOWN_T = 550; // milliseconds - -function DefaultHandlers(mouseHandler) { - mouseHandler.$clickSelection = null; - - var editor = mouseHandler.editor; - editor.setDefaultHandler("mousedown", this.onMouseDown.bind(mouseHandler)); - editor.setDefaultHandler("dblclick", this.onDoubleClick.bind(mouseHandler)); - editor.setDefaultHandler("tripleclick", this.onTripleClick.bind(mouseHandler)); - editor.setDefaultHandler("quadclick", this.onQuadClick.bind(mouseHandler)); - editor.setDefaultHandler("mousewheel", this.onMouseWheel.bind(mouseHandler)); - - var exports = ["select", "startSelect", "selectEnd", "selectAllEnd", "selectByWordsEnd", - "selectByLinesEnd", "dragWait", "dragWaitEnd", "focusWait"]; - - exports.forEach(function(x) { - mouseHandler[x] = this[x]; - }, this); - - mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange"); - mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange"); -} - -(function() { - - this.onMouseDown = function(ev) { - var inSelection = ev.inSelection(); - var pos = ev.getDocumentPosition(); - this.mousedownEvent = ev; - var editor = this.editor; - - var button = ev.getButton(); - if (button !== 0) { - var selectionRange = editor.getSelectionRange(); - var selectionEmpty = selectionRange.isEmpty(); - if (selectionEmpty || button == 1) - editor.selection.moveToPosition(pos); - if (button == 2) { - editor.textInput.onContextMenu(ev.domEvent); - if (!useragent.isMozilla) - ev.preventDefault(); - } - return; - } - - this.mousedownEvent.time = Date.now(); - if (inSelection && !editor.isFocused()) { - editor.focus(); - if (this.$focusTimeout && !this.$clickSelection && !editor.inMultiSelectMode) { - this.setState("focusWait"); - this.captureMouse(ev); - return; - } - } - - this.captureMouse(ev); - this.startSelect(pos, ev.domEvent._clicks > 1); - return ev.preventDefault(); - }; - - this.startSelect = function(pos, waitForClickSelection) { - pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y); - var editor = this.editor; - if (!this.mousedownEvent) return; - if (this.mousedownEvent.getShiftKey()) - editor.selection.selectToPosition(pos); - else if (!waitForClickSelection) - editor.selection.moveToPosition(pos); - if (!waitForClickSelection) - this.select(); - if (editor.renderer.scroller.setCapture) { - editor.renderer.scroller.setCapture(); - } - editor.setStyle("ace_selecting"); - this.setState("select"); - }; - - this.select = function() { - var anchor, editor = this.editor; - var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); - if (this.$clickSelection) { - var cmp = this.$clickSelection.comparePoint(cursor); - - if (cmp == -1) { - anchor = this.$clickSelection.end; - } else if (cmp == 1) { - anchor = this.$clickSelection.start; - } else { - var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); - cursor = orientedRange.cursor; - anchor = orientedRange.anchor; - } - editor.selection.setSelectionAnchor(anchor.row, anchor.column); - } - editor.selection.selectToPosition(cursor); - editor.renderer.scrollCursorIntoView(); - }; - - this.extendSelectionBy = function(unitName) { - var anchor, editor = this.editor; - var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); - var range = editor.selection[unitName](cursor.row, cursor.column); - if (this.$clickSelection) { - var cmpStart = this.$clickSelection.comparePoint(range.start); - var cmpEnd = this.$clickSelection.comparePoint(range.end); - - if (cmpStart == -1 && cmpEnd <= 0) { - anchor = this.$clickSelection.end; - if (range.end.row != cursor.row || range.end.column != cursor.column) - cursor = range.start; - } else if (cmpEnd == 1 && cmpStart >= 0) { - anchor = this.$clickSelection.start; - if (range.start.row != cursor.row || range.start.column != cursor.column) - cursor = range.end; - } else if (cmpStart == -1 && cmpEnd == 1) { - cursor = range.end; - anchor = range.start; - } else { - var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); - cursor = orientedRange.cursor; - anchor = orientedRange.anchor; - } - editor.selection.setSelectionAnchor(anchor.row, anchor.column); - } - editor.selection.selectToPosition(cursor); - editor.renderer.scrollCursorIntoView(); - }; - - this.selectEnd = - this.selectAllEnd = - this.selectByWordsEnd = - this.selectByLinesEnd = function() { - this.$clickSelection = null; - this.editor.unsetStyle("ace_selecting"); - if (this.editor.renderer.scroller.releaseCapture) { - this.editor.renderer.scroller.releaseCapture(); - } - }; - - this.focusWait = function() { - var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); - var time = Date.now(); - - if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimeout) - this.startSelect(this.mousedownEvent.getDocumentPosition()); - }; - - this.onDoubleClick = function(ev) { - var pos = ev.getDocumentPosition(); - var editor = this.editor; - var session = editor.session; - - var range = session.getBracketRange(pos); - if (range) { - if (range.isEmpty()) { - range.start.column--; - range.end.column++; - } - this.setState("select"); - } else { - range = editor.selection.getWordRange(pos.row, pos.column); - this.setState("selectByWords"); - } - this.$clickSelection = range; - this.select(); - }; - - this.onTripleClick = function(ev) { - var pos = ev.getDocumentPosition(); - var editor = this.editor; - - this.setState("selectByLines"); - var range = editor.getSelectionRange(); - if (range.isMultiLine() && range.contains(pos.row, pos.column)) { - this.$clickSelection = editor.selection.getLineRange(range.start.row); - this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end; - } else { - this.$clickSelection = editor.selection.getLineRange(pos.row); - } - this.select(); - }; - - this.onQuadClick = function(ev) { - var editor = this.editor; - - editor.selectAll(); - this.$clickSelection = editor.getSelectionRange(); - this.setState("selectAll"); - }; - - this.onMouseWheel = function(ev) { - if (ev.getAccelKey()) - return; - if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) { - ev.wheelX = ev.wheelY; - ev.wheelY = 0; - } - - var editor = this.editor; - - if (!this.$lastScroll) - this.$lastScroll = { t: 0, vx: 0, vy: 0, allowed: 0 }; - - var prevScroll = this.$lastScroll; - var t = ev.domEvent.timeStamp; - var dt = t - prevScroll.t; - var vx = dt ? ev.wheelX / dt : prevScroll.vx; - var vy = dt ? ev.wheelY / dt : prevScroll.vy; - if (dt < SCROLL_COOLDOWN_T) { - vx = (vx + prevScroll.vx) / 2; - vy = (vy + prevScroll.vy) / 2; - } - - var direction = Math.abs(vx / vy); - - var canScroll = false; - if (direction >= 1 && editor.renderer.isScrollableBy(ev.wheelX * ev.speed, 0)) - canScroll = true; - if (direction <= 1 && editor.renderer.isScrollableBy(0, ev.wheelY * ev.speed)) - canScroll = true; - - if (canScroll) { - prevScroll.allowed = t; - } else if (t - prevScroll.allowed < SCROLL_COOLDOWN_T) { - var isSlower = Math.abs(vx) <= 1.5 * Math.abs(prevScroll.vx) - && Math.abs(vy) <= 1.5 * Math.abs(prevScroll.vy); - if (isSlower) { - canScroll = true; - prevScroll.allowed = t; - } - else { - prevScroll.allowed = 0; - } - } - - prevScroll.t = t; - prevScroll.vx = vx; - prevScroll.vy = vy; - - if (canScroll) { - editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); - return ev.stop(); - } - }; - -}).call(DefaultHandlers.prototype); - -exports.DefaultHandlers = DefaultHandlers; - -function calcDistance(ax, ay, bx, by) { - return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); -} - -function calcRangeOrientation(range, cursor) { - if (range.start.row == range.end.row) - var cmp = 2 * cursor.column - range.start.column - range.end.column; - else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column) - var cmp = cursor.column - 4; - else - var cmp = 2 * cursor.row - range.start.row - range.end.row; - - if (cmp < 0) - return {cursor: range.start, anchor: range.end}; - else - return {cursor: range.end, anchor: range.start}; -} - -}); - -define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var dom = require("./lib/dom"); -function Tooltip (parentNode) { - this.isOpen = false; - this.$element = null; - this.$parentNode = parentNode; -} - -(function() { - this.$init = function() { - this.$element = dom.createElement("div"); - this.$element.className = "ace_tooltip"; - this.$element.style.display = "none"; - this.$parentNode.appendChild(this.$element); - return this.$element; - }; - this.getElement = function() { - return this.$element || this.$init(); - }; - this.setText = function(text) { - this.getElement().textContent = text; - }; - this.setHtml = function(html) { - this.getElement().innerHTML = html; - }; - this.setPosition = function(x, y) { - this.getElement().style.left = x + "px"; - this.getElement().style.top = y + "px"; - }; - this.setClassName = function(className) { - dom.addCssClass(this.getElement(), className); - }; - this.show = function(text, x, y) { - if (text != null) - this.setText(text); - if (x != null && y != null) - this.setPosition(x, y); - if (!this.isOpen) { - this.getElement().style.display = "block"; - this.isOpen = true; - } - }; - - this.hide = function() { - if (this.isOpen) { - this.getElement().style.display = "none"; - this.isOpen = false; - } - }; - this.getHeight = function() { - return this.getElement().offsetHeight; - }; - this.getWidth = function() { - return this.getElement().offsetWidth; - }; - - this.destroy = function() { - this.isOpen = false; - if (this.$element && this.$element.parentNode) { - this.$element.parentNode.removeChild(this.$element); - } - }; - -}).call(Tooltip.prototype); - -exports.Tooltip = Tooltip; -}); - -define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(require, exports, module) { -"use strict"; -var dom = require("../lib/dom"); -var oop = require("../lib/oop"); -var event = require("../lib/event"); -var Tooltip = require("../tooltip").Tooltip; - -function GutterHandler(mouseHandler) { - var editor = mouseHandler.editor; - var gutter = editor.renderer.$gutterLayer; - var tooltip = new GutterTooltip(editor.container); - - mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) { - if (!editor.isFocused() || e.getButton() != 0) - return; - var gutterRegion = gutter.getRegion(e); - - if (gutterRegion == "foldWidgets") - return; - - var row = e.getDocumentPosition().row; - var selection = editor.session.selection; - - if (e.getShiftKey()) - selection.selectTo(row, 0); - else { - if (e.domEvent.detail == 2) { - editor.selectAll(); - return e.preventDefault(); - } - mouseHandler.$clickSelection = editor.selection.getLineRange(row); - } - mouseHandler.setState("selectByLines"); - mouseHandler.captureMouse(e); - return e.preventDefault(); - }); - - - var tooltipTimeout, mouseEvent, tooltipAnnotation; - - function showTooltip() { - var row = mouseEvent.getDocumentPosition().row; - var annotation = gutter.$annotations[row]; - if (!annotation) - return hideTooltip(); - - var maxRow = editor.session.getLength(); - if (row == maxRow) { - var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row; - var pos = mouseEvent.$pos; - if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column)) - return hideTooltip(); - } - - if (tooltipAnnotation == annotation) - return; - tooltipAnnotation = annotation.text.join("
"); - - tooltip.setHtml(tooltipAnnotation); - tooltip.show(); - editor._signal("showGutterTooltip", tooltip); - editor.on("mousewheel", hideTooltip); - - if (mouseHandler.$tooltipFollowsMouse) { - moveTooltip(mouseEvent); - } else { - var gutterElement = mouseEvent.domEvent.target; - var rect = gutterElement.getBoundingClientRect(); - var style = tooltip.getElement().style; - style.left = rect.right + "px"; - style.top = rect.bottom + "px"; - } - } - - function hideTooltip() { - if (tooltipTimeout) - tooltipTimeout = clearTimeout(tooltipTimeout); - if (tooltipAnnotation) { - tooltip.hide(); - tooltipAnnotation = null; - editor._signal("hideGutterTooltip", tooltip); - editor.off("mousewheel", hideTooltip); - } - } - - function moveTooltip(e) { - tooltip.setPosition(e.x, e.y); - } - - mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) { - var target = e.domEvent.target || e.domEvent.srcElement; - if (dom.hasCssClass(target, "ace_fold-widget")) - return hideTooltip(); - - if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse) - moveTooltip(e); - - mouseEvent = e; - if (tooltipTimeout) - return; - tooltipTimeout = setTimeout(function() { - tooltipTimeout = null; - if (mouseEvent && !mouseHandler.isMousePressed) - showTooltip(); - else - hideTooltip(); - }, 50); - }); - - event.addListener(editor.renderer.$gutter, "mouseout", function(e) { - mouseEvent = null; - if (!tooltipAnnotation || tooltipTimeout) - return; - - tooltipTimeout = setTimeout(function() { - tooltipTimeout = null; - hideTooltip(); - }, 50); - }, editor); - - editor.on("changeSession", hideTooltip); -} - -function GutterTooltip(parentNode) { - Tooltip.call(this, parentNode); -} - -oop.inherits(GutterTooltip, Tooltip); - -(function(){ - this.setPosition = function(x, y) { - var windowWidth = window.innerWidth || document.documentElement.clientWidth; - var windowHeight = window.innerHeight || document.documentElement.clientHeight; - var width = this.getWidth(); - var height = this.getHeight(); - x += 15; - y += 15; - if (x + width > windowWidth) { - x -= (x + width) - windowWidth; - } - if (y + height > windowHeight) { - y -= 20 + height; - } - Tooltip.prototype.setPosition.call(this, x, y); - }; - -}).call(GutterTooltip.prototype); - - - -exports.GutterHandler = GutterHandler; - -}); - -define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(require, exports, module) { -"use strict"; - -var event = require("../lib/event"); -var useragent = require("../lib/useragent"); -var MouseEvent = exports.MouseEvent = function(domEvent, editor) { - this.domEvent = domEvent; - this.editor = editor; - - this.x = this.clientX = domEvent.clientX; - this.y = this.clientY = domEvent.clientY; - - this.$pos = null; - this.$inSelection = null; - - this.propagationStopped = false; - this.defaultPrevented = false; -}; - -(function() { - - this.stopPropagation = function() { - event.stopPropagation(this.domEvent); - this.propagationStopped = true; - }; - - this.preventDefault = function() { - event.preventDefault(this.domEvent); - this.defaultPrevented = true; - }; - - this.stop = function() { - this.stopPropagation(); - this.preventDefault(); - }; - this.getDocumentPosition = function() { - if (this.$pos) - return this.$pos; - - this.$pos = this.editor.renderer.screenToTextCoordinates(this.clientX, this.clientY); - return this.$pos; - }; - this.inSelection = function() { - if (this.$inSelection !== null) - return this.$inSelection; - - var editor = this.editor; - - - var selectionRange = editor.getSelectionRange(); - if (selectionRange.isEmpty()) - this.$inSelection = false; - else { - var pos = this.getDocumentPosition(); - this.$inSelection = selectionRange.contains(pos.row, pos.column); - } - - return this.$inSelection; - }; - this.getButton = function() { - return event.getButton(this.domEvent); - }; - this.getShiftKey = function() { - return this.domEvent.shiftKey; - }; - - this.getAccelKey = useragent.isMac - ? function() { return this.domEvent.metaKey; } - : function() { return this.domEvent.ctrlKey; }; - -}).call(MouseEvent.prototype); - -}); - -define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(require, exports, module) { -"use strict"; - -var dom = require("../lib/dom"); -var event = require("../lib/event"); -var useragent = require("../lib/useragent"); - -var AUTOSCROLL_DELAY = 200; -var SCROLL_CURSOR_DELAY = 200; -var SCROLL_CURSOR_HYSTERESIS = 5; - -function DragdropHandler(mouseHandler) { - - var editor = mouseHandler.editor; - - var dragImage = dom.createElement("div"); - dragImage.style.cssText = "top:-100px;position:absolute;z-index:2147483647;opacity:0.5"; - dragImage.textContent = "\xa0"; - - var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"]; - - exports.forEach(function(x) { - mouseHandler[x] = this[x]; - }, this); - editor.on("mousedown", this.onMouseDown.bind(mouseHandler)); - - var mouseTarget = editor.container; - var dragSelectionMarker, x, y; - var timerId, range; - var dragCursor, counter = 0; - var dragOperation; - var isInternal; - var autoScrollStartTime; - var cursorMovedTime; - var cursorPointOnCaretMoved; - - this.onDragStart = function(e) { - if (this.cancelDrag || !mouseTarget.draggable) { - var self = this; - setTimeout(function(){ - self.startSelect(); - self.captureMouse(e); - }, 0); - return e.preventDefault(); - } - range = editor.getSelectionRange(); - - var dataTransfer = e.dataTransfer; - dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove"; - editor.container.appendChild(dragImage); - - dataTransfer.setDragImage && dataTransfer.setDragImage(dragImage, 0, 0); - setTimeout(function() { - editor.container.removeChild(dragImage); - }); - dataTransfer.clearData(); - dataTransfer.setData("Text", editor.session.getTextRange()); - - isInternal = true; - this.setState("drag"); - }; - - this.onDragEnd = function(e) { - mouseTarget.draggable = false; - isInternal = false; - this.setState(null); - if (!editor.getReadOnly()) { - var dropEffect = e.dataTransfer.dropEffect; - if (!dragOperation && dropEffect == "move") - editor.session.remove(editor.getSelectionRange()); - editor.$resetCursorStyle(); - } - this.editor.unsetStyle("ace_dragging"); - this.editor.renderer.setCursorStyle(""); - }; - - this.onDragEnter = function(e) { - if (editor.getReadOnly() || !canAccept(e.dataTransfer)) - return; - x = e.clientX; - y = e.clientY; - if (!dragSelectionMarker) - addDragMarker(); - counter++; - e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); - return event.preventDefault(e); - }; - - this.onDragOver = function(e) { - if (editor.getReadOnly() || !canAccept(e.dataTransfer)) - return; - x = e.clientX; - y = e.clientY; - if (!dragSelectionMarker) { - addDragMarker(); - counter++; - } - if (onMouseMoveTimer !== null) - onMouseMoveTimer = null; - - e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); - return event.preventDefault(e); - }; - - this.onDragLeave = function(e) { - counter--; - if (counter <= 0 && dragSelectionMarker) { - clearDragMarker(); - dragOperation = null; - return event.preventDefault(e); - } - }; - - this.onDrop = function(e) { - if (!dragCursor) - return; - var dataTransfer = e.dataTransfer; - if (isInternal) { - switch (dragOperation) { - case "move": - if (range.contains(dragCursor.row, dragCursor.column)) { - range = { - start: dragCursor, - end: dragCursor - }; - } else { - range = editor.moveText(range, dragCursor); - } - break; - case "copy": - range = editor.moveText(range, dragCursor, true); - break; - } - } else { - var dropData = dataTransfer.getData('Text'); - range = { - start: dragCursor, - end: editor.session.insert(dragCursor, dropData) - }; - editor.focus(); - dragOperation = null; - } - clearDragMarker(); - return event.preventDefault(e); - }; - - event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler), editor); - event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler), editor); - event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler), editor); - event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler), editor); - event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler), editor); - event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler), editor); - - function scrollCursorIntoView(cursor, prevCursor) { - var now = Date.now(); - var vMovement = !prevCursor || cursor.row != prevCursor.row; - var hMovement = !prevCursor || cursor.column != prevCursor.column; - if (!cursorMovedTime || vMovement || hMovement) { - editor.moveCursorToPosition(cursor); - cursorMovedTime = now; - cursorPointOnCaretMoved = {x: x, y: y}; - } else { - var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y); - if (distance > SCROLL_CURSOR_HYSTERESIS) { - cursorMovedTime = null; - } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) { - editor.renderer.scrollCursorIntoView(); - cursorMovedTime = null; - } - } - } - - function autoScroll(cursor, prevCursor) { - var now = Date.now(); - var lineHeight = editor.renderer.layerConfig.lineHeight; - var characterWidth = editor.renderer.layerConfig.characterWidth; - var editorRect = editor.renderer.scroller.getBoundingClientRect(); - var offsets = { - x: { - left: x - editorRect.left, - right: editorRect.right - x - }, - y: { - top: y - editorRect.top, - bottom: editorRect.bottom - y - } - }; - var nearestXOffset = Math.min(offsets.x.left, offsets.x.right); - var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom); - var scrollCursor = {row: cursor.row, column: cursor.column}; - if (nearestXOffset / characterWidth <= 2) { - scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2); - } - if (nearestYOffset / lineHeight <= 1) { - scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1); - } - var vScroll = cursor.row != scrollCursor.row; - var hScroll = cursor.column != scrollCursor.column; - var vMovement = !prevCursor || cursor.row != prevCursor.row; - if (vScroll || (hScroll && !vMovement)) { - if (!autoScrollStartTime) - autoScrollStartTime = now; - else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY) - editor.renderer.scrollCursorIntoView(scrollCursor); - } else { - autoScrollStartTime = null; - } - } - - function onDragInterval() { - var prevCursor = dragCursor; - dragCursor = editor.renderer.screenToTextCoordinates(x, y); - scrollCursorIntoView(dragCursor, prevCursor); - autoScroll(dragCursor, prevCursor); - } - - function addDragMarker() { - range = editor.selection.toOrientedRange(); - dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle()); - editor.clearSelection(); - if (editor.isFocused()) - editor.renderer.$cursorLayer.setBlinking(false); - clearInterval(timerId); - onDragInterval(); - timerId = setInterval(onDragInterval, 20); - counter = 0; - event.addListener(document, "mousemove", onMouseMove); - } - - function clearDragMarker() { - clearInterval(timerId); - editor.session.removeMarker(dragSelectionMarker); - dragSelectionMarker = null; - editor.selection.fromOrientedRange(range); - if (editor.isFocused() && !isInternal) - editor.$resetCursorStyle(); - range = null; - dragCursor = null; - counter = 0; - autoScrollStartTime = null; - cursorMovedTime = null; - event.removeListener(document, "mousemove", onMouseMove); - } - var onMouseMoveTimer = null; - function onMouseMove() { - if (onMouseMoveTimer == null) { - onMouseMoveTimer = setTimeout(function() { - if (onMouseMoveTimer != null && dragSelectionMarker) - clearDragMarker(); - }, 20); - } - } - - function canAccept(dataTransfer) { - var types = dataTransfer.types; - return !types || Array.prototype.some.call(types, function(type) { - return type == 'text/plain' || type == 'Text'; - }); - } - - function getDropEffect(e) { - var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized']; - var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized']; - - var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey; - var effectAllowed = "uninitialized"; - try { - effectAllowed = e.dataTransfer.effectAllowed.toLowerCase(); - } catch (e) {} - var dropEffect = "none"; - - if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0) - dropEffect = "copy"; - else if (moveAllowed.indexOf(effectAllowed) >= 0) - dropEffect = "move"; - else if (copyAllowed.indexOf(effectAllowed) >= 0) - dropEffect = "copy"; - - return dropEffect; - } -} - -(function() { - - this.dragWait = function() { - var interval = Date.now() - this.mousedownEvent.time; - if (interval > this.editor.getDragDelay()) - this.startDrag(); - }; - - this.dragWaitEnd = function() { - var target = this.editor.container; - target.draggable = false; - this.startSelect(this.mousedownEvent.getDocumentPosition()); - this.selectEnd(); - }; - - this.dragReadyEnd = function(e) { - this.editor.$resetCursorStyle(); - this.editor.unsetStyle("ace_dragging"); - this.editor.renderer.setCursorStyle(""); - this.dragWaitEnd(); - }; - - this.startDrag = function(){ - this.cancelDrag = false; - var editor = this.editor; - var target = editor.container; - target.draggable = true; - editor.renderer.$cursorLayer.setBlinking(false); - editor.setStyle("ace_dragging"); - var cursorStyle = useragent.isWin ? "default" : "move"; - editor.renderer.setCursorStyle(cursorStyle); - this.setState("dragReady"); - }; - - this.onMouseDrag = function(e) { - var target = this.editor.container; - if (useragent.isIE && this.state == "dragReady") { - var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); - if (distance > 3) - target.dragDrop(); - } - if (this.state === "dragWait") { - var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); - if (distance > 0) { - target.draggable = false; - this.startSelect(this.mousedownEvent.getDocumentPosition()); - } - } - }; - - this.onMouseDown = function(e) { - if (!this.$dragEnabled) - return; - this.mousedownEvent = e; - var editor = this.editor; - - var inSelection = e.inSelection(); - var button = e.getButton(); - var clickCount = e.domEvent.detail || 1; - if (clickCount === 1 && button === 0 && inSelection) { - if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey())) - return; - this.mousedownEvent.time = Date.now(); - var eventTarget = e.domEvent.target || e.domEvent.srcElement; - if ("unselectable" in eventTarget) - eventTarget.unselectable = "on"; - if (editor.getDragDelay()) { - if (useragent.isWebKit) { - this.cancelDrag = true; - var mouseTarget = editor.container; - mouseTarget.draggable = true; - } - this.setState("dragWait"); - } else { - this.startDrag(); - } - this.captureMouse(e, this.onMouseDrag.bind(this)); - e.defaultPrevented = true; - } - }; - -}).call(DragdropHandler.prototype); - - -function calcDistance(ax, ay, bx, by) { - return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); -} - -exports.DragdropHandler = DragdropHandler; - -}); - -define("ace/mouse/touch_handler",["require","exports","module","ace/mouse/mouse_event","ace/lib/event","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -var MouseEvent = require("./mouse_event").MouseEvent; -var event = require("../lib/event"); -var dom = require("../lib/dom"); - -exports.addTouchListeners = function(el, editor) { - var mode = "scroll"; - var startX; - var startY; - var touchStartT; - var lastT; - var longTouchTimer; - var animationTimer; - var animationSteps = 0; - var pos; - var clickCount = 0; - var vX = 0; - var vY = 0; - var pressed; - var contextMenu; - - function createContextMenu() { - var clipboard = window.navigator && window.navigator.clipboard; - var isOpen = false; - var updateMenu = function() { - var selected = editor.getCopyText(); - var hasUndo = editor.session.getUndoManager().hasUndo(); - contextMenu.replaceChild( - dom.buildDom(isOpen ? ["span", - !selected && ["span", { class: "ace_mobile-button", action: "selectall" }, "Select All"], - selected && ["span", { class: "ace_mobile-button", action: "copy" }, "Copy"], - selected && ["span", { class: "ace_mobile-button", action: "cut" }, "Cut"], - clipboard && ["span", { class: "ace_mobile-button", action: "paste" }, "Paste"], - hasUndo && ["span", { class: "ace_mobile-button", action: "undo" }, "Undo"], - ["span", { class: "ace_mobile-button", action: "find" }, "Find"], - ["span", { class: "ace_mobile-button", action: "openCommandPallete" }, "Pallete"] - ] : ["span"]), - contextMenu.firstChild - ); - }; - var handleClick = function(e) { - var action = e.target.getAttribute("action"); - - if (action == "more" || !isOpen) { - isOpen = !isOpen; - return updateMenu(); - } - if (action == "paste") { - clipboard.readText().then(function (text) { - editor.execCommand(action, text); - }); - } - else if (action) { - if (action == "cut" || action == "copy") { - if (clipboard) - clipboard.writeText(editor.getCopyText()); - else - document.execCommand("copy"); - } - editor.execCommand(action); - } - contextMenu.firstChild.style.display = "none"; - isOpen = false; - if (action != "openCommandPallete") - editor.focus(); - }; - contextMenu = dom.buildDom(["div", - { - class: "ace_mobile-menu", - ontouchstart: function(e) { - mode = "menu"; - e.stopPropagation(); - e.preventDefault(); - editor.textInput.focus(); - }, - ontouchend: function(e) { - e.stopPropagation(); - e.preventDefault(); - handleClick(e); - }, - onclick: handleClick - }, - ["span"], - ["span", { class: "ace_mobile-button", action: "more" }, "..."] - ], editor.container); - } - function showContextMenu() { - if (!contextMenu) createContextMenu(); - var cursor = editor.selection.cursor; - var pagePos = editor.renderer.textToScreenCoordinates(cursor.row, cursor.column); - var leftOffset = editor.renderer.textToScreenCoordinates(0, 0).pageX; - var scrollLeft = editor.renderer.scrollLeft; - var rect = editor.container.getBoundingClientRect(); - contextMenu.style.top = pagePos.pageY - rect.top - 3 + "px"; - if (pagePos.pageX - rect.left < rect.width - 70) { - contextMenu.style.left = ""; - contextMenu.style.right = "10px"; - } else { - contextMenu.style.right = ""; - contextMenu.style.left = leftOffset + scrollLeft - rect.left + "px"; - } - contextMenu.style.display = ""; - contextMenu.firstChild.style.display = "none"; - editor.on("input", hideContextMenu); - } - function hideContextMenu(e) { - if (contextMenu) - contextMenu.style.display = "none"; - editor.off("input", hideContextMenu); - } - - function handleLongTap() { - longTouchTimer = null; - clearTimeout(longTouchTimer); - var range = editor.selection.getRange(); - var inSelection = range.contains(pos.row, pos.column); - if (range.isEmpty() || !inSelection) { - editor.selection.moveToPosition(pos); - editor.selection.selectWord(); - } - mode = "wait"; - showContextMenu(); - } - function switchToSelectionMode() { - longTouchTimer = null; - clearTimeout(longTouchTimer); - editor.selection.moveToPosition(pos); - var range = clickCount >= 2 - ? editor.selection.getLineRange(pos.row) - : editor.session.getBracketRange(pos); - if (range && !range.isEmpty()) { - editor.selection.setRange(range); - } else { - editor.selection.selectWord(); - } - mode = "wait"; - } - event.addListener(el, "contextmenu", function(e) { - if (!pressed) return; - var textarea = editor.textInput.getElement(); - textarea.focus(); - }, editor); - event.addListener(el, "touchstart", function (e) { - var touches = e.touches; - if (longTouchTimer || touches.length > 1) { - clearTimeout(longTouchTimer); - longTouchTimer = null; - touchStartT = -1; - mode = "zoom"; - return; - } - - pressed = editor.$mouseHandler.isMousePressed = true; - var h = editor.renderer.layerConfig.lineHeight; - var w = editor.renderer.layerConfig.lineHeight; - var t = e.timeStamp; - lastT = t; - var touchObj = touches[0]; - var x = touchObj.clientX; - var y = touchObj.clientY; - if (Math.abs(startX - x) + Math.abs(startY - y) > h) - touchStartT = -1; - - startX = e.clientX = x; - startY = e.clientY = y; - vX = vY = 0; - - var ev = new MouseEvent(e, editor); - pos = ev.getDocumentPosition(); - - if (t - touchStartT < 500 && touches.length == 1 && !animationSteps) { - clickCount++; - e.preventDefault(); - e.button = 0; - switchToSelectionMode(); - } else { - clickCount = 0; - var cursor = editor.selection.cursor; - var anchor = editor.selection.isEmpty() ? cursor : editor.selection.anchor; - - var cursorPos = editor.renderer.$cursorLayer.getPixelPosition(cursor, true); - var anchorPos = editor.renderer.$cursorLayer.getPixelPosition(anchor, true); - var rect = editor.renderer.scroller.getBoundingClientRect(); - var offsetTop = editor.renderer.layerConfig.offset; - var offsetLeft = editor.renderer.scrollLeft; - var weightedDistance = function(x, y) { - x = x / w; - y = y / h - 0.75; - return x * x + y * y; - }; - - if (e.clientX < rect.left) { - mode = "zoom"; - return; - } - - var diff1 = weightedDistance( - e.clientX - rect.left - cursorPos.left + offsetLeft, - e.clientY - rect.top - cursorPos.top + offsetTop - ); - var diff2 = weightedDistance( - e.clientX - rect.left - anchorPos.left + offsetLeft, - e.clientY - rect.top - anchorPos.top + offsetTop - ); - if (diff1 < 3.5 && diff2 < 3.5) - mode = diff1 > diff2 ? "cursor" : "anchor"; - - if (diff2 < 3.5) - mode = "anchor"; - else if (diff1 < 3.5) - mode = "cursor"; - else - mode = "scroll"; - longTouchTimer = setTimeout(handleLongTap, 450); - } - touchStartT = t; - }, editor); - - event.addListener(el, "touchend", function (e) { - pressed = editor.$mouseHandler.isMousePressed = false; - if (animationTimer) clearInterval(animationTimer); - if (mode == "zoom") { - mode = ""; - animationSteps = 0; - } else if (longTouchTimer) { - editor.selection.moveToPosition(pos); - animationSteps = 0; - showContextMenu(); - } else if (mode == "scroll") { - animate(); - hideContextMenu(); - } else { - showContextMenu(); - } - clearTimeout(longTouchTimer); - longTouchTimer = null; - }, editor); - event.addListener(el, "touchmove", function (e) { - if (longTouchTimer) { - clearTimeout(longTouchTimer); - longTouchTimer = null; - } - var touches = e.touches; - if (touches.length > 1 || mode == "zoom") return; - - var touchObj = touches[0]; - - var wheelX = startX - touchObj.clientX; - var wheelY = startY - touchObj.clientY; - - if (mode == "wait") { - if (wheelX * wheelX + wheelY * wheelY > 4) - mode = "cursor"; - else - return e.preventDefault(); - } - - startX = touchObj.clientX; - startY = touchObj.clientY; - - e.clientX = touchObj.clientX; - e.clientY = touchObj.clientY; - - var t = e.timeStamp; - var dt = t - lastT; - lastT = t; - if (mode == "scroll") { - var mouseEvent = new MouseEvent(e, editor); - mouseEvent.speed = 1; - mouseEvent.wheelX = wheelX; - mouseEvent.wheelY = wheelY; - if (10 * Math.abs(wheelX) < Math.abs(wheelY)) wheelX = 0; - if (10 * Math.abs(wheelY) < Math.abs(wheelX)) wheelY = 0; - if (dt != 0) { - vX = wheelX / dt; - vY = wheelY / dt; - } - editor._emit("mousewheel", mouseEvent); - if (!mouseEvent.propagationStopped) { - vX = vY = 0; - } - } - else { - var ev = new MouseEvent(e, editor); - var pos = ev.getDocumentPosition(); - if (mode == "cursor") - editor.selection.moveCursorToPosition(pos); - else if (mode == "anchor") - editor.selection.setSelectionAnchor(pos.row, pos.column); - editor.renderer.scrollCursorIntoView(pos); - e.preventDefault(); - } - }, editor); - - function animate() { - animationSteps += 60; - animationTimer = setInterval(function() { - if (animationSteps-- <= 0) { - clearInterval(animationTimer); - animationTimer = null; - } - if (Math.abs(vX) < 0.01) vX = 0; - if (Math.abs(vY) < 0.01) vY = 0; - if (animationSteps < 20) vX = 0.9 * vX; - if (animationSteps < 20) vY = 0.9 * vY; - var oldScrollTop = editor.session.getScrollTop(); - editor.renderer.scrollBy(10 * vX, 10 * vY); - if (oldScrollTop == editor.session.getScrollTop()) - animationSteps = 0; - }, 10); - } -}; - -}); - -define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(require, exports, module) { -"use strict"; -var dom = require("./dom"); - -exports.get = function (url, callback) { - var xhr = new XMLHttpRequest(); - xhr.open('GET', url, true); - xhr.onreadystatechange = function () { - if (xhr.readyState === 4) { - callback(xhr.responseText); - } - }; - xhr.send(null); -}; - -exports.loadScript = function(path, callback) { - var head = dom.getDocumentHead(); - var s = document.createElement('script'); - - s.src = path; - head.appendChild(s); - - s.onload = s.onreadystatechange = function(_, isAbort) { - if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") { - s = s.onload = s.onreadystatechange = null; - if (!isAbort) - callback(); - } - }; -}; -exports.qualifyURL = function(url) { - var a = document.createElement('a'); - a.href = url; - return a.href; -}; - -}); - -define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { -"use strict"; - -var EventEmitter = {}; -var stopPropagation = function() { this.propagationStopped = true; }; -var preventDefault = function() { this.defaultPrevented = true; }; - -EventEmitter._emit = -EventEmitter._dispatchEvent = function(eventName, e) { - this._eventRegistry || (this._eventRegistry = {}); - this._defaultHandlers || (this._defaultHandlers = {}); - - var listeners = this._eventRegistry[eventName] || []; - var defaultHandler = this._defaultHandlers[eventName]; - if (!listeners.length && !defaultHandler) - return; - - if (typeof e != "object" || !e) - e = {}; - - if (!e.type) - e.type = eventName; - if (!e.stopPropagation) - e.stopPropagation = stopPropagation; - if (!e.preventDefault) - e.preventDefault = preventDefault; - - listeners = listeners.slice(); - for (var i=0; i 1) - base = parts[parts.length - 2]; - var path = options[component + "Path"]; - if (path == null) { - path = options.basePath; - } else if (sep == "/") { - component = sep = ""; - } - if (path && path.slice(-1) != "/") - path += "/"; - return path + component + sep + base + this.get("suffix"); -}; - -exports.setModuleUrl = function(name, subst) { - return options.$moduleUrls[name] = subst; -}; - -exports.$loading = {}; -exports.loadModule = function(moduleName, onLoad) { - var module, moduleType; - if (Array.isArray(moduleName)) { - moduleType = moduleName[0]; - moduleName = moduleName[1]; - } - - try { - module = require(moduleName); - } catch (e) {} - if (module && !exports.$loading[moduleName]) - return onLoad && onLoad(module); - - if (!exports.$loading[moduleName]) - exports.$loading[moduleName] = []; - - exports.$loading[moduleName].push(onLoad); - - if (exports.$loading[moduleName].length > 1) - return; - - var afterLoad = function() { - require([moduleName], function(module) { - exports._emit("load.module", {name: moduleName, module: module}); - var listeners = exports.$loading[moduleName]; - exports.$loading[moduleName] = null; - listeners.forEach(function(onLoad) { - onLoad && onLoad(module); - }); - }); - }; - - if (!exports.get("packaged")) - return afterLoad(); - - net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad); - reportErrorIfPathIsNotConfigured(); -}; - -var reportErrorIfPathIsNotConfigured = function() { - if ( - !options.basePath && !options.workerPath - && !options.modePath && !options.themePath - && !Object.keys(options.$moduleUrls).length - ) { - console.error( - "Unable to infer path to ace from script src,", - "use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes", - "or with webpack use ace/webpack-resolver" - ); - reportErrorIfPathIsNotConfigured = function() {}; - } -}; -init(true);function init(packaged) { - - if (!global || !global.document) - return; - - options.packaged = packaged || require.packaged || module.packaged || (global.define && define.packaged); - - var scriptOptions = {}; - var scriptUrl = ""; - var currentScript = (document.currentScript || document._currentScript ); // native or polyfill - var currentDocument = currentScript && currentScript.ownerDocument || document; - - var scripts = currentDocument.getElementsByTagName("script"); - for (var i=0; i 0){ - if (action == 0x10){ - for(i = condPos; i < ix; i++){ - levels[i] = 1; - } - condPos = -1; - } else { - condPos = -1; - } - } - cond = impTab[newState][6]; - if (cond){ - if(condPos == -1){ - condPos = ix; - } - }else{ - if (condPos > -1){ - for(i = condPos; i < ix; i++){ - levels[i] = newLevel; - } - condPos = -1; - } - } - if (charTypes[ix] == B){ - levels[ix] = 0; - } - hiLevel |= newLevel; - } - if (hasUBAT_S){ - for(i = 0; i < len; i++){ - if(charTypes[i] == S){ - levels[i] = dir; - for(var j = i - 1; j >= 0; j--){ - if(charTypes[j] == WS){ - levels[j] = dir; - }else{ - break; - } - } - } - } - } -} - -function _invertLevel(lev, levels, _array) { - if (hiLevel < lev){ - return; - } - if (lev == 1 && dir == RTL && !hasUBAT_B){ - _array.reverse(); - return; - } - var len = _array.length, start = 0, end, lo, hi, tmp; - while(start < len){ - if (levels[start] >= lev){ - end = start + 1; - while(end < len && levels[end] >= lev){ - end++; - } - for(lo = start, hi = end - 1 ; lo < hi; lo++, hi--){ - tmp = _array[lo]; - _array[lo] = _array[hi]; - _array[hi] = tmp; - } - start = end; - } - start++; - } -} - -function _getCharClass(chars, types, classes, ix) { - var cType = types[ix], wType, nType, len, i; - switch(cType){ - case L: - case R: - lastArabic = false; - case ON: - case AN: - return cType; - case EN: - return lastArabic ? AN : EN; - case AL: - lastArabic = true; - hasUBAT_AL = true; - return R; - case WS: - return ON; - case CS: - if (ix < 1 || (ix + 1) >= types.length || - ((wType = classes[ix - 1]) != EN && wType != AN) || - ((nType = types[ix + 1]) != EN && nType != AN)){ - return ON; - } - if (lastArabic){nType = AN;} - return nType == wType ? nType : ON; - case ES: - wType = ix > 0 ? classes[ix - 1] : B; - if (wType == EN && (ix + 1) < types.length && types[ix + 1] == EN){ - return EN; - } - return ON; - case ET: - if (ix > 0 && classes[ix - 1] == EN){ - return EN; - } - if (lastArabic){ - return ON; - } - i = ix + 1; - len = types.length; - while (i < len && types[i] == ET){ - i++; - } - if (i < len && types[i] == EN){ - return EN; - } - return ON; - case NSM: - len = types.length; - i = ix + 1; - while (i < len && types[i] == NSM){ - i++; - } - if (i < len){ - var c = chars[ix], rtlCandidate = (c >= 0x0591 && c <= 0x08FF) || c == 0xFB1E; - - wType = types[i]; - if (rtlCandidate && (wType == R || wType == AL)){ - return R; - } - } - - if (ix < 1 || (wType = types[ix - 1]) == B){ - return ON; - } - return classes[ix - 1]; - case B: - lastArabic = false; - hasUBAT_B = true; - return dir; - case S: - hasUBAT_S = true; - return ON; - case LRE: - case RLE: - case LRO: - case RLO: - case PDF: - lastArabic = false; - case BN: - return ON; - } -} - -function _getCharacterType( ch ) { - var uc = ch.charCodeAt(0), hi = uc >> 8; - - if (hi == 0) { - return ((uc > 0x00BF) ? L : UnicodeTBL00[uc]); - } else if (hi == 5) { - return (/[\u0591-\u05f4]/.test(ch) ? R : L); - } else if (hi == 6) { - if (/[\u0610-\u061a\u064b-\u065f\u06d6-\u06e4\u06e7-\u06ed]/.test(ch)) - return NSM; - else if (/[\u0660-\u0669\u066b-\u066c]/.test(ch)) - return AN; - else if (uc == 0x066A) - return ET; - else if (/[\u06f0-\u06f9]/.test(ch)) - return EN; - else - return AL; - } else if (hi == 0x20 && uc <= 0x205F) { - return UnicodeTBL20[uc & 0xFF]; - } else if (hi == 0xFE) { - return (uc >= 0xFE70 ? AL : ON); - } - return ON; -} - -function _isArabicDiacritics( ch ) { - return (ch >= '\u064b' && ch <= '\u0655'); -} -exports.L = L; -exports.R = R; -exports.EN = EN; -exports.ON_R = 3; -exports.AN = 4; -exports.R_H = 5; -exports.B = 6; -exports.RLE = 7; - -exports.DOT = "\xB7"; -exports.doBidiReorder = function(text, textCharTypes, isRtl) { - if (text.length < 2) - return {}; - - var chars = text.split(""), logicalFromVisual = new Array(chars.length), - bidiLevels = new Array(chars.length), levels = []; - - dir = isRtl ? RTL : LTR; - - _computeLevels(chars, levels, chars.length, textCharTypes); - - for (var i = 0; i < logicalFromVisual.length; logicalFromVisual[i] = i, i++); - - _invertLevel(2, levels, logicalFromVisual); - _invertLevel(1, levels, logicalFromVisual); - - for (var i = 0; i < logicalFromVisual.length - 1; i++) { //fix levels to reflect character width - if (textCharTypes[i] === AN) { - levels[i] = exports.AN; - } else if (levels[i] === R && ((textCharTypes[i] > AL && textCharTypes[i] < LRE) - || textCharTypes[i] === ON || textCharTypes[i] === BN)) { - levels[i] = exports.ON_R; - } else if ((i > 0 && chars[i - 1] === '\u0644') && /\u0622|\u0623|\u0625|\u0627/.test(chars[i])) { - levels[i - 1] = levels[i] = exports.R_H; - i++; - } - } - if (chars[chars.length - 1] === exports.DOT) - levels[chars.length - 1] = exports.B; - - if (chars[0] === '\u202B') - levels[0] = exports.RLE; - - for (var i = 0; i < logicalFromVisual.length; i++) { - bidiLevels[i] = levels[logicalFromVisual[i]]; - } - - return {'logicalFromVisual': logicalFromVisual, 'bidiLevels': bidiLevels}; -}; -exports.hasBidiCharacters = function(text, textCharTypes){ - var ret = false; - for (var i = 0; i < text.length; i++){ - textCharTypes[i] = _getCharacterType(text.charAt(i)); - if (!ret && (textCharTypes[i] == R || textCharTypes[i] == AL || textCharTypes[i] == AN)) - ret = true; - } - return ret; -}; -exports.getVisualFromLogicalIdx = function(logIdx, rowMap) { - for (var i = 0; i < rowMap.logicalFromVisual.length; i++) { - if (rowMap.logicalFromVisual[i] == logIdx) - return i; - } - return 0; -}; - -}); - -define("ace/bidihandler",["require","exports","module","ace/lib/bidiutil","ace/lib/lang"], function(require, exports, module) { -"use strict"; - -var bidiUtil = require("./lib/bidiutil"); -var lang = require("./lib/lang"); -var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\u202B]/; -var BidiHandler = function(session) { - this.session = session; - this.bidiMap = {}; - this.currentRow = null; - this.bidiUtil = bidiUtil; - this.charWidths = []; - this.EOL = "\xAC"; - this.showInvisibles = true; - this.isRtlDir = false; - this.$isRtl = false; - this.line = ""; - this.wrapIndent = 0; - this.EOF = "\xB6"; - this.RLE = "\u202B"; - this.contentWidth = 0; - this.fontMetrics = null; - this.rtlLineOffset = 0; - this.wrapOffset = 0; - this.isMoveLeftOperation = false; - this.seenBidi = bidiRE.test(session.getValue()); -}; - -(function() { - this.isBidiRow = function(screenRow, docRow, splitIndex) { - if (!this.seenBidi) - return false; - if (screenRow !== this.currentRow) { - this.currentRow = screenRow; - this.updateRowLine(docRow, splitIndex); - this.updateBidiMap(); - } - return this.bidiMap.bidiLevels; - }; - - this.onChange = function(delta) { - if (!this.seenBidi) { - if (delta.action == "insert" && bidiRE.test(delta.lines.join("\n"))) { - this.seenBidi = true; - this.currentRow = null; - } - } - else { - this.currentRow = null; - } - }; - - this.getDocumentRow = function() { - var docRow = 0; - var rowCache = this.session.$screenRowCache; - if (rowCache.length) { - var index = this.session.$getRowCacheIndex(rowCache, this.currentRow); - if (index >= 0) - docRow = this.session.$docRowCache[index]; - } - - return docRow; - }; - - this.getSplitIndex = function() { - var splitIndex = 0; - var rowCache = this.session.$screenRowCache; - if (rowCache.length) { - var currentIndex, prevIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow); - while (this.currentRow - splitIndex > 0) { - currentIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow - splitIndex - 1); - if (currentIndex !== prevIndex) - break; - - prevIndex = currentIndex; - splitIndex++; - } - } else { - splitIndex = this.currentRow; - } - - return splitIndex; - }; - - this.updateRowLine = function(docRow, splitIndex) { - if (docRow === undefined) - docRow = this.getDocumentRow(); - - var isLastRow = (docRow === this.session.getLength() - 1), - endOfLine = isLastRow ? this.EOF : this.EOL; - - this.wrapIndent = 0; - this.line = this.session.getLine(docRow); - this.isRtlDir = this.$isRtl || this.line.charAt(0) === this.RLE; - if (this.session.$useWrapMode) { - var splits = this.session.$wrapData[docRow]; - if (splits) { - if (splitIndex === undefined) - splitIndex = this.getSplitIndex(); - - if(splitIndex > 0 && splits.length) { - this.wrapIndent = splits.indent; - this.wrapOffset = this.wrapIndent * this.charWidths[bidiUtil.L]; - this.line = (splitIndex < splits.length) ? - this.line.substring(splits[splitIndex - 1], splits[splitIndex]) : - this.line.substring(splits[splits.length - 1]); - } else { - this.line = this.line.substring(0, splits[splitIndex]); - } - } - if (splitIndex == splits.length) - this.line += (this.showInvisibles) ? endOfLine : bidiUtil.DOT; - } else { - this.line += this.showInvisibles ? endOfLine : bidiUtil.DOT; - } - var session = this.session, shift = 0, size; - this.line = this.line.replace(/\t|[\u1100-\u2029, \u202F-\uFFE6]/g, function(ch, i){ - if (ch === '\t' || session.isFullWidth(ch.charCodeAt(0))) { - size = (ch === '\t') ? session.getScreenTabSize(i + shift) : 2; - shift += size - 1; - return lang.stringRepeat(bidiUtil.DOT, size); - } - return ch; - }); - - if (this.isRtlDir) { - this.fontMetrics.$main.textContent = (this.line.charAt(this.line.length - 1) == bidiUtil.DOT) ? this.line.substr(0, this.line.length - 1) : this.line; - this.rtlLineOffset = this.contentWidth - this.fontMetrics.$main.getBoundingClientRect().width; - } - }; - - this.updateBidiMap = function() { - var textCharTypes = []; - if (bidiUtil.hasBidiCharacters(this.line, textCharTypes) || this.isRtlDir) { - this.bidiMap = bidiUtil.doBidiReorder(this.line, textCharTypes, this.isRtlDir); - } else { - this.bidiMap = {}; - } - }; - this.markAsDirty = function() { - this.currentRow = null; - }; - this.updateCharacterWidths = function(fontMetrics) { - if (this.characterWidth === fontMetrics.$characterSize.width) - return; - - this.fontMetrics = fontMetrics; - var characterWidth = this.characterWidth = fontMetrics.$characterSize.width; - var bidiCharWidth = fontMetrics.$measureCharWidth("\u05d4"); - - this.charWidths[bidiUtil.L] = this.charWidths[bidiUtil.EN] = this.charWidths[bidiUtil.ON_R] = characterWidth; - this.charWidths[bidiUtil.R] = this.charWidths[bidiUtil.AN] = bidiCharWidth; - this.charWidths[bidiUtil.R_H] = bidiCharWidth * 0.45; - this.charWidths[bidiUtil.B] = this.charWidths[bidiUtil.RLE] = 0; - - this.currentRow = null; - }; - - this.setShowInvisibles = function(showInvisibles) { - this.showInvisibles = showInvisibles; - this.currentRow = null; - }; - - this.setEolChar = function(eolChar) { - this.EOL = eolChar; - }; - - this.setContentWidth = function(width) { - this.contentWidth = width; - }; - - this.isRtlLine = function(row) { - if (this.$isRtl) return true; - if (row != undefined) - return (this.session.getLine(row).charAt(0) == this.RLE); - else - return this.isRtlDir; - }; - - this.setRtlDirection = function(editor, isRtlDir) { - var cursor = editor.getCursorPosition(); - for (var row = editor.selection.getSelectionAnchor().row; row <= cursor.row; row++) { - if (!isRtlDir && editor.session.getLine(row).charAt(0) === editor.session.$bidiHandler.RLE) - editor.session.doc.removeInLine(row, 0, 1); - else if (isRtlDir && editor.session.getLine(row).charAt(0) !== editor.session.$bidiHandler.RLE) - editor.session.doc.insert({column: 0, row: row}, editor.session.$bidiHandler.RLE); - } - }; - this.getPosLeft = function(col) { - col -= this.wrapIndent; - var leftBoundary = (this.line.charAt(0) === this.RLE) ? 1 : 0; - var logicalIdx = (col > leftBoundary) ? (this.session.getOverwrite() ? col : col - 1) : leftBoundary; - var visualIdx = bidiUtil.getVisualFromLogicalIdx(logicalIdx, this.bidiMap), - levels = this.bidiMap.bidiLevels, left = 0; - - if (!this.session.getOverwrite() && col <= leftBoundary && levels[visualIdx] % 2 !== 0) - visualIdx++; - - for (var i = 0; i < visualIdx; i++) { - left += this.charWidths[levels[i]]; - } - - if (!this.session.getOverwrite() && (col > leftBoundary) && (levels[visualIdx] % 2 === 0)) - left += this.charWidths[levels[visualIdx]]; - - if (this.wrapIndent) - left += this.isRtlDir ? (-1 * this.wrapOffset) : this.wrapOffset; - - if (this.isRtlDir) - left += this.rtlLineOffset; - - return left; - }; - this.getSelections = function(startCol, endCol) { - var map = this.bidiMap, levels = map.bidiLevels, level, selections = [], offset = 0, - selColMin = Math.min(startCol, endCol) - this.wrapIndent, selColMax = Math.max(startCol, endCol) - this.wrapIndent, - isSelected = false, isSelectedPrev = false, selectionStart = 0; - - if (this.wrapIndent) - offset += this.isRtlDir ? (-1 * this.wrapOffset) : this.wrapOffset; - - for (var logIdx, visIdx = 0; visIdx < levels.length; visIdx++) { - logIdx = map.logicalFromVisual[visIdx]; - level = levels[visIdx]; - isSelected = (logIdx >= selColMin) && (logIdx < selColMax); - if (isSelected && !isSelectedPrev) { - selectionStart = offset; - } else if (!isSelected && isSelectedPrev) { - selections.push({left: selectionStart, width: offset - selectionStart}); - } - offset += this.charWidths[level]; - isSelectedPrev = isSelected; - } - - if (isSelected && (visIdx === levels.length)) { - selections.push({left: selectionStart, width: offset - selectionStart}); - } - - if(this.isRtlDir) { - for (var i = 0; i < selections.length; i++) { - selections[i].left += this.rtlLineOffset; - } - } - return selections; - }; - this.offsetToCol = function(posX) { - if(this.isRtlDir) - posX -= this.rtlLineOffset; - - var logicalIdx = 0, posX = Math.max(posX, 0), - offset = 0, visualIdx = 0, levels = this.bidiMap.bidiLevels, - charWidth = this.charWidths[levels[visualIdx]]; - - if (this.wrapIndent) - posX -= this.isRtlDir ? (-1 * this.wrapOffset) : this.wrapOffset; - - while(posX > offset + charWidth/2) { - offset += charWidth; - if(visualIdx === levels.length - 1) { - charWidth = 0; - break; - } - charWidth = this.charWidths[levels[++visualIdx]]; - } - - if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && (levels[visualIdx] % 2 === 0)){ - if(posX < offset) - visualIdx--; - logicalIdx = this.bidiMap.logicalFromVisual[visualIdx]; - - } else if (visualIdx > 0 && (levels[visualIdx - 1] % 2 === 0) && (levels[visualIdx] % 2 !== 0)){ - logicalIdx = 1 + ((posX > offset) ? this.bidiMap.logicalFromVisual[visualIdx] - : this.bidiMap.logicalFromVisual[visualIdx - 1]); - - } else if ((this.isRtlDir && visualIdx === levels.length - 1 && charWidth === 0 && (levels[visualIdx - 1] % 2 === 0)) - || (!this.isRtlDir && visualIdx === 0 && (levels[visualIdx] % 2 !== 0))){ - logicalIdx = 1 + this.bidiMap.logicalFromVisual[visualIdx]; - } else { - if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && charWidth !== 0) - visualIdx--; - logicalIdx = this.bidiMap.logicalFromVisual[visualIdx]; - } - - if (logicalIdx === 0 && this.isRtlDir) - logicalIdx++; - - return (logicalIdx + this.wrapIndent); - }; - -}).call(BidiHandler.prototype); - -exports.BidiHandler = BidiHandler; -}); - -define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var lang = require("./lib/lang"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var Range = require("./range").Range; -var Selection = function(session) { - this.session = session; - this.doc = session.getDocument(); - - this.clearSelection(); - this.cursor = this.lead = this.doc.createAnchor(0, 0); - this.anchor = this.doc.createAnchor(0, 0); - this.$silent = false; - - var self = this; - this.cursor.on("change", function(e) { - self.$cursorChanged = true; - if (!self.$silent) - self._emit("changeCursor"); - if (!self.$isEmpty && !self.$silent) - self._emit("changeSelection"); - if (!self.$keepDesiredColumnOnChange && e.old.column != e.value.column) - self.$desiredColumn = null; - }); - - this.anchor.on("change", function() { - self.$anchorChanged = true; - if (!self.$isEmpty && !self.$silent) - self._emit("changeSelection"); - }); -}; - -(function() { - - oop.implement(this, EventEmitter); - this.isEmpty = function() { - return this.$isEmpty || ( - this.anchor.row == this.lead.row && - this.anchor.column == this.lead.column - ); - }; - this.isMultiLine = function() { - return !this.$isEmpty && this.anchor.row != this.cursor.row; - }; - this.getCursor = function() { - return this.lead.getPosition(); - }; - this.setSelectionAnchor = function(row, column) { - this.$isEmpty = false; - this.anchor.setPosition(row, column); - }; - this.getAnchor = - this.getSelectionAnchor = function() { - if (this.$isEmpty) - return this.getSelectionLead(); - - return this.anchor.getPosition(); - }; - this.getSelectionLead = function() { - return this.lead.getPosition(); - }; - this.isBackwards = function() { - var anchor = this.anchor; - var lead = this.lead; - return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column)); - }; - this.getRange = function() { - var anchor = this.anchor; - var lead = this.lead; - - if (this.$isEmpty) - return Range.fromPoints(lead, lead); - - return this.isBackwards() - ? Range.fromPoints(lead, anchor) - : Range.fromPoints(anchor, lead); - }; - this.clearSelection = function() { - if (!this.$isEmpty) { - this.$isEmpty = true; - this._emit("changeSelection"); - } - }; - this.selectAll = function() { - this.$setSelection(0, 0, Number.MAX_VALUE, Number.MAX_VALUE); - }; - this.setRange = - this.setSelectionRange = function(range, reverse) { - var start = reverse ? range.end : range.start; - var end = reverse ? range.start : range.end; - this.$setSelection(start.row, start.column, end.row, end.column); - }; - - this.$setSelection = function(anchorRow, anchorColumn, cursorRow, cursorColumn) { - if (this.$silent) - return; - var wasEmpty = this.$isEmpty; - var wasMultiselect = this.inMultiSelectMode; - this.$silent = true; - this.$cursorChanged = this.$anchorChanged = false; - this.anchor.setPosition(anchorRow, anchorColumn); - this.cursor.setPosition(cursorRow, cursorColumn); - this.$isEmpty = !Range.comparePoints(this.anchor, this.cursor); - this.$silent = false; - if (this.$cursorChanged) - this._emit("changeCursor"); - if (this.$cursorChanged || this.$anchorChanged || wasEmpty != this.$isEmpty || wasMultiselect) - this._emit("changeSelection"); - }; - - this.$moveSelection = function(mover) { - var lead = this.lead; - if (this.$isEmpty) - this.setSelectionAnchor(lead.row, lead.column); - - mover.call(this); - }; - this.selectTo = function(row, column) { - this.$moveSelection(function() { - this.moveCursorTo(row, column); - }); - }; - this.selectToPosition = function(pos) { - this.$moveSelection(function() { - this.moveCursorToPosition(pos); - }); - }; - this.moveTo = function(row, column) { - this.clearSelection(); - this.moveCursorTo(row, column); - }; - this.moveToPosition = function(pos) { - this.clearSelection(); - this.moveCursorToPosition(pos); - }; - this.selectUp = function() { - this.$moveSelection(this.moveCursorUp); - }; - this.selectDown = function() { - this.$moveSelection(this.moveCursorDown); - }; - this.selectRight = function() { - this.$moveSelection(this.moveCursorRight); - }; - this.selectLeft = function() { - this.$moveSelection(this.moveCursorLeft); - }; - this.selectLineStart = function() { - this.$moveSelection(this.moveCursorLineStart); - }; - this.selectLineEnd = function() { - this.$moveSelection(this.moveCursorLineEnd); - }; - this.selectFileEnd = function() { - this.$moveSelection(this.moveCursorFileEnd); - }; - this.selectFileStart = function() { - this.$moveSelection(this.moveCursorFileStart); - }; - this.selectWordRight = function() { - this.$moveSelection(this.moveCursorWordRight); - }; - this.selectWordLeft = function() { - this.$moveSelection(this.moveCursorWordLeft); - }; - this.getWordRange = function(row, column) { - if (typeof column == "undefined") { - var cursor = row || this.lead; - row = cursor.row; - column = cursor.column; - } - return this.session.getWordRange(row, column); - }; - this.selectWord = function() { - this.setSelectionRange(this.getWordRange()); - }; - this.selectAWord = function() { - var cursor = this.getCursor(); - var range = this.session.getAWordRange(cursor.row, cursor.column); - this.setSelectionRange(range); - }; - - this.getLineRange = function(row, excludeLastChar) { - var rowStart = typeof row == "number" ? row : this.lead.row; - var rowEnd; - - var foldLine = this.session.getFoldLine(rowStart); - if (foldLine) { - rowStart = foldLine.start.row; - rowEnd = foldLine.end.row; - } else { - rowEnd = rowStart; - } - if (excludeLastChar === true) - return new Range(rowStart, 0, rowEnd, this.session.getLine(rowEnd).length); - else - return new Range(rowStart, 0, rowEnd + 1, 0); - }; - this.selectLine = function() { - this.setSelectionRange(this.getLineRange()); - }; - this.moveCursorUp = function() { - this.moveCursorBy(-1, 0); - }; - this.moveCursorDown = function() { - this.moveCursorBy(1, 0); - }; - this.wouldMoveIntoSoftTab = function(cursor, tabSize, direction) { - var start = cursor.column; - var end = cursor.column + tabSize; - - if (direction < 0) { - start = cursor.column - tabSize; - end = cursor.column; - } - return this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(start, end).split(" ").length-1 == tabSize; - }; - this.moveCursorLeft = function() { - var cursor = this.lead.getPosition(), - fold; - - if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) { - this.moveCursorTo(fold.start.row, fold.start.column); - } else if (cursor.column === 0) { - if (cursor.row > 0) { - this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length); - } - } - else { - var tabSize = this.session.getTabSize(); - if (this.wouldMoveIntoSoftTab(cursor, tabSize, -1) && !this.session.getNavigateWithinSoftTabs()) { - this.moveCursorBy(0, -tabSize); - } else { - this.moveCursorBy(0, -1); - } - } - }; - this.moveCursorRight = function() { - var cursor = this.lead.getPosition(), - fold; - if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) { - this.moveCursorTo(fold.end.row, fold.end.column); - } - else if (this.lead.column == this.doc.getLine(this.lead.row).length) { - if (this.lead.row < this.doc.getLength() - 1) { - this.moveCursorTo(this.lead.row + 1, 0); - } - } - else { - var tabSize = this.session.getTabSize(); - var cursor = this.lead; - if (this.wouldMoveIntoSoftTab(cursor, tabSize, 1) && !this.session.getNavigateWithinSoftTabs()) { - this.moveCursorBy(0, tabSize); - } else { - this.moveCursorBy(0, 1); - } - } - }; - this.moveCursorLineStart = function() { - var row = this.lead.row; - var column = this.lead.column; - var screenRow = this.session.documentToScreenRow(row, column); - var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0); - var beforeCursor = this.session.getDisplayLine( - row, null, firstColumnPosition.row, - firstColumnPosition.column - ); - - var leadingSpace = beforeCursor.match(/^\s*/); - if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart) - firstColumnPosition.column += leadingSpace[0].length; - this.moveCursorToPosition(firstColumnPosition); - }; - this.moveCursorLineEnd = function() { - var lead = this.lead; - var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column); - if (this.lead.column == lineEnd.column) { - var line = this.session.getLine(lineEnd.row); - if (lineEnd.column == line.length) { - var textEnd = line.search(/\s+$/); - if (textEnd > 0) - lineEnd.column = textEnd; - } - } - - this.moveCursorTo(lineEnd.row, lineEnd.column); - }; - this.moveCursorFileEnd = function() { - var row = this.doc.getLength() - 1; - var column = this.doc.getLine(row).length; - this.moveCursorTo(row, column); - }; - this.moveCursorFileStart = function() { - this.moveCursorTo(0, 0); - }; - this.moveCursorLongWordRight = function() { - var row = this.lead.row; - var column = this.lead.column; - var line = this.doc.getLine(row); - var rightOfCursor = line.substring(column); - - this.session.nonTokenRe.lastIndex = 0; - this.session.tokenRe.lastIndex = 0; - var fold = this.session.getFoldAt(row, column, 1); - if (fold) { - this.moveCursorTo(fold.end.row, fold.end.column); - return; - } - if (this.session.nonTokenRe.exec(rightOfCursor)) { - column += this.session.nonTokenRe.lastIndex; - this.session.nonTokenRe.lastIndex = 0; - rightOfCursor = line.substring(column); - } - if (column >= line.length) { - this.moveCursorTo(row, line.length); - this.moveCursorRight(); - if (row < this.doc.getLength() - 1) - this.moveCursorWordRight(); - return; - } - if (this.session.tokenRe.exec(rightOfCursor)) { - column += this.session.tokenRe.lastIndex; - this.session.tokenRe.lastIndex = 0; - } - - this.moveCursorTo(row, column); - }; - this.moveCursorLongWordLeft = function() { - var row = this.lead.row; - var column = this.lead.column; - var fold; - if (fold = this.session.getFoldAt(row, column, -1)) { - this.moveCursorTo(fold.start.row, fold.start.column); - return; - } - - var str = this.session.getFoldStringAt(row, column, -1); - if (str == null) { - str = this.doc.getLine(row).substring(0, column); - } - - var leftOfCursor = lang.stringReverse(str); - this.session.nonTokenRe.lastIndex = 0; - this.session.tokenRe.lastIndex = 0; - if (this.session.nonTokenRe.exec(leftOfCursor)) { - column -= this.session.nonTokenRe.lastIndex; - leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex); - this.session.nonTokenRe.lastIndex = 0; - } - if (column <= 0) { - this.moveCursorTo(row, 0); - this.moveCursorLeft(); - if (row > 0) - this.moveCursorWordLeft(); - return; - } - if (this.session.tokenRe.exec(leftOfCursor)) { - column -= this.session.tokenRe.lastIndex; - this.session.tokenRe.lastIndex = 0; - } - - this.moveCursorTo(row, column); - }; - - this.$shortWordEndIndex = function(rightOfCursor) { - var index = 0, ch; - var whitespaceRe = /\s/; - var tokenRe = this.session.tokenRe; - - tokenRe.lastIndex = 0; - if (this.session.tokenRe.exec(rightOfCursor)) { - index = this.session.tokenRe.lastIndex; - } else { - while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) - index ++; - - if (index < 1) { - tokenRe.lastIndex = 0; - while ((ch = rightOfCursor[index]) && !tokenRe.test(ch)) { - tokenRe.lastIndex = 0; - index ++; - if (whitespaceRe.test(ch)) { - if (index > 2) { - index--; - break; - } else { - while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) - index ++; - if (index > 2) - break; - } - } - } - } - } - tokenRe.lastIndex = 0; - - return index; - }; - - this.moveCursorShortWordRight = function() { - var row = this.lead.row; - var column = this.lead.column; - var line = this.doc.getLine(row); - var rightOfCursor = line.substring(column); - - var fold = this.session.getFoldAt(row, column, 1); - if (fold) - return this.moveCursorTo(fold.end.row, fold.end.column); - - if (column == line.length) { - var l = this.doc.getLength(); - do { - row++; - rightOfCursor = this.doc.getLine(row); - } while (row < l && /^\s*$/.test(rightOfCursor)); - - if (!/^\s+/.test(rightOfCursor)) - rightOfCursor = ""; - column = 0; - } - - var index = this.$shortWordEndIndex(rightOfCursor); - - this.moveCursorTo(row, column + index); - }; - - this.moveCursorShortWordLeft = function() { - var row = this.lead.row; - var column = this.lead.column; - - var fold; - if (fold = this.session.getFoldAt(row, column, -1)) - return this.moveCursorTo(fold.start.row, fold.start.column); - - var line = this.session.getLine(row).substring(0, column); - if (column === 0) { - do { - row--; - line = this.doc.getLine(row); - } while (row > 0 && /^\s*$/.test(line)); - - column = line.length; - if (!/\s+$/.test(line)) - line = ""; - } - - var leftOfCursor = lang.stringReverse(line); - var index = this.$shortWordEndIndex(leftOfCursor); - - return this.moveCursorTo(row, column - index); - }; - - this.moveCursorWordRight = function() { - if (this.session.$selectLongWords) - this.moveCursorLongWordRight(); - else - this.moveCursorShortWordRight(); - }; - - this.moveCursorWordLeft = function() { - if (this.session.$selectLongWords) - this.moveCursorLongWordLeft(); - else - this.moveCursorShortWordLeft(); - }; - this.moveCursorBy = function(rows, chars) { - var screenPos = this.session.documentToScreenPosition( - this.lead.row, - this.lead.column - ); - - var offsetX; - - if (chars === 0) { - if (rows !== 0) { - if (this.session.$bidiHandler.isBidiRow(screenPos.row, this.lead.row)) { - offsetX = this.session.$bidiHandler.getPosLeft(screenPos.column); - screenPos.column = Math.round(offsetX / this.session.$bidiHandler.charWidths[0]); - } else { - offsetX = screenPos.column * this.session.$bidiHandler.charWidths[0]; - } - } - - if (this.$desiredColumn) - screenPos.column = this.$desiredColumn; - else - this.$desiredColumn = screenPos.column; - } - - if (rows != 0 && this.session.lineWidgets && this.session.lineWidgets[this.lead.row]) { - var widget = this.session.lineWidgets[this.lead.row]; - if (rows < 0) - rows -= widget.rowsAbove || 0; - else if (rows > 0) - rows += widget.rowCount - (widget.rowsAbove || 0); - } - - var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column, offsetX); - - if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) { - - } - this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0); - }; - this.moveCursorToPosition = function(position) { - this.moveCursorTo(position.row, position.column); - }; - this.moveCursorTo = function(row, column, keepDesiredColumn) { - var fold = this.session.getFoldAt(row, column, 1); - if (fold) { - row = fold.start.row; - column = fold.start.column; - } - - this.$keepDesiredColumnOnChange = true; - var line = this.session.getLine(row); - if (/[\uDC00-\uDFFF]/.test(line.charAt(column)) && line.charAt(column - 1)) { - if (this.lead.row == row && this.lead.column == column + 1) - column = column - 1; - else - column = column + 1; - } - this.lead.setPosition(row, column); - this.$keepDesiredColumnOnChange = false; - - if (!keepDesiredColumn) - this.$desiredColumn = null; - }; - this.moveCursorToScreen = function(row, column, keepDesiredColumn) { - var pos = this.session.screenToDocumentPosition(row, column); - this.moveCursorTo(pos.row, pos.column, keepDesiredColumn); - }; - this.detach = function() { - this.lead.detach(); - this.anchor.detach(); - }; - - this.fromOrientedRange = function(range) { - this.setSelectionRange(range, range.cursor == range.start); - this.$desiredColumn = range.desiredColumn || this.$desiredColumn; - }; - - this.toOrientedRange = function(range) { - var r = this.getRange(); - if (range) { - range.start.column = r.start.column; - range.start.row = r.start.row; - range.end.column = r.end.column; - range.end.row = r.end.row; - } else { - range = r; - } - - range.cursor = this.isBackwards() ? range.start : range.end; - range.desiredColumn = this.$desiredColumn; - return range; - }; - this.getRangeOfMovements = function(func) { - var start = this.getCursor(); - try { - func(this); - var end = this.getCursor(); - return Range.fromPoints(start, end); - } catch(e) { - return Range.fromPoints(start, start); - } finally { - this.moveCursorToPosition(start); - } - }; - - this.toJSON = function() { - if (this.rangeCount) { - var data = this.ranges.map(function(r) { - var r1 = r.clone(); - r1.isBackwards = r.cursor == r.start; - return r1; - }); - } else { - var data = this.getRange(); - data.isBackwards = this.isBackwards(); - } - return data; - }; - - this.fromJSON = function(data) { - if (data.start == undefined) { - if (this.rangeList && data.length > 1) { - this.toSingleRange(data[0]); - for (var i = data.length; i--; ) { - var r = Range.fromPoints(data[i].start, data[i].end); - if (data[i].isBackwards) - r.cursor = r.start; - this.addRange(r, true); - } - return; - } else { - data = data[0]; - } - } - if (this.rangeList) - this.toSingleRange(data); - this.setSelectionRange(data, data.isBackwards); - }; - - this.isEqual = function(data) { - if ((data.length || this.rangeCount) && data.length != this.rangeCount) - return false; - if (!data.length || !this.ranges) - return this.getRange().isEqual(data); - - for (var i = this.ranges.length; i--; ) { - if (!this.ranges[i].isEqual(data[i])) - return false; - } - return true; - }; - -}).call(Selection.prototype); - -exports.Selection = Selection; -}); - -define("ace/tokenizer",["require","exports","module","ace/config"], function(require, exports, module) { -"use strict"; - -var config = require("./config"); -var MAX_TOKEN_COUNT = 2000; -var Tokenizer = function(rules) { - this.states = rules; - - this.regExps = {}; - this.matchMappings = {}; - for (var key in this.states) { - var state = this.states[key]; - var ruleRegExps = []; - var matchTotal = 0; - var mapping = this.matchMappings[key] = {defaultToken: "text"}; - var flag = "g"; - - var splitterRurles = []; - for (var i = 0; i < state.length; i++) { - var rule = state[i]; - if (rule.defaultToken) - mapping.defaultToken = rule.defaultToken; - if (rule.caseInsensitive) - flag = "gi"; - if (rule.regex == null) - continue; - - if (rule.regex instanceof RegExp) - rule.regex = rule.regex.toString().slice(1, -1); - var adjustedregex = rule.regex; - var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2; - if (Array.isArray(rule.token)) { - if (rule.token.length == 1 || matchcount == 1) { - rule.token = rule.token[0]; - } else if (matchcount - 1 != rule.token.length) { - this.reportError("number of classes and regexp groups doesn't match", { - rule: rule, - groupCount: matchcount - 1 - }); - rule.token = rule.token[0]; - } else { - rule.tokenArray = rule.token; - rule.token = null; - rule.onMatch = this.$arrayTokens; - } - } else if (typeof rule.token == "function" && !rule.onMatch) { - if (matchcount > 1) - rule.onMatch = this.$applyToken; - else - rule.onMatch = rule.token; - } - - if (matchcount > 1) { - if (/\\\d/.test(rule.regex)) { - adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) { - return "\\" + (parseInt(digit, 10) + matchTotal + 1); - }); - } else { - matchcount = 1; - adjustedregex = this.removeCapturingGroups(rule.regex); - } - if (!rule.splitRegex && typeof rule.token != "string") - splitterRurles.push(rule); // flag will be known only at the very end - } - - mapping[matchTotal] = i; - matchTotal += matchcount; - - ruleRegExps.push(adjustedregex); - if (!rule.onMatch) - rule.onMatch = null; - } - - if (!ruleRegExps.length) { - mapping[0] = 0; - ruleRegExps.push("$"); - } - - splitterRurles.forEach(function(rule) { - rule.splitRegex = this.createSplitterRegexp(rule.regex, flag); - }, this); - - this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag); - } -}; - -(function() { - this.$setMaxTokenCount = function(m) { - MAX_TOKEN_COUNT = m | 0; - }; - - this.$applyToken = function(str) { - var values = this.splitRegex.exec(str).slice(1); - var types = this.token.apply(this, values); - if (typeof types === "string") - return [{type: types, value: str}]; - - var tokens = []; - for (var i = 0, l = types.length; i < l; i++) { - if (values[i]) - tokens[tokens.length] = { - type: types[i], - value: values[i] - }; - } - return tokens; - }; - - this.$arrayTokens = function(str) { - if (!str) - return []; - var values = this.splitRegex.exec(str); - if (!values) - return "text"; - var tokens = []; - var types = this.tokenArray; - for (var i = 0, l = types.length; i < l; i++) { - if (values[i + 1]) - tokens[tokens.length] = { - type: types[i], - value: values[i + 1] - }; - } - return tokens; - }; - - this.removeCapturingGroups = function(src) { - var r = src.replace( - /\\.|\[(?:\\.|[^\\\]])*|\(\?[:=!<]|(\()/g, - function(x, y) {return y ? "(?:" : x;} - ); - return r; - }; - - this.createSplitterRegexp = function(src, flag) { - if (src.indexOf("(?=") != -1) { - var stack = 0; - var inChClass = false; - var lastCapture = {}; - src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function( - m, esc, parenOpen, parenClose, square, index - ) { - if (inChClass) { - inChClass = square != "]"; - } else if (square) { - inChClass = true; - } else if (parenClose) { - if (stack == lastCapture.stack) { - lastCapture.end = index+1; - lastCapture.stack = -1; - } - stack--; - } else if (parenOpen) { - stack++; - if (parenOpen.length != 1) { - lastCapture.stack = stack; - lastCapture.start = index; - } - } - return m; - }); - - if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end))) - src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end); - } - if (src.charAt(0) != "^") src = "^" + src; - if (src.charAt(src.length - 1) != "$") src += "$"; - - return new RegExp(src, (flag||"").replace("g", "")); - }; - this.getLineTokens = function(line, startState) { - if (startState && typeof startState != "string") { - var stack = startState.slice(0); - startState = stack[0]; - if (startState === "#tmp") { - stack.shift(); - startState = stack.shift(); - } - } else - var stack = []; - - var currentState = startState || "start"; - var state = this.states[currentState]; - if (!state) { - currentState = "start"; - state = this.states[currentState]; - } - var mapping = this.matchMappings[currentState]; - var re = this.regExps[currentState]; - re.lastIndex = 0; - - var match, tokens = []; - var lastIndex = 0; - var matchAttempts = 0; - - var token = {type: null, value: ""}; - - while (match = re.exec(line)) { - var type = mapping.defaultToken; - var rule = null; - var value = match[0]; - var index = re.lastIndex; - - if (index - value.length > lastIndex) { - var skipped = line.substring(lastIndex, index - value.length); - if (token.type == type) { - token.value += skipped; - } else { - if (token.type) - tokens.push(token); - token = {type: type, value: skipped}; - } - } - - for (var i = 0; i < match.length-2; i++) { - if (match[i + 1] === undefined) - continue; - - rule = state[mapping[i]]; - - if (rule.onMatch) - type = rule.onMatch(value, currentState, stack, line); - else - type = rule.token; - - if (rule.next) { - if (typeof rule.next == "string") { - currentState = rule.next; - } else { - currentState = rule.next(currentState, stack); - } - - state = this.states[currentState]; - if (!state) { - this.reportError("state doesn't exist", currentState); - currentState = "start"; - state = this.states[currentState]; - } - mapping = this.matchMappings[currentState]; - lastIndex = index; - re = this.regExps[currentState]; - re.lastIndex = index; - } - if (rule.consumeLineEnd) - lastIndex = index; - break; - } - - if (value) { - if (typeof type === "string") { - if ((!rule || rule.merge !== false) && token.type === type) { - token.value += value; - } else { - if (token.type) - tokens.push(token); - token = {type: type, value: value}; - } - } else if (type) { - if (token.type) - tokens.push(token); - token = {type: null, value: ""}; - for (var i = 0; i < type.length; i++) - tokens.push(type[i]); - } - } - - if (lastIndex == line.length) - break; - - lastIndex = index; - - if (matchAttempts++ > MAX_TOKEN_COUNT) { - if (matchAttempts > 2 * line.length) { - this.reportError("infinite loop with in ace tokenizer", { - startState: startState, - line: line - }); - } - while (lastIndex < line.length) { - if (token.type) - tokens.push(token); - token = { - value: line.substring(lastIndex, lastIndex += 500), - type: "overflow" - }; - } - currentState = "start"; - stack = []; - break; - } - } - - if (token.type) - tokens.push(token); - - if (stack.length > 1) { - if (stack[0] !== currentState) - stack.unshift("#tmp", currentState); - } - return { - tokens : tokens, - state : stack.length ? stack : currentState - }; - }; - - this.reportError = config.reportError; - -}).call(Tokenizer.prototype); - -exports.Tokenizer = Tokenizer; -}); - -define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(require, exports, module) { -"use strict"; - -var lang = require("../lib/lang"); - -var TextHighlightRules = function() { - - this.$rules = { - "start" : [{ - token : "empty_line", - regex : '^$' - }, { - defaultToken : "text" - }] - }; -}; - -(function() { - - this.addRules = function(rules, prefix) { - if (!prefix) { - for (var key in rules) - this.$rules[key] = rules[key]; - return; - } - for (var key in rules) { - var state = rules[key]; - for (var i = 0; i < state.length; i++) { - var rule = state[i]; - if (rule.next || rule.onMatch) { - if (typeof rule.next == "string") { - if (rule.next.indexOf(prefix) !== 0) - rule.next = prefix + rule.next; - } - if (rule.nextState && rule.nextState.indexOf(prefix) !== 0) - rule.nextState = prefix + rule.nextState; - } - } - this.$rules[prefix + key] = state; - } - }; - - this.getRules = function() { - return this.$rules; - }; - - this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) { - var embedRules = typeof HighlightRules == "function" - ? new HighlightRules().getRules() - : HighlightRules; - if (states) { - for (var i = 0; i < states.length; i++) - states[i] = prefix + states[i]; - } else { - states = []; - for (var key in embedRules) - states.push(prefix + key); - } - - this.addRules(embedRules, prefix); - - if (escapeRules) { - var addRules = Array.prototype[append ? "push" : "unshift"]; - for (var i = 0; i < states.length; i++) - addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules)); - } - - if (!this.$embeds) - this.$embeds = []; - this.$embeds.push(prefix); - }; - - this.getEmbeds = function() { - return this.$embeds; - }; - - var pushState = function(currentState, stack) { - if (currentState != "start" || stack.length) - stack.unshift(this.nextState, currentState); - return this.nextState; - }; - var popState = function(currentState, stack) { - stack.shift(); - return stack.shift() || "start"; - }; - - this.normalizeRules = function() { - var id = 0; - var rules = this.$rules; - function processState(key) { - var state = rules[key]; - state.processed = true; - for (var i = 0; i < state.length; i++) { - var rule = state[i]; - var toInsert = null; - if (Array.isArray(rule)) { - toInsert = rule; - rule = {}; - } - if (!rule.regex && rule.start) { - rule.regex = rule.start; - if (!rule.next) - rule.next = []; - rule.next.push({ - defaultToken: rule.token - }, { - token: rule.token + ".end", - regex: rule.end || rule.start, - next: "pop" - }); - rule.token = rule.token + ".start"; - rule.push = true; - } - var next = rule.next || rule.push; - if (next && Array.isArray(next)) { - var stateName = rule.stateName; - if (!stateName) { - stateName = rule.token; - if (typeof stateName != "string") - stateName = stateName[0] || ""; - if (rules[stateName]) - stateName += id++; - } - rules[stateName] = next; - rule.next = stateName; - processState(stateName); - } else if (next == "pop") { - rule.next = popState; - } - - if (rule.push) { - rule.nextState = rule.next || rule.push; - rule.next = pushState; - delete rule.push; - } - - if (rule.rules) { - for (var r in rule.rules) { - if (rules[r]) { - if (rules[r].push) - rules[r].push.apply(rules[r], rule.rules[r]); - } else { - rules[r] = rule.rules[r]; - } - } - } - var includeName = typeof rule == "string" ? rule : rule.include; - if (includeName) { - if (Array.isArray(includeName)) - toInsert = includeName.map(function(x) { return rules[x]; }); - else - toInsert = rules[includeName]; - } - - if (toInsert) { - var args = [i, 1].concat(toInsert); - if (rule.noEscape) - args = args.filter(function(x) {return !x.next;}); - state.splice.apply(state, args); - i--; - } - - if (rule.keywordMap) { - rule.token = this.createKeywordMapper( - rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive - ); - delete rule.defaultToken; - } - } - } - Object.keys(rules).forEach(processState, this); - }; - - this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) { - var keywords = Object.create(null); - this.$keywordList = []; - Object.keys(map).forEach(function(className) { - var a = map[className]; - var list = a.split(splitChar || "|"); - for (var i = list.length; i--; ) { - var word = list[i]; - this.$keywordList.push(word); - if (ignoreCase) - word = word.toLowerCase(); - keywords[word] = className; - } - }, this); - map = null; - return ignoreCase - ? function(value) {return keywords[value.toLowerCase()] || defaultToken; } - : function(value) {return keywords[value] || defaultToken; }; - }; - - this.getKeywords = function() { - return this.$keywords; - }; - -}).call(TextHighlightRules.prototype); - -exports.TextHighlightRules = TextHighlightRules; -}); - -define("ace/mode/behaviour",["require","exports","module"], function(require, exports, module) { -"use strict"; - -var Behaviour = function() { - this.$behaviours = {}; -}; - -(function () { - - this.add = function (name, action, callback) { - switch (undefined) { - case this.$behaviours: - this.$behaviours = {}; - case this.$behaviours[name]: - this.$behaviours[name] = {}; - } - this.$behaviours[name][action] = callback; - }; - - this.addBehaviours = function (behaviours) { - for (var key in behaviours) { - for (var action in behaviours[key]) { - this.add(key, action, behaviours[key][action]); - } - } - }; - - this.remove = function (name) { - if (this.$behaviours && this.$behaviours[name]) { - delete this.$behaviours[name]; - } - }; - - this.inherit = function (mode, filter) { - if (typeof mode === "function") { - var behaviours = new mode().getBehaviours(filter); - } else { - var behaviours = mode.getBehaviours(filter); - } - this.addBehaviours(behaviours); - }; - - this.getBehaviours = function (filter) { - if (!filter) { - return this.$behaviours; - } else { - var ret = {}; - for (var i = 0; i < filter.length; i++) { - if (this.$behaviours[filter[i]]) { - ret[filter[i]] = this.$behaviours[filter[i]]; - } - } - return ret; - } - }; - -}).call(Behaviour.prototype); - -exports.Behaviour = Behaviour; -}); - -define("ace/token_iterator",["require","exports","module","ace/range"], function(require, exports, module) { -"use strict"; - -var Range = require("./range").Range; -var TokenIterator = function(session, initialRow, initialColumn) { - this.$session = session; - this.$row = initialRow; - this.$rowTokens = session.getTokens(initialRow); - - var token = session.getTokenAt(initialRow, initialColumn); - this.$tokenIndex = token ? token.index : -1; -}; - -(function() { - this.stepBackward = function() { - this.$tokenIndex -= 1; - - while (this.$tokenIndex < 0) { - this.$row -= 1; - if (this.$row < 0) { - this.$row = 0; - return null; - } - - this.$rowTokens = this.$session.getTokens(this.$row); - this.$tokenIndex = this.$rowTokens.length - 1; - } - - return this.$rowTokens[this.$tokenIndex]; - }; - this.stepForward = function() { - this.$tokenIndex += 1; - var rowCount; - while (this.$tokenIndex >= this.$rowTokens.length) { - this.$row += 1; - if (!rowCount) - rowCount = this.$session.getLength(); - if (this.$row >= rowCount) { - this.$row = rowCount - 1; - return null; - } - - this.$rowTokens = this.$session.getTokens(this.$row); - this.$tokenIndex = 0; - } - - return this.$rowTokens[this.$tokenIndex]; - }; - this.getCurrentToken = function () { - return this.$rowTokens[this.$tokenIndex]; - }; - this.getCurrentTokenRow = function () { - return this.$row; - }; - this.getCurrentTokenColumn = function() { - var rowTokens = this.$rowTokens; - var tokenIndex = this.$tokenIndex; - var column = rowTokens[tokenIndex].start; - if (column !== undefined) - return column; - - column = 0; - while (tokenIndex > 0) { - tokenIndex -= 1; - column += rowTokens[tokenIndex].value.length; - } - - return column; - }; - this.getCurrentTokenPosition = function() { - return {row: this.$row, column: this.getCurrentTokenColumn()}; - }; - this.getCurrentTokenRange = function() { - var token = this.$rowTokens[this.$tokenIndex]; - var column = this.getCurrentTokenColumn(); - return new Range(this.$row, column, this.$row, column + token.value.length); - }; - -}).call(TokenIterator.prototype); - -exports.TokenIterator = TokenIterator; -}); - -define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { -"use strict"; - -var oop = require("../../lib/oop"); -var Behaviour = require("../behaviour").Behaviour; -var TokenIterator = require("../../token_iterator").TokenIterator; -var lang = require("../../lib/lang"); - -var SAFE_INSERT_IN_TOKENS = - ["text", "paren.rparen", "rparen", "paren", "punctuation.operator"]; -var SAFE_INSERT_BEFORE_TOKENS = - ["text", "paren.rparen", "rparen", "paren", "punctuation.operator", "comment"]; - -var context; -var contextCache = {}; -var defaultQuotes = {'"' : '"', "'" : "'"}; - -var initContext = function(editor) { - var id = -1; - if (editor.multiSelect) { - id = editor.selection.index; - if (contextCache.rangeCount != editor.multiSelect.rangeCount) - contextCache = {rangeCount: editor.multiSelect.rangeCount}; - } - if (contextCache[id]) - return context = contextCache[id]; - context = contextCache[id] = { - autoInsertedBrackets: 0, - autoInsertedRow: -1, - autoInsertedLineEnd: "", - maybeInsertedBrackets: 0, - maybeInsertedRow: -1, - maybeInsertedLineStart: "", - maybeInsertedLineEnd: "" - }; -}; - -var getWrapped = function(selection, selected, opening, closing) { - var rowDiff = selection.end.row - selection.start.row; - return { - text: opening + selected + closing, - selection: [ - 0, - selection.start.column + 1, - rowDiff, - selection.end.column + (rowDiff ? 0 : 1) - ] - }; -}; - -var CstyleBehaviour = function(options) { - this.add("braces", "insertion", function(state, action, editor, session, text) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - if (text == '{') { - initContext(editor); - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, '{', '}'); - } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { - if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode || options && options.braces) { - CstyleBehaviour.recordAutoInsert(editor, session, "}"); - return { - text: '{}', - selection: [1, 1] - }; - } else { - CstyleBehaviour.recordMaybeInsert(editor, session, "{"); - return { - text: '{', - selection: [1, 1] - }; - } - } - } else if (text == '}') { - initContext(editor); - var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '}') { - var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); - if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { - CstyleBehaviour.popAutoInsertedClosing(); - return { - text: '', - selection: [1, 1] - }; - } - } - } else if (text == "\n" || text == "\r\n") { - initContext(editor); - var closing = ""; - if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { - closing = lang.stringRepeat("}", context.maybeInsertedBrackets); - CstyleBehaviour.clearMaybeInsertedClosing(); - } - var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar === '}') { - var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); - if (!openBracePos) - return null; - var next_indent = this.$getIndent(session.getLine(openBracePos.row)); - } else if (closing) { - var next_indent = this.$getIndent(line); - } else { - CstyleBehaviour.clearMaybeInsertedClosing(); - return; - } - var indent = next_indent + session.getTabString(); - - return { - text: '\n' + indent + '\n' + next_indent + closing, - selection: [1, indent.length, 1, indent.length] - }; - } else { - CstyleBehaviour.clearMaybeInsertedClosing(); - } - }); - - this.add("braces", "deletion", function(state, action, editor, session, range) { - var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '{') { - initContext(editor); - var line = session.doc.getLine(range.start.row); - var rightChar = line.substring(range.end.column, range.end.column + 1); - if (rightChar == '}') { - range.end.column++; - return range; - } else { - context.maybeInsertedBrackets--; - } - } - }); - - this.add("parens", "insertion", function(state, action, editor, session, text) { - if (text == '(') { - initContext(editor); - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, '(', ')'); - } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { - CstyleBehaviour.recordAutoInsert(editor, session, ")"); - return { - text: '()', - selection: [1, 1] - }; - } - } else if (text == ')') { - initContext(editor); - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == ')') { - var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); - if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { - CstyleBehaviour.popAutoInsertedClosing(); - return { - text: '', - selection: [1, 1] - }; - } - } - } - }); - - this.add("parens", "deletion", function(state, action, editor, session, range) { - var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '(') { - initContext(editor); - var line = session.doc.getLine(range.start.row); - var rightChar = line.substring(range.start.column + 1, range.start.column + 2); - if (rightChar == ')') { - range.end.column++; - return range; - } - } - }); - - this.add("brackets", "insertion", function(state, action, editor, session, text) { - if (text == '[') { - initContext(editor); - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, '[', ']'); - } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { - CstyleBehaviour.recordAutoInsert(editor, session, "]"); - return { - text: '[]', - selection: [1, 1] - }; - } - } else if (text == ']') { - initContext(editor); - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == ']') { - var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); - if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { - CstyleBehaviour.popAutoInsertedClosing(); - return { - text: '', - selection: [1, 1] - }; - } - } - } - }); - - this.add("brackets", "deletion", function(state, action, editor, session, range) { - var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '[') { - initContext(editor); - var line = session.doc.getLine(range.start.row); - var rightChar = line.substring(range.start.column + 1, range.start.column + 2); - if (rightChar == ']') { - range.end.column++; - return range; - } - } - }); - - this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { - var quotes = session.$mode.$quotes || defaultQuotes; - if (text.length == 1 && quotes[text]) { - if (this.lineCommentStart && this.lineCommentStart.indexOf(text) != -1) - return; - initContext(editor); - var quote = text; - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && (selected.length != 1 || !quotes[selected]) && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, quote, quote); - } else if (!selected) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - var leftChar = line.substring(cursor.column-1, cursor.column); - var rightChar = line.substring(cursor.column, cursor.column + 1); - - var token = session.getTokenAt(cursor.row, cursor.column); - var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); - if (leftChar == "\\" && token && /escape/.test(token.type)) - return null; - - var stringBefore = token && /string|escape/.test(token.type); - var stringAfter = !rightToken || /string|escape/.test(rightToken.type); - - var pair; - if (rightChar == quote) { - pair = stringBefore !== stringAfter; - if (pair && /string\.end/.test(rightToken.type)) - pair = false; - } else { - if (stringBefore && !stringAfter) - return null; // wrap string with different quote - if (stringBefore && stringAfter) - return null; // do not pair quotes inside strings - var wordRe = session.$mode.tokenRe; - wordRe.lastIndex = 0; - var isWordBefore = wordRe.test(leftChar); - wordRe.lastIndex = 0; - var isWordAfter = wordRe.test(leftChar); - if (isWordBefore || isWordAfter) - return null; // before or after alphanumeric - if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) - return null; // there is rightChar and it isn't closing - var charBefore = line[cursor.column - 2]; - if (leftChar == quote && (charBefore == quote || wordRe.test(charBefore))) - return null; - pair = true; - } - return { - text: pair ? quote + quote : "", - selection: [1,1] - }; - } - } - }); - - this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { - var quotes = session.$mode.$quotes || defaultQuotes; - - var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && quotes.hasOwnProperty(selected)) { - initContext(editor); - var line = session.doc.getLine(range.start.row); - var rightChar = line.substring(range.start.column + 1, range.start.column + 2); - if (rightChar == selected) { - range.end.column++; - return range; - } - } - }); - -}; - - -CstyleBehaviour.isSaneInsertion = function(editor, session) { - var cursor = editor.getCursorPosition(); - var iterator = new TokenIterator(session, cursor.row, cursor.column); - if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { - if (/[)}\]]/.test(editor.session.getLine(cursor.row)[cursor.column])) - return true; - var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); - if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) - return false; - } - iterator.stepForward(); - return iterator.getCurrentTokenRow() !== cursor.row || - this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); -}; - -CstyleBehaviour.$matchTokenType = function(token, types) { - return types.indexOf(token.type || token) > -1; -}; - -CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) - context.autoInsertedBrackets = 0; - context.autoInsertedRow = cursor.row; - context.autoInsertedLineEnd = bracket + line.substr(cursor.column); - context.autoInsertedBrackets++; -}; - -CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - if (!this.isMaybeInsertedClosing(cursor, line)) - context.maybeInsertedBrackets = 0; - context.maybeInsertedRow = cursor.row; - context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; - context.maybeInsertedLineEnd = line.substr(cursor.column); - context.maybeInsertedBrackets++; -}; - -CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { - return context.autoInsertedBrackets > 0 && - cursor.row === context.autoInsertedRow && - bracket === context.autoInsertedLineEnd[0] && - line.substr(cursor.column) === context.autoInsertedLineEnd; -}; - -CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { - return context.maybeInsertedBrackets > 0 && - cursor.row === context.maybeInsertedRow && - line.substr(cursor.column) === context.maybeInsertedLineEnd && - line.substr(0, cursor.column) == context.maybeInsertedLineStart; -}; - -CstyleBehaviour.popAutoInsertedClosing = function() { - context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); - context.autoInsertedBrackets--; -}; - -CstyleBehaviour.clearMaybeInsertedClosing = function() { - if (context) { - context.maybeInsertedBrackets = 0; - context.maybeInsertedRow = -1; - } -}; - - - -oop.inherits(CstyleBehaviour, Behaviour); - -exports.CstyleBehaviour = CstyleBehaviour; -}); - -define("ace/unicode",["require","exports","module"], function(require, exports, module) { -"use strict"; -var wordChars = [48,9,8,25,5,0,2,25,48,0,11,0,5,0,6,22,2,30,2,457,5,11,15,4,8,0,2,0,18,116,2,1,3,3,9,0,2,2,2,0,2,19,2,82,2,138,2,4,3,155,12,37,3,0,8,38,10,44,2,0,2,1,2,1,2,0,9,26,6,2,30,10,7,61,2,9,5,101,2,7,3,9,2,18,3,0,17,58,3,100,15,53,5,0,6,45,211,57,3,18,2,5,3,11,3,9,2,1,7,6,2,2,2,7,3,1,3,21,2,6,2,0,4,3,3,8,3,1,3,3,9,0,5,1,2,4,3,11,16,2,2,5,5,1,3,21,2,6,2,1,2,1,2,1,3,0,2,4,5,1,3,2,4,0,8,3,2,0,8,15,12,2,2,8,2,2,2,21,2,6,2,1,2,4,3,9,2,2,2,2,3,0,16,3,3,9,18,2,2,7,3,1,3,21,2,6,2,1,2,4,3,8,3,1,3,2,9,1,5,1,2,4,3,9,2,0,17,1,2,5,4,2,2,3,4,1,2,0,2,1,4,1,4,2,4,11,5,4,4,2,2,3,3,0,7,0,15,9,18,2,2,7,2,2,2,22,2,9,2,4,4,7,2,2,2,3,8,1,2,1,7,3,3,9,19,1,2,7,2,2,2,22,2,9,2,4,3,8,2,2,2,3,8,1,8,0,2,3,3,9,19,1,2,7,2,2,2,22,2,15,4,7,2,2,2,3,10,0,9,3,3,9,11,5,3,1,2,17,4,23,2,8,2,0,3,6,4,0,5,5,2,0,2,7,19,1,14,57,6,14,2,9,40,1,2,0,3,1,2,0,3,0,7,3,2,6,2,2,2,0,2,0,3,1,2,12,2,2,3,4,2,0,2,5,3,9,3,1,35,0,24,1,7,9,12,0,2,0,2,0,5,9,2,35,5,19,2,5,5,7,2,35,10,0,58,73,7,77,3,37,11,42,2,0,4,328,2,3,3,6,2,0,2,3,3,40,2,3,3,32,2,3,3,6,2,0,2,3,3,14,2,56,2,3,3,66,5,0,33,15,17,84,13,619,3,16,2,25,6,74,22,12,2,6,12,20,12,19,13,12,2,2,2,1,13,51,3,29,4,0,5,1,3,9,34,2,3,9,7,87,9,42,6,69,11,28,4,11,5,11,11,39,3,4,12,43,5,25,7,10,38,27,5,62,2,28,3,10,7,9,14,0,89,75,5,9,18,8,13,42,4,11,71,55,9,9,4,48,83,2,2,30,14,230,23,280,3,5,3,37,3,5,3,7,2,0,2,0,2,0,2,30,3,52,2,6,2,0,4,2,2,6,4,3,3,5,5,12,6,2,2,6,67,1,20,0,29,0,14,0,17,4,60,12,5,0,4,11,18,0,5,0,3,9,2,0,4,4,7,0,2,0,2,0,2,3,2,10,3,3,6,4,5,0,53,1,2684,46,2,46,2,132,7,6,15,37,11,53,10,0,17,22,10,6,2,6,2,6,2,6,2,6,2,6,2,6,2,6,2,31,48,0,470,1,36,5,2,4,6,1,5,85,3,1,3,2,2,89,2,3,6,40,4,93,18,23,57,15,513,6581,75,20939,53,1164,68,45,3,268,4,27,21,31,3,13,13,1,2,24,9,69,11,1,38,8,3,102,3,1,111,44,25,51,13,68,12,9,7,23,4,0,5,45,3,35,13,28,4,64,15,10,39,54,10,13,3,9,7,22,4,1,5,66,25,2,227,42,2,1,3,9,7,11171,13,22,5,48,8453,301,3,61,3,105,39,6,13,4,6,11,2,12,2,4,2,0,2,1,2,1,2,107,34,362,19,63,3,53,41,11,5,15,17,6,13,1,25,2,33,4,2,134,20,9,8,25,5,0,2,25,12,88,4,5,3,5,3,5,3,2]; - -var code = 0; -var str = []; -for (var i = 0; i < wordChars.length; i += 2) { - str.push(code += wordChars[i]); - if (wordChars[i + 1]) - str.push(45, code += wordChars[i + 1]); -} - -exports.wordChars = String.fromCharCode.apply(null, str); - -}); - -define("ace/mode/text",["require","exports","module","ace/config","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour/cstyle","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(require, exports, module) { -"use strict"; -var config = require("../config"); - -var Tokenizer = require("../tokenizer").Tokenizer; -var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; -var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; -var unicode = require("../unicode"); -var lang = require("../lib/lang"); -var TokenIterator = require("../token_iterator").TokenIterator; -var Range = require("../range").Range; - -var Mode = function() { - this.HighlightRules = TextHighlightRules; -}; - -(function() { - this.$defaultBehaviour = new CstyleBehaviour(); - - this.tokenRe = new RegExp("^[" + unicode.wordChars + "\\$_]+", "g"); - - this.nonTokenRe = new RegExp("^(?:[^" + unicode.wordChars + "\\$_]|\\s])+", "g"); - - this.getTokenizer = function() { - if (!this.$tokenizer) { - this.$highlightRules = this.$highlightRules || new this.HighlightRules(this.$highlightRuleConfig); - this.$tokenizer = new Tokenizer(this.$highlightRules.getRules()); - } - return this.$tokenizer; - }; - - this.lineCommentStart = ""; - this.blockComment = ""; - - this.toggleCommentLines = function(state, session, startRow, endRow) { - var doc = session.doc; - - var ignoreBlankLines = true; - var shouldRemove = true; - var minIndent = Infinity; - var tabSize = session.getTabSize(); - var insertAtTabStop = false; - - if (!this.lineCommentStart) { - if (!this.blockComment) - return false; - var lineCommentStart = this.blockComment.start; - var lineCommentEnd = this.blockComment.end; - var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")"); - var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$"); - - var comment = function(line, i) { - if (testRemove(line, i)) - return; - if (!ignoreBlankLines || /\S/.test(line)) { - doc.insertInLine({row: i, column: line.length}, lineCommentEnd); - doc.insertInLine({row: i, column: minIndent}, lineCommentStart); - } - }; - - var uncomment = function(line, i) { - var m; - if (m = line.match(regexpEnd)) - doc.removeInLine(i, line.length - m[0].length, line.length); - if (m = line.match(regexpStart)) - doc.removeInLine(i, m[1].length, m[0].length); - }; - - var testRemove = function(line, row) { - if (regexpStart.test(line)) - return true; - var tokens = session.getTokens(row); - for (var i = 0; i < tokens.length; i++) { - if (tokens[i].type === "comment") - return true; - } - }; - } else { - if (Array.isArray(this.lineCommentStart)) { - var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|"); - var lineCommentStart = this.lineCommentStart[0]; - } else { - var regexpStart = lang.escapeRegExp(this.lineCommentStart); - var lineCommentStart = this.lineCommentStart; - } - regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?"); - - insertAtTabStop = session.getUseSoftTabs(); - - var uncomment = function(line, i) { - var m = line.match(regexpStart); - if (!m) return; - var start = m[1].length, end = m[0].length; - if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ") - end--; - doc.removeInLine(i, start, end); - }; - var commentWithSpace = lineCommentStart + " "; - var comment = function(line, i) { - if (!ignoreBlankLines || /\S/.test(line)) { - if (shouldInsertSpace(line, minIndent, minIndent)) - doc.insertInLine({row: i, column: minIndent}, commentWithSpace); - else - doc.insertInLine({row: i, column: minIndent}, lineCommentStart); - } - }; - var testRemove = function(line, i) { - return regexpStart.test(line); - }; - - var shouldInsertSpace = function(line, before, after) { - var spaces = 0; - while (before-- && line.charAt(before) == " ") - spaces++; - if (spaces % tabSize != 0) - return false; - var spaces = 0; - while (line.charAt(after++) == " ") - spaces++; - if (tabSize > 2) - return spaces % tabSize != tabSize - 1; - else - return spaces % tabSize == 0; - }; - } - - function iter(fun) { - for (var i = startRow; i <= endRow; i++) - fun(doc.getLine(i), i); - } - - - var minEmptyLength = Infinity; - iter(function(line, i) { - var indent = line.search(/\S/); - if (indent !== -1) { - if (indent < minIndent) - minIndent = indent; - if (shouldRemove && !testRemove(line, i)) - shouldRemove = false; - } else if (minEmptyLength > line.length) { - minEmptyLength = line.length; - } - }); - - if (minIndent == Infinity) { - minIndent = minEmptyLength; - ignoreBlankLines = false; - shouldRemove = false; - } - - if (insertAtTabStop && minIndent % tabSize != 0) - minIndent = Math.floor(minIndent / tabSize) * tabSize; - - iter(shouldRemove ? uncomment : comment); - }; - - this.toggleBlockComment = function(state, session, range, cursor) { - var comment = this.blockComment; - if (!comment) - return; - if (!comment.start && comment[0]) - comment = comment[0]; - - var iterator = new TokenIterator(session, cursor.row, cursor.column); - var token = iterator.getCurrentToken(); - - var sel = session.selection; - var initialRange = session.selection.toOrientedRange(); - var startRow, colDiff; - - if (token && /comment/.test(token.type)) { - var startRange, endRange; - while (token && /comment/.test(token.type)) { - var i = token.value.indexOf(comment.start); - if (i != -1) { - var row = iterator.getCurrentTokenRow(); - var column = iterator.getCurrentTokenColumn() + i; - startRange = new Range(row, column, row, column + comment.start.length); - break; - } - token = iterator.stepBackward(); - } - - var iterator = new TokenIterator(session, cursor.row, cursor.column); - var token = iterator.getCurrentToken(); - while (token && /comment/.test(token.type)) { - var i = token.value.indexOf(comment.end); - if (i != -1) { - var row = iterator.getCurrentTokenRow(); - var column = iterator.getCurrentTokenColumn() + i; - endRange = new Range(row, column, row, column + comment.end.length); - break; - } - token = iterator.stepForward(); - } - if (endRange) - session.remove(endRange); - if (startRange) { - session.remove(startRange); - startRow = startRange.start.row; - colDiff = -comment.start.length; - } - } else { - colDiff = comment.start.length; - startRow = range.start.row; - session.insert(range.end, comment.end); - session.insert(range.start, comment.start); - } - if (initialRange.start.row == startRow) - initialRange.start.column += colDiff; - if (initialRange.end.row == startRow) - initialRange.end.column += colDiff; - session.selection.fromOrientedRange(initialRange); - }; - - this.getNextLineIndent = function(state, line, tab) { - return this.$getIndent(line); - }; - - this.checkOutdent = function(state, line, input) { - return false; - }; - - this.autoOutdent = function(state, doc, row) { - }; - - this.$getIndent = function(line) { - return line.match(/^\s*/)[0]; - }; - - this.createWorker = function(session) { - return null; - }; - - this.createModeDelegates = function (mapping) { - this.$embeds = []; - this.$modes = {}; - for (var i in mapping) { - if (mapping[i]) { - var Mode = mapping[i]; - var id = Mode.prototype.$id; - var mode = config.$modes[id]; - if (!mode) - config.$modes[id] = mode = new Mode(); - if (!config.$modes[i]) - config.$modes[i] = mode; - this.$embeds.push(i); - this.$modes[i] = mode; - } - } - - var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent", - "checkOutdent", "autoOutdent", "transformAction", "getCompletions"]; - - for (var i = 0; i < delegations.length; i++) { - (function(scope) { - var functionName = delegations[i]; - var defaultHandler = scope[functionName]; - scope[delegations[i]] = function() { - return this.$delegator(functionName, arguments, defaultHandler); - }; - }(this)); - } - }; - - this.$delegator = function(method, args, defaultHandler) { - var state = args[0] || "start"; - if (typeof state != "string") { - if (Array.isArray(state[2])) { - var language = state[2][state[2].length - 1]; - var mode = this.$modes[language]; - if (mode) - return mode[method].apply(mode, [state[1]].concat([].slice.call(args, 1))); - } - state = state[0] || "start"; - } - - for (var i = 0; i < this.$embeds.length; i++) { - if (!this.$modes[this.$embeds[i]]) continue; - - var split = state.split(this.$embeds[i]); - if (!split[0] && split[1]) { - args[0] = split[1]; - var mode = this.$modes[this.$embeds[i]]; - return mode[method].apply(mode, args); - } - } - var ret = defaultHandler.apply(this, args); - return defaultHandler ? ret : undefined; - }; - - this.transformAction = function(state, action, editor, session, param) { - if (this.$behaviour) { - var behaviours = this.$behaviour.getBehaviours(); - for (var key in behaviours) { - if (behaviours[key][action]) { - var ret = behaviours[key][action].apply(this, arguments); - if (ret) { - return ret; - } - } - } - } - }; - - this.getKeywords = function(append) { - if (!this.completionKeywords) { - var rules = this.$tokenizer.rules; - var completionKeywords = []; - for (var rule in rules) { - var ruleItr = rules[rule]; - for (var r = 0, l = ruleItr.length; r < l; r++) { - if (typeof ruleItr[r].token === "string") { - if (/keyword|support|storage/.test(ruleItr[r].token)) - completionKeywords.push(ruleItr[r].regex); - } - else if (typeof ruleItr[r].token === "object") { - for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) { - if (/keyword|support|storage/.test(ruleItr[r].token[a])) { - var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a]; - completionKeywords.push(rule.substr(1, rule.length - 2)); - } - } - } - } - } - this.completionKeywords = completionKeywords; - } - if (!append) - return this.$keywordList; - return completionKeywords.concat(this.$keywordList || []); - }; - - this.$createKeywordList = function() { - if (!this.$highlightRules) - this.getTokenizer(); - return this.$keywordList = this.$highlightRules.$keywordList || []; - }; - - this.getCompletions = function(state, session, pos, prefix) { - var keywords = this.$keywordList || this.$createKeywordList(); - return keywords.map(function(word) { - return { - name: word, - value: word, - score: 0, - meta: "keyword" - }; - }); - }; - - this.$id = "ace/mode/text"; -}).call(Mode.prototype); - -exports.Mode = Mode; -}); - -define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { -"use strict"; - -function throwDeltaError(delta, errorText){ - console.log("Invalid Delta:", delta); - throw "Invalid Delta: " + errorText; -} - -function positionInDocument(docLines, position) { - return position.row >= 0 && position.row < docLines.length && - position.column >= 0 && position.column <= docLines[position.row].length; -} - -function validateDelta(docLines, delta) { - if (delta.action != "insert" && delta.action != "remove") - throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); - if (!(delta.lines instanceof Array)) - throwDeltaError(delta, "delta.lines must be an Array"); - if (!delta.start || !delta.end) - throwDeltaError(delta, "delta.start/end must be an present"); - var start = delta.start; - if (!positionInDocument(docLines, delta.start)) - throwDeltaError(delta, "delta.start must be contained in document"); - var end = delta.end; - if (delta.action == "remove" && !positionInDocument(docLines, end)) - throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); - var numRangeRows = end.row - start.row; - var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); - if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) - throwDeltaError(delta, "delta.range must match delta lines"); -} - -exports.applyDelta = function(docLines, delta, doNotValidate) { - - var row = delta.start.row; - var startColumn = delta.start.column; - var line = docLines[row] || ""; - switch (delta.action) { - case "insert": - var lines = delta.lines; - if (lines.length === 1) { - docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); - } else { - var args = [row, 1].concat(delta.lines); - docLines.splice.apply(docLines, args); - docLines[row] = line.substring(0, startColumn) + docLines[row]; - docLines[row + delta.lines.length - 1] += line.substring(startColumn); - } - break; - case "remove": - var endColumn = delta.end.column; - var endRow = delta.end.row; - if (row === endRow) { - docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); - } else { - docLines.splice( - row, endRow - row + 1, - line.substring(0, startColumn) + docLines[endRow].substring(endColumn) - ); - } - break; - } -}; -}); - -define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; - -var Anchor = exports.Anchor = function(doc, row, column) { - this.$onChange = this.onChange.bind(this); - this.attach(doc); - - if (typeof column == "undefined") - this.setPosition(row.row, row.column); - else - this.setPosition(row, column); -}; - -(function() { - - oop.implement(this, EventEmitter); - this.getPosition = function() { - return this.$clipPositionToDocument(this.row, this.column); - }; - this.getDocument = function() { - return this.document; - }; - this.$insertRight = false; - this.onChange = function(delta) { - if (delta.start.row == delta.end.row && delta.start.row != this.row) - return; - - if (delta.start.row > this.row) - return; - - var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); - this.setPosition(point.row, point.column, true); - }; - - function $pointsInOrder(point1, point2, equalPointsInOrder) { - var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; - return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); - } - - function $getTransformedPoint(delta, point, moveIfEqual) { - var deltaIsInsert = delta.action == "insert"; - var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); - var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); - var deltaStart = delta.start; - var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. - if ($pointsInOrder(point, deltaStart, moveIfEqual)) { - return { - row: point.row, - column: point.column - }; - } - if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { - return { - row: point.row + deltaRowShift, - column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) - }; - } - - return { - row: deltaStart.row, - column: deltaStart.column - }; - } - this.setPosition = function(row, column, noClip) { - var pos; - if (noClip) { - pos = { - row: row, - column: column - }; - } else { - pos = this.$clipPositionToDocument(row, column); - } - - if (this.row == pos.row && this.column == pos.column) - return; - - var old = { - row: this.row, - column: this.column - }; - - this.row = pos.row; - this.column = pos.column; - this._signal("change", { - old: old, - value: pos - }); - }; - this.detach = function() { - this.document.off("change", this.$onChange); - }; - this.attach = function(doc) { - this.document = doc || this.document; - this.document.on("change", this.$onChange); - }; - this.$clipPositionToDocument = function(row, column) { - var pos = {}; - - if (row >= this.document.getLength()) { - pos.row = Math.max(0, this.document.getLength() - 1); - pos.column = this.document.getLine(pos.row).length; - } - else if (row < 0) { - pos.row = 0; - pos.column = 0; - } - else { - pos.row = row; - pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); - } - - if (column < 0) - pos.column = 0; - - return pos; - }; - -}).call(Anchor.prototype); - -}); - -define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var applyDelta = require("./apply_delta").applyDelta; -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var Range = require("./range").Range; -var Anchor = require("./anchor").Anchor; - -var Document = function(textOrLines) { - this.$lines = [""]; - if (textOrLines.length === 0) { - this.$lines = [""]; - } else if (Array.isArray(textOrLines)) { - this.insertMergedLines({row: 0, column: 0}, textOrLines); - } else { - this.insert({row: 0, column:0}, textOrLines); - } -}; - -(function() { - - oop.implement(this, EventEmitter); - this.setValue = function(text) { - var len = this.getLength() - 1; - this.remove(new Range(0, 0, len, this.getLine(len).length)); - this.insert({row: 0, column: 0}, text); - }; - this.getValue = function() { - return this.getAllLines().join(this.getNewLineCharacter()); - }; - this.createAnchor = function(row, column) { - return new Anchor(this, row, column); - }; - if ("aaa".split(/a/).length === 0) { - this.$split = function(text) { - return text.replace(/\r\n|\r/g, "\n").split("\n"); - }; - } else { - this.$split = function(text) { - return text.split(/\r\n|\r|\n/); - }; - } - - - this.$detectNewLine = function(text) { - var match = text.match(/^.*?(\r\n|\r|\n)/m); - this.$autoNewLine = match ? match[1] : "\n"; - this._signal("changeNewLineMode"); - }; - this.getNewLineCharacter = function() { - switch (this.$newLineMode) { - case "windows": - return "\r\n"; - case "unix": - return "\n"; - default: - return this.$autoNewLine || "\n"; - } - }; - - this.$autoNewLine = ""; - this.$newLineMode = "auto"; - this.setNewLineMode = function(newLineMode) { - if (this.$newLineMode === newLineMode) - return; - - this.$newLineMode = newLineMode; - this._signal("changeNewLineMode"); - }; - this.getNewLineMode = function() { - return this.$newLineMode; - }; - this.isNewLine = function(text) { - return (text == "\r\n" || text == "\r" || text == "\n"); - }; - this.getLine = function(row) { - return this.$lines[row] || ""; - }; - this.getLines = function(firstRow, lastRow) { - return this.$lines.slice(firstRow, lastRow + 1); - }; - this.getAllLines = function() { - return this.getLines(0, this.getLength()); - }; - this.getLength = function() { - return this.$lines.length; - }; - this.getTextRange = function(range) { - return this.getLinesForRange(range).join(this.getNewLineCharacter()); - }; - this.getLinesForRange = function(range) { - var lines; - if (range.start.row === range.end.row) { - lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; - } else { - lines = this.getLines(range.start.row, range.end.row); - lines[0] = (lines[0] || "").substring(range.start.column); - var l = lines.length - 1; - if (range.end.row - range.start.row == l) - lines[l] = lines[l].substring(0, range.end.column); - } - return lines; - }; - this.insertLines = function(row, lines) { - console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); - return this.insertFullLines(row, lines); - }; - this.removeLines = function(firstRow, lastRow) { - console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); - return this.removeFullLines(firstRow, lastRow); - }; - this.insertNewLine = function(position) { - console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); - return this.insertMergedLines(position, ["", ""]); - }; - this.insert = function(position, text) { - if (this.getLength() <= 1) - this.$detectNewLine(text); - - return this.insertMergedLines(position, this.$split(text)); - }; - this.insertInLine = function(position, text) { - var start = this.clippedPos(position.row, position.column); - var end = this.pos(position.row, position.column + text.length); - - this.applyDelta({ - start: start, - end: end, - action: "insert", - lines: [text] - }, true); - - return this.clonePos(end); - }; - - this.clippedPos = function(row, column) { - var length = this.getLength(); - if (row === undefined) { - row = length; - } else if (row < 0) { - row = 0; - } else if (row >= length) { - row = length - 1; - column = undefined; - } - var line = this.getLine(row); - if (column == undefined) - column = line.length; - column = Math.min(Math.max(column, 0), line.length); - return {row: row, column: column}; - }; - - this.clonePos = function(pos) { - return {row: pos.row, column: pos.column}; - }; - - this.pos = function(row, column) { - return {row: row, column: column}; - }; - - this.$clipPosition = function(position) { - var length = this.getLength(); - if (position.row >= length) { - position.row = Math.max(0, length - 1); - position.column = this.getLine(length - 1).length; - } else { - position.row = Math.max(0, position.row); - position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); - } - return position; - }; - this.insertFullLines = function(row, lines) { - row = Math.min(Math.max(row, 0), this.getLength()); - var column = 0; - if (row < this.getLength()) { - lines = lines.concat([""]); - column = 0; - } else { - lines = [""].concat(lines); - row--; - column = this.$lines[row].length; - } - this.insertMergedLines({row: row, column: column}, lines); - }; - this.insertMergedLines = function(position, lines) { - var start = this.clippedPos(position.row, position.column); - var end = { - row: start.row + lines.length - 1, - column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length - }; - - this.applyDelta({ - start: start, - end: end, - action: "insert", - lines: lines - }); - - return this.clonePos(end); - }; - this.remove = function(range) { - var start = this.clippedPos(range.start.row, range.start.column); - var end = this.clippedPos(range.end.row, range.end.column); - this.applyDelta({ - start: start, - end: end, - action: "remove", - lines: this.getLinesForRange({start: start, end: end}) - }); - return this.clonePos(start); - }; - this.removeInLine = function(row, startColumn, endColumn) { - var start = this.clippedPos(row, startColumn); - var end = this.clippedPos(row, endColumn); - - this.applyDelta({ - start: start, - end: end, - action: "remove", - lines: this.getLinesForRange({start: start, end: end}) - }, true); - - return this.clonePos(start); - }; - this.removeFullLines = function(firstRow, lastRow) { - firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); - lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); - var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; - var deleteLastNewLine = lastRow < this.getLength() - 1; - var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); - var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); - var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); - var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); - var range = new Range(startRow, startCol, endRow, endCol); - var deletedLines = this.$lines.slice(firstRow, lastRow + 1); - - this.applyDelta({ - start: range.start, - end: range.end, - action: "remove", - lines: this.getLinesForRange(range) - }); - return deletedLines; - }; - this.removeNewLine = function(row) { - if (row < this.getLength() - 1 && row >= 0) { - this.applyDelta({ - start: this.pos(row, this.getLine(row).length), - end: this.pos(row + 1, 0), - action: "remove", - lines: ["", ""] - }); - } - }; - this.replace = function(range, text) { - if (!(range instanceof Range)) - range = Range.fromPoints(range.start, range.end); - if (text.length === 0 && range.isEmpty()) - return range.start; - if (text == this.getTextRange(range)) - return range.end; - - this.remove(range); - var end; - if (text) { - end = this.insert(range.start, text); - } - else { - end = range.start; - } - - return end; - }; - this.applyDeltas = function(deltas) { - for (var i=0; i=0; i--) { - this.revertDelta(deltas[i]); - } - }; - this.applyDelta = function(delta, doNotValidate) { - var isInsert = delta.action == "insert"; - if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] - : !Range.comparePoints(delta.start, delta.end)) { - return; - } - - if (isInsert && delta.lines.length > 20000) { - this.$splitAndapplyLargeDelta(delta, 20000); - } - else { - applyDelta(this.$lines, delta, doNotValidate); - this._signal("change", delta); - } - }; - - this.$safeApplyDelta = function(delta) { - var docLength = this.$lines.length; - if ( - delta.action == "remove" && delta.start.row < docLength && delta.end.row < docLength - || delta.action == "insert" && delta.start.row <= docLength - ) { - this.applyDelta(delta); - } - }; - - this.$splitAndapplyLargeDelta = function(delta, MAX) { - var lines = delta.lines; - var l = lines.length - MAX + 1; - var row = delta.start.row; - var column = delta.start.column; - for (var from = 0, to = 0; from < l; from = to) { - to += MAX - 1; - var chunk = lines.slice(from, to); - chunk.push(""); - this.applyDelta({ - start: this.pos(row + from, column), - end: this.pos(row + to, column = 0), - action: delta.action, - lines: chunk - }, true); - } - delta.lines = lines.slice(from); - delta.start.row = row + from; - delta.start.column = column; - this.applyDelta(delta, true); - }; - this.revertDelta = function(delta) { - this.$safeApplyDelta({ - start: this.clonePos(delta.start), - end: this.clonePos(delta.end), - action: (delta.action == "insert" ? "remove" : "insert"), - lines: delta.lines.slice() - }); - }; - this.indexToPosition = function(index, startRow) { - var lines = this.$lines || this.getAllLines(); - var newlineLength = this.getNewLineCharacter().length; - for (var i = startRow || 0, l = lines.length; i < l; i++) { - index -= lines[i].length + newlineLength; - if (index < 0) - return {row: i, column: index + lines[i].length + newlineLength}; - } - return {row: l-1, column: index + lines[l-1].length + newlineLength}; - }; - this.positionToIndex = function(pos, startRow) { - var lines = this.$lines || this.getAllLines(); - var newlineLength = this.getNewLineCharacter().length; - var index = 0; - var row = Math.min(pos.row, lines.length); - for (var i = startRow || 0; i < row; ++i) - index += lines[i].length + newlineLength; - - return index + pos.column; - }; - -}).call(Document.prototype); - -exports.Document = Document; -}); - -define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; - -var BackgroundTokenizer = function(tokenizer, editor) { - this.running = false; - this.lines = []; - this.states = []; - this.currentLine = 0; - this.tokenizer = tokenizer; - - var self = this; - - this.$worker = function() { - if (!self.running) { return; } - - var workerStart = new Date(); - var currentLine = self.currentLine; - var endLine = -1; - var doc = self.doc; - - var startLine = currentLine; - while (self.lines[currentLine]) - currentLine++; - - var len = doc.getLength(); - var processedLines = 0; - self.running = false; - while (currentLine < len) { - self.$tokenizeRow(currentLine); - endLine = currentLine; - do { - currentLine++; - } while (self.lines[currentLine]); - processedLines ++; - if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) { - self.running = setTimeout(self.$worker, 20); - break; - } - } - self.currentLine = currentLine; - - if (endLine == -1) - endLine = currentLine; - - if (startLine <= endLine) - self.fireUpdateEvent(startLine, endLine); - }; -}; - -(function(){ - - oop.implement(this, EventEmitter); - this.setTokenizer = function(tokenizer) { - this.tokenizer = tokenizer; - this.lines = []; - this.states = []; - - this.start(0); - }; - this.setDocument = function(doc) { - this.doc = doc; - this.lines = []; - this.states = []; - - this.stop(); - }; - this.fireUpdateEvent = function(firstRow, lastRow) { - var data = { - first: firstRow, - last: lastRow - }; - this._signal("update", {data: data}); - }; - this.start = function(startRow) { - this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength()); - this.lines.splice(this.currentLine, this.lines.length); - this.states.splice(this.currentLine, this.states.length); - - this.stop(); - this.running = setTimeout(this.$worker, 700); - }; - - this.scheduleStart = function() { - if (!this.running) - this.running = setTimeout(this.$worker, 700); - }; - - this.$updateOnChange = function(delta) { - var startRow = delta.start.row; - var len = delta.end.row - startRow; - - if (len === 0) { - this.lines[startRow] = null; - } else if (delta.action == "remove") { - this.lines.splice(startRow, len + 1, null); - this.states.splice(startRow, len + 1, null); - } else { - var args = Array(len + 1); - args.unshift(startRow, 1); - this.lines.splice.apply(this.lines, args); - this.states.splice.apply(this.states, args); - } - - this.currentLine = Math.min(startRow, this.currentLine, this.doc.getLength()); - - this.stop(); - }; - this.stop = function() { - if (this.running) - clearTimeout(this.running); - this.running = false; - }; - this.getTokens = function(row) { - return this.lines[row] || this.$tokenizeRow(row); - }; - this.getState = function(row) { - if (this.currentLine == row) - this.$tokenizeRow(row); - return this.states[row] || "start"; - }; - - this.$tokenizeRow = function(row) { - var line = this.doc.getLine(row); - var state = this.states[row - 1]; - - var data = this.tokenizer.getLineTokens(line, state, row); - - if (this.states[row] + "" !== data.state + "") { - this.states[row] = data.state; - this.lines[row + 1] = null; - if (this.currentLine > row + 1) - this.currentLine = row + 1; - } else if (this.currentLine == row) { - this.currentLine = row + 1; - } - - return this.lines[row] = data.tokens; - }; - -}).call(BackgroundTokenizer.prototype); - -exports.BackgroundTokenizer = BackgroundTokenizer; -}); - -define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(require, exports, module) { -"use strict"; - -var lang = require("./lib/lang"); -var oop = require("./lib/oop"); -var Range = require("./range").Range; - -var SearchHighlight = function(regExp, clazz, type) { - this.setRegexp(regExp); - this.clazz = clazz; - this.type = type || "text"; -}; - -(function() { - this.MAX_RANGES = 500; - - this.setRegexp = function(regExp) { - if (this.regExp+"" == regExp+"") - return; - this.regExp = regExp; - this.cache = []; - }; - - this.update = function(html, markerLayer, session, config) { - if (!this.regExp) - return; - var start = config.firstRow, end = config.lastRow; - - for (var i = start; i <= end; i++) { - var ranges = this.cache[i]; - if (ranges == null) { - ranges = lang.getMatchOffsets(session.getLine(i), this.regExp); - if (ranges.length > this.MAX_RANGES) - ranges = ranges.slice(0, this.MAX_RANGES); - ranges = ranges.map(function(match) { - return new Range(i, match.offset, i, match.offset + match.length); - }); - this.cache[i] = ranges.length ? ranges : ""; - } - - for (var j = ranges.length; j --; ) { - markerLayer.drawSingleLineMarker( - html, ranges[j].toScreenRange(session), this.clazz, config); - } - } - }; - -}).call(SearchHighlight.prototype); - -exports.SearchHighlight = SearchHighlight; -}); - -define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(require, exports, module) { -"use strict"; - -var Range = require("../range").Range; -function FoldLine(foldData, folds) { - this.foldData = foldData; - if (Array.isArray(folds)) { - this.folds = folds; - } else { - folds = this.folds = [ folds ]; - } - - var last = folds[folds.length - 1]; - this.range = new Range(folds[0].start.row, folds[0].start.column, - last.end.row, last.end.column); - this.start = this.range.start; - this.end = this.range.end; - - this.folds.forEach(function(fold) { - fold.setFoldLine(this); - }, this); -} - -(function() { - this.shiftRow = function(shift) { - this.start.row += shift; - this.end.row += shift; - this.folds.forEach(function(fold) { - fold.start.row += shift; - fold.end.row += shift; - }); - }; - - this.addFold = function(fold) { - if (fold.sameRow) { - if (fold.start.row < this.startRow || fold.endRow > this.endRow) { - throw new Error("Can't add a fold to this FoldLine as it has no connection"); - } - this.folds.push(fold); - this.folds.sort(function(a, b) { - return -a.range.compareEnd(b.start.row, b.start.column); - }); - if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) { - this.end.row = fold.end.row; - this.end.column = fold.end.column; - } else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) { - this.start.row = fold.start.row; - this.start.column = fold.start.column; - } - } else if (fold.start.row == this.end.row) { - this.folds.push(fold); - this.end.row = fold.end.row; - this.end.column = fold.end.column; - } else if (fold.end.row == this.start.row) { - this.folds.unshift(fold); - this.start.row = fold.start.row; - this.start.column = fold.start.column; - } else { - throw new Error("Trying to add fold to FoldRow that doesn't have a matching row"); - } - fold.foldLine = this; - }; - - this.containsRow = function(row) { - return row >= this.start.row && row <= this.end.row; - }; - - this.walk = function(callback, endRow, endColumn) { - var lastEnd = 0, - folds = this.folds, - fold, - cmp, stop, isNewRow = true; - - if (endRow == null) { - endRow = this.end.row; - endColumn = this.end.column; - } - - for (var i = 0; i < folds.length; i++) { - fold = folds[i]; - - cmp = fold.range.compareStart(endRow, endColumn); - if (cmp == -1) { - callback(null, endRow, endColumn, lastEnd, isNewRow); - return; - } - - stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow); - stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd); - if (stop || cmp === 0) { - return; - } - isNewRow = !fold.sameRow; - lastEnd = fold.end.column; - } - callback(null, endRow, endColumn, lastEnd, isNewRow); - }; - - this.getNextFoldTo = function(row, column) { - var fold, cmp; - for (var i = 0; i < this.folds.length; i++) { - fold = this.folds[i]; - cmp = fold.range.compareEnd(row, column); - if (cmp == -1) { - return { - fold: fold, - kind: "after" - }; - } else if (cmp === 0) { - return { - fold: fold, - kind: "inside" - }; - } - } - return null; - }; - - this.addRemoveChars = function(row, column, len) { - var ret = this.getNextFoldTo(row, column), - fold, folds; - if (ret) { - fold = ret.fold; - if (ret.kind == "inside" - && fold.start.column != column - && fold.start.row != row) - { - window.console && window.console.log(row, column, fold); - } else if (fold.start.row == row) { - folds = this.folds; - var i = folds.indexOf(fold); - if (i === 0) { - this.start.column += len; - } - for (i; i < folds.length; i++) { - fold = folds[i]; - fold.start.column += len; - if (!fold.sameRow) { - return; - } - fold.end.column += len; - } - this.end.column += len; - } - } - }; - - this.split = function(row, column) { - var pos = this.getNextFoldTo(row, column); - - if (!pos || pos.kind == "inside") - return null; - - var fold = pos.fold; - var folds = this.folds; - var foldData = this.foldData; - - var i = folds.indexOf(fold); - var foldBefore = folds[i - 1]; - this.end.row = foldBefore.end.row; - this.end.column = foldBefore.end.column; - folds = folds.splice(i, folds.length - i); - - var newFoldLine = new FoldLine(foldData, folds); - foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine); - return newFoldLine; - }; - - this.merge = function(foldLineNext) { - var folds = foldLineNext.folds; - for (var i = 0; i < folds.length; i++) { - this.addFold(folds[i]); - } - var foldData = this.foldData; - foldData.splice(foldData.indexOf(foldLineNext), 1); - }; - - this.toString = function() { - var ret = [this.range.toString() + ": [" ]; - - this.folds.forEach(function(fold) { - ret.push(" " + fold.toString()); - }); - ret.push("]"); - return ret.join("\n"); - }; - - this.idxToPosition = function(idx) { - var lastFoldEndColumn = 0; - - for (var i = 0; i < this.folds.length; i++) { - var fold = this.folds[i]; - - idx -= fold.start.column - lastFoldEndColumn; - if (idx < 0) { - return { - row: fold.start.row, - column: fold.start.column + idx - }; - } - - idx -= fold.placeholder.length; - if (idx < 0) { - return fold.start; - } - - lastFoldEndColumn = fold.end.column; - } - - return { - row: this.end.row, - column: this.end.column + idx - }; - }; -}).call(FoldLine.prototype); - -exports.FoldLine = FoldLine; -}); - -define("ace/range_list",["require","exports","module","ace/range"], function(require, exports, module) { -"use strict"; -var Range = require("./range").Range; -var comparePoints = Range.comparePoints; - -var RangeList = function() { - this.ranges = []; - this.$bias = 1; -}; - -(function() { - this.comparePoints = comparePoints; - - this.pointIndex = function(pos, excludeEdges, startIndex) { - var list = this.ranges; - - for (var i = startIndex || 0; i < list.length; i++) { - var range = list[i]; - var cmpEnd = comparePoints(pos, range.end); - if (cmpEnd > 0) - continue; - var cmpStart = comparePoints(pos, range.start); - if (cmpEnd === 0) - return excludeEdges && cmpStart !== 0 ? -i-2 : i; - if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges)) - return i; - - return -i-1; - } - return -i - 1; - }; - - this.add = function(range) { - var excludeEdges = !range.isEmpty(); - var startIndex = this.pointIndex(range.start, excludeEdges); - if (startIndex < 0) - startIndex = -startIndex - 1; - - var endIndex = this.pointIndex(range.end, excludeEdges, startIndex); - - if (endIndex < 0) - endIndex = -endIndex - 1; - else - endIndex++; - return this.ranges.splice(startIndex, endIndex - startIndex, range); - }; - - this.addList = function(list) { - var removed = []; - for (var i = list.length; i--; ) { - removed.push.apply(removed, this.add(list[i])); - } - return removed; - }; - - this.substractPoint = function(pos) { - var i = this.pointIndex(pos); - - if (i >= 0) - return this.ranges.splice(i, 1); - }; - this.merge = function() { - var removed = []; - var list = this.ranges; - - list = list.sort(function(a, b) { - return comparePoints(a.start, b.start); - }); - - var next = list[0], range; - for (var i = 1; i < list.length; i++) { - range = next; - next = list[i]; - var cmp = comparePoints(range.end, next.start); - if (cmp < 0) - continue; - - if (cmp == 0 && !range.isEmpty() && !next.isEmpty()) - continue; - - if (comparePoints(range.end, next.end) < 0) { - range.end.row = next.end.row; - range.end.column = next.end.column; - } - - list.splice(i, 1); - removed.push(next); - next = range; - i--; - } - - this.ranges = list; - - return removed; - }; - - this.contains = function(row, column) { - return this.pointIndex({row: row, column: column}) >= 0; - }; - - this.containsPoint = function(pos) { - return this.pointIndex(pos) >= 0; - }; - - this.rangeAtPoint = function(pos) { - var i = this.pointIndex(pos); - if (i >= 0) - return this.ranges[i]; - }; - - - this.clipRows = function(startRow, endRow) { - var list = this.ranges; - if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow) - return []; - - var startIndex = this.pointIndex({row: startRow, column: 0}); - if (startIndex < 0) - startIndex = -startIndex - 1; - var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex); - if (endIndex < 0) - endIndex = -endIndex - 1; - - var clipped = []; - for (var i = startIndex; i < endIndex; i++) { - clipped.push(list[i]); - } - return clipped; - }; - - this.removeAll = function() { - return this.ranges.splice(0, this.ranges.length); - }; - - this.attach = function(session) { - if (this.session) - this.detach(); - - this.session = session; - this.onChange = this.$onChange.bind(this); - - this.session.on('change', this.onChange); - }; - - this.detach = function() { - if (!this.session) - return; - this.session.removeListener('change', this.onChange); - this.session = null; - }; - - this.$onChange = function(delta) { - var start = delta.start; - var end = delta.end; - var startRow = start.row; - var endRow = end.row; - var ranges = this.ranges; - for (var i = 0, n = ranges.length; i < n; i++) { - var r = ranges[i]; - if (r.end.row >= startRow) - break; - } - - if (delta.action == "insert") { - var lineDif = endRow - startRow; - var colDiff = -start.column + end.column; - for (; i < n; i++) { - var r = ranges[i]; - if (r.start.row > startRow) - break; - - if (r.start.row == startRow && r.start.column >= start.column) { - if (r.start.column == start.column && this.$bias <= 0) { - } else { - r.start.column += colDiff; - r.start.row += lineDif; - } - } - if (r.end.row == startRow && r.end.column >= start.column) { - if (r.end.column == start.column && this.$bias < 0) { - continue; - } - if (r.end.column == start.column && colDiff > 0 && i < n - 1) { - if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column) - r.end.column -= colDiff; - } - r.end.column += colDiff; - r.end.row += lineDif; - } - } - } else { - var lineDif = startRow - endRow; - var colDiff = start.column - end.column; - for (; i < n; i++) { - var r = ranges[i]; - - if (r.start.row > endRow) - break; - - if (r.end.row < endRow - && ( - startRow < r.end.row - || startRow == r.end.row && start.column < r.end.column - ) - ) { - r.end.row = startRow; - r.end.column = start.column; - } - else if (r.end.row == endRow) { - if (r.end.column <= end.column) { - if (lineDif || r.end.column > start.column) { - r.end.column = start.column; - r.end.row = start.row; - } - } - else { - r.end.column += colDiff; - r.end.row += lineDif; - } - } - else if (r.end.row > endRow) { - r.end.row += lineDif; - } - - if (r.start.row < endRow - && ( - startRow < r.start.row - || startRow == r.start.row && start.column < r.start.column - ) - ) { - r.start.row = startRow; - r.start.column = start.column; - } - else if (r.start.row == endRow) { - if (r.start.column <= end.column) { - if (lineDif || r.start.column > start.column) { - r.start.column = start.column; - r.start.row = start.row; - } - } - else { - r.start.column += colDiff; - r.start.row += lineDif; - } - } - else if (r.start.row > endRow) { - r.start.row += lineDif; - } - } - } - - if (lineDif != 0 && i < n) { - for (; i < n; i++) { - var r = ranges[i]; - r.start.row += lineDif; - r.end.row += lineDif; - } - } - }; - -}).call(RangeList.prototype); - -exports.RangeList = RangeList; -}); - -define("ace/edit_session/fold",["require","exports","module","ace/range_list","ace/lib/oop"], function(require, exports, module) { -"use strict"; - -var RangeList = require("../range_list").RangeList; -var oop = require("../lib/oop"); -var Fold = exports.Fold = function(range, placeholder) { - this.foldLine = null; - this.placeholder = placeholder; - this.range = range; - this.start = range.start; - this.end = range.end; - - this.sameRow = range.start.row == range.end.row; - this.subFolds = this.ranges = []; -}; - -oop.inherits(Fold, RangeList); - -(function() { - - this.toString = function() { - return '"' + this.placeholder + '" ' + this.range.toString(); - }; - - this.setFoldLine = function(foldLine) { - this.foldLine = foldLine; - this.subFolds.forEach(function(fold) { - fold.setFoldLine(foldLine); - }); - }; - - this.clone = function() { - var range = this.range.clone(); - var fold = new Fold(range, this.placeholder); - this.subFolds.forEach(function(subFold) { - fold.subFolds.push(subFold.clone()); - }); - fold.collapseChildren = this.collapseChildren; - return fold; - }; - - this.addSubFold = function(fold) { - if (this.range.isEqual(fold)) - return; - consumeRange(fold, this.start); - - var row = fold.start.row, column = fold.start.column; - for (var i = 0, cmp = -1; i < this.subFolds.length; i++) { - cmp = this.subFolds[i].range.compare(row, column); - if (cmp != 1) - break; - } - var afterStart = this.subFolds[i]; - var firstConsumed = 0; - - if (cmp == 0) { - if (afterStart.range.containsRange(fold)) - return afterStart.addSubFold(fold); - else - firstConsumed = 1; - } - var row = fold.range.end.row, column = fold.range.end.column; - for (var j = i, cmp = -1; j < this.subFolds.length; j++) { - cmp = this.subFolds[j].range.compare(row, column); - if (cmp != 1) - break; - } - if (cmp == 0) j++; - var consumedFolds = this.subFolds.splice(i, j - i, fold); - var last = cmp == 0 ? consumedFolds.length - 1 : consumedFolds.length; - for (var k = firstConsumed; k < last; k++) { - fold.addSubFold(consumedFolds[k]); - } - fold.setFoldLine(this.foldLine); - - return fold; - }; - - this.restoreRange = function(range) { - return restoreRange(range, this.start); - }; - -}).call(Fold.prototype); - -function consumePoint(point, anchor) { - point.row -= anchor.row; - if (point.row == 0) - point.column -= anchor.column; -} -function consumeRange(range, anchor) { - consumePoint(range.start, anchor); - consumePoint(range.end, anchor); -} -function restorePoint(point, anchor) { - if (point.row == 0) - point.column += anchor.column; - point.row += anchor.row; -} -function restoreRange(range, anchor) { - restorePoint(range.start, anchor); - restorePoint(range.end, anchor); -} - -}); - -define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(require, exports, module) { -"use strict"; - -var Range = require("../range").Range; -var FoldLine = require("./fold_line").FoldLine; -var Fold = require("./fold").Fold; -var TokenIterator = require("../token_iterator").TokenIterator; - -function Folding() { - this.getFoldAt = function(row, column, side) { - var foldLine = this.getFoldLine(row); - if (!foldLine) - return null; - - var folds = foldLine.folds; - for (var i = 0; i < folds.length; i++) { - var range = folds[i].range; - if (range.contains(row, column)) { - if (side == 1 && range.isEnd(row, column) && !range.isEmpty()) { - continue; - } else if (side == -1 && range.isStart(row, column) && !range.isEmpty()) { - continue; - } - return folds[i]; - } - } - }; - this.getFoldsInRange = function(range) { - var start = range.start; - var end = range.end; - var foldLines = this.$foldData; - var foundFolds = []; - - start.column += 1; - end.column -= 1; - - for (var i = 0; i < foldLines.length; i++) { - var cmp = foldLines[i].range.compareRange(range); - if (cmp == 2) { - continue; - } - else if (cmp == -2) { - break; - } - - var folds = foldLines[i].folds; - for (var j = 0; j < folds.length; j++) { - var fold = folds[j]; - cmp = fold.range.compareRange(range); - if (cmp == -2) { - break; - } else if (cmp == 2) { - continue; - } else - if (cmp == 42) { - break; - } - foundFolds.push(fold); - } - } - start.column -= 1; - end.column += 1; - - return foundFolds; - }; - - this.getFoldsInRangeList = function(ranges) { - if (Array.isArray(ranges)) { - var folds = []; - ranges.forEach(function(range) { - folds = folds.concat(this.getFoldsInRange(range)); - }, this); - } else { - var folds = this.getFoldsInRange(ranges); - } - return folds; - }; - this.getAllFolds = function() { - var folds = []; - var foldLines = this.$foldData; - - for (var i = 0; i < foldLines.length; i++) - for (var j = 0; j < foldLines[i].folds.length; j++) - folds.push(foldLines[i].folds[j]); - - return folds; - }; - this.getFoldStringAt = function(row, column, trim, foldLine) { - foldLine = foldLine || this.getFoldLine(row); - if (!foldLine) - return null; - - var lastFold = { - end: { column: 0 } - }; - var str, fold; - for (var i = 0; i < foldLine.folds.length; i++) { - fold = foldLine.folds[i]; - var cmp = fold.range.compareEnd(row, column); - if (cmp == -1) { - str = this - .getLine(fold.start.row) - .substring(lastFold.end.column, fold.start.column); - break; - } - else if (cmp === 0) { - return null; - } - lastFold = fold; - } - if (!str) - str = this.getLine(fold.start.row).substring(lastFold.end.column); - - if (trim == -1) - return str.substring(0, column - lastFold.end.column); - else if (trim == 1) - return str.substring(column - lastFold.end.column); - else - return str; - }; - - this.getFoldLine = function(docRow, startFoldLine) { - var foldData = this.$foldData; - var i = 0; - if (startFoldLine) - i = foldData.indexOf(startFoldLine); - if (i == -1) - i = 0; - for (i; i < foldData.length; i++) { - var foldLine = foldData[i]; - if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) { - return foldLine; - } else if (foldLine.end.row > docRow) { - return null; - } - } - return null; - }; - this.getNextFoldLine = function(docRow, startFoldLine) { - var foldData = this.$foldData; - var i = 0; - if (startFoldLine) - i = foldData.indexOf(startFoldLine); - if (i == -1) - i = 0; - for (i; i < foldData.length; i++) { - var foldLine = foldData[i]; - if (foldLine.end.row >= docRow) { - return foldLine; - } - } - return null; - }; - - this.getFoldedRowCount = function(first, last) { - var foldData = this.$foldData, rowCount = last-first+1; - for (var i = 0; i < foldData.length; i++) { - var foldLine = foldData[i], - end = foldLine.end.row, - start = foldLine.start.row; - if (end >= last) { - if (start < last) { - if (start >= first) - rowCount -= last-start; - else - rowCount = 0; // in one fold - } - break; - } else if (end >= first){ - if (start >= first) // fold inside range - rowCount -= end-start; - else - rowCount -= end-first+1; - } - } - return rowCount; - }; - - this.$addFoldLine = function(foldLine) { - this.$foldData.push(foldLine); - this.$foldData.sort(function(a, b) { - return a.start.row - b.start.row; - }); - return foldLine; - }; - this.addFold = function(placeholder, range) { - var foldData = this.$foldData; - var added = false; - var fold; - - if (placeholder instanceof Fold) - fold = placeholder; - else { - fold = new Fold(range, placeholder); - fold.collapseChildren = range.collapseChildren; - } - this.$clipRangeToDocument(fold.range); - - var startRow = fold.start.row; - var startColumn = fold.start.column; - var endRow = fold.end.row; - var endColumn = fold.end.column; - - var startFold = this.getFoldAt(startRow, startColumn, 1); - var endFold = this.getFoldAt(endRow, endColumn, -1); - if (startFold && endFold == startFold) - return startFold.addSubFold(fold); - - if (startFold && !startFold.range.isStart(startRow, startColumn)) - this.removeFold(startFold); - - if (endFold && !endFold.range.isEnd(endRow, endColumn)) - this.removeFold(endFold); - var folds = this.getFoldsInRange(fold.range); - if (folds.length > 0) { - this.removeFolds(folds); - if (!fold.collapseChildren) { - folds.forEach(function(subFold) { - fold.addSubFold(subFold); - }); - } - } - - for (var i = 0; i < foldData.length; i++) { - var foldLine = foldData[i]; - if (endRow == foldLine.start.row) { - foldLine.addFold(fold); - added = true; - break; - } else if (startRow == foldLine.end.row) { - foldLine.addFold(fold); - added = true; - if (!fold.sameRow) { - var foldLineNext = foldData[i + 1]; - if (foldLineNext && foldLineNext.start.row == endRow) { - foldLine.merge(foldLineNext); - break; - } - } - break; - } else if (endRow <= foldLine.start.row) { - break; - } - } - - if (!added) - foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold)); - - if (this.$useWrapMode) - this.$updateWrapData(foldLine.start.row, foldLine.start.row); - else - this.$updateRowLengthCache(foldLine.start.row, foldLine.start.row); - this.$modified = true; - this._signal("changeFold", { data: fold, action: "add" }); - - return fold; - }; - - this.addFolds = function(folds) { - folds.forEach(function(fold) { - this.addFold(fold); - }, this); - }; - - this.removeFold = function(fold) { - var foldLine = fold.foldLine; - var startRow = foldLine.start.row; - var endRow = foldLine.end.row; - - var foldLines = this.$foldData; - var folds = foldLine.folds; - if (folds.length == 1) { - foldLines.splice(foldLines.indexOf(foldLine), 1); - } else - if (foldLine.range.isEnd(fold.end.row, fold.end.column)) { - folds.pop(); - foldLine.end.row = folds[folds.length - 1].end.row; - foldLine.end.column = folds[folds.length - 1].end.column; - } else - if (foldLine.range.isStart(fold.start.row, fold.start.column)) { - folds.shift(); - foldLine.start.row = folds[0].start.row; - foldLine.start.column = folds[0].start.column; - } else - if (fold.sameRow) { - folds.splice(folds.indexOf(fold), 1); - } else - { - var newFoldLine = foldLine.split(fold.start.row, fold.start.column); - folds = newFoldLine.folds; - folds.shift(); - newFoldLine.start.row = folds[0].start.row; - newFoldLine.start.column = folds[0].start.column; - } - - if (!this.$updating) { - if (this.$useWrapMode) - this.$updateWrapData(startRow, endRow); - else - this.$updateRowLengthCache(startRow, endRow); - } - this.$modified = true; - this._signal("changeFold", { data: fold, action: "remove" }); - }; - - this.removeFolds = function(folds) { - var cloneFolds = []; - for (var i = 0; i < folds.length; i++) { - cloneFolds.push(folds[i]); - } - - cloneFolds.forEach(function(fold) { - this.removeFold(fold); - }, this); - this.$modified = true; - }; - - this.expandFold = function(fold) { - this.removeFold(fold); - fold.subFolds.forEach(function(subFold) { - fold.restoreRange(subFold); - this.addFold(subFold); - }, this); - if (fold.collapseChildren > 0) { - this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1); - } - fold.subFolds = []; - }; - - this.expandFolds = function(folds) { - folds.forEach(function(fold) { - this.expandFold(fold); - }, this); - }; - - this.unfold = function(location, expandInner) { - var range, folds; - if (location == null) { - range = new Range(0, 0, this.getLength(), 0); - if (expandInner == null) expandInner = true; - } else if (typeof location == "number") { - range = new Range(location, 0, location, this.getLine(location).length); - } else if ("row" in location) { - range = Range.fromPoints(location, location); - } else if (Array.isArray(location)) { - folds = []; - location.forEach(function(range) { - folds = folds.concat(this.unfold(range)); - }, this); - return folds; - } else { - range = location; - } - - folds = this.getFoldsInRangeList(range); - var outermostFolds = folds; - while ( - folds.length == 1 - && Range.comparePoints(folds[0].start, range.start) < 0 - && Range.comparePoints(folds[0].end, range.end) > 0 - ) { - this.expandFolds(folds); - folds = this.getFoldsInRangeList(range); - } - - if (expandInner != false) { - this.removeFolds(folds); - } else { - this.expandFolds(folds); - } - if (outermostFolds.length) - return outermostFolds; - }; - this.isRowFolded = function(docRow, startFoldRow) { - return !!this.getFoldLine(docRow, startFoldRow); - }; - - this.getRowFoldEnd = function(docRow, startFoldRow) { - var foldLine = this.getFoldLine(docRow, startFoldRow); - return foldLine ? foldLine.end.row : docRow; - }; - - this.getRowFoldStart = function(docRow, startFoldRow) { - var foldLine = this.getFoldLine(docRow, startFoldRow); - return foldLine ? foldLine.start.row : docRow; - }; - - this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) { - if (startRow == null) - startRow = foldLine.start.row; - if (startColumn == null) - startColumn = 0; - if (endRow == null) - endRow = foldLine.end.row; - if (endColumn == null) - endColumn = this.getLine(endRow).length; - var doc = this.doc; - var textLine = ""; - - foldLine.walk(function(placeholder, row, column, lastColumn) { - if (row < startRow) - return; - if (row == startRow) { - if (column < startColumn) - return; - lastColumn = Math.max(startColumn, lastColumn); - } - - if (placeholder != null) { - textLine += placeholder; - } else { - textLine += doc.getLine(row).substring(lastColumn, column); - } - }, endRow, endColumn); - return textLine; - }; - - this.getDisplayLine = function(row, endColumn, startRow, startColumn) { - var foldLine = this.getFoldLine(row); - - if (!foldLine) { - var line; - line = this.doc.getLine(row); - return line.substring(startColumn || 0, endColumn || line.length); - } else { - return this.getFoldDisplayLine( - foldLine, row, endColumn, startRow, startColumn); - } - }; - - this.$cloneFoldData = function() { - var fd = []; - fd = this.$foldData.map(function(foldLine) { - var folds = foldLine.folds.map(function(fold) { - return fold.clone(); - }); - return new FoldLine(fd, folds); - }); - - return fd; - }; - - this.toggleFold = function(tryToUnfold) { - var selection = this.selection; - var range = selection.getRange(); - var fold; - var bracketPos; - - if (range.isEmpty()) { - var cursor = range.start; - fold = this.getFoldAt(cursor.row, cursor.column); - - if (fold) { - this.expandFold(fold); - return; - } else if (bracketPos = this.findMatchingBracket(cursor)) { - if (range.comparePoint(bracketPos) == 1) { - range.end = bracketPos; - } else { - range.start = bracketPos; - range.start.column++; - range.end.column--; - } - } else if (bracketPos = this.findMatchingBracket({row: cursor.row, column: cursor.column + 1})) { - if (range.comparePoint(bracketPos) == 1) - range.end = bracketPos; - else - range.start = bracketPos; - - range.start.column++; - } else { - range = this.getCommentFoldRange(cursor.row, cursor.column) || range; - } - } else { - var folds = this.getFoldsInRange(range); - if (tryToUnfold && folds.length) { - this.expandFolds(folds); - return; - } else if (folds.length == 1 ) { - fold = folds[0]; - } - } - - if (!fold) - fold = this.getFoldAt(range.start.row, range.start.column); - - if (fold && fold.range.toString() == range.toString()) { - this.expandFold(fold); - return; - } - - var placeholder = "..."; - if (!range.isMultiLine()) { - placeholder = this.getTextRange(range); - if (placeholder.length < 4) - return; - placeholder = placeholder.trim().substring(0, 2) + ".."; - } - - this.addFold(placeholder, range); - }; - - this.getCommentFoldRange = function(row, column, dir) { - var iterator = new TokenIterator(this, row, column); - var token = iterator.getCurrentToken(); - var type = token && token.type; - if (token && /^comment|string/.test(type)) { - type = type.match(/comment|string/)[0]; - if (type == "comment") - type += "|doc-start"; - var re = new RegExp(type); - var range = new Range(); - if (dir != 1) { - do { - token = iterator.stepBackward(); - } while (token && re.test(token.type)); - iterator.stepForward(); - } - - range.start.row = iterator.getCurrentTokenRow(); - range.start.column = iterator.getCurrentTokenColumn() + 2; - - iterator = new TokenIterator(this, row, column); - - if (dir != -1) { - var lastRow = -1; - do { - token = iterator.stepForward(); - if (lastRow == -1) { - var state = this.getState(iterator.$row); - if (!re.test(state)) - lastRow = iterator.$row; - } else if (iterator.$row > lastRow) { - break; - } - } while (token && re.test(token.type)); - token = iterator.stepBackward(); - } else - token = iterator.getCurrentToken(); - - range.end.row = iterator.getCurrentTokenRow(); - range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2; - return range; - } - }; - - this.foldAll = function(startRow, endRow, depth, test) { - if (depth == undefined) - depth = 100000; // JSON.stringify doesn't hanle Infinity - var foldWidgets = this.foldWidgets; - if (!foldWidgets) - return; // mode doesn't support folding - endRow = endRow || this.getLength(); - startRow = startRow || 0; - for (var row = startRow; row < endRow; row++) { - if (foldWidgets[row] == null) - foldWidgets[row] = this.getFoldWidget(row); - if (foldWidgets[row] != "start") - continue; - - if (test && !test(row)) continue; - - var range = this.getFoldWidgetRange(row); - if (range && range.isMultiLine() - && range.end.row <= endRow - && range.start.row >= startRow - ) { - row = range.end.row; - range.collapseChildren = depth; - this.addFold("...", range); - } - } - }; - - this.foldToLevel = function(level) { - this.foldAll(); - while (level-- > 0) - this.unfold(null, false); - }; - - this.foldAllComments = function() { - var session = this; - this.foldAll(null, null, null, function(row) { - var tokens = session.getTokens(row); - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (token.type == "text" && /^\s+$/.test(token.value)) - continue; - if (/comment/.test(token.type)) - return true; - return false; - } - }); - }; - this.$foldStyles = { - "manual": 1, - "markbegin": 1, - "markbeginend": 1 - }; - this.$foldStyle = "markbegin"; - this.setFoldStyle = function(style) { - if (!this.$foldStyles[style]) - throw new Error("invalid fold style: " + style + "[" + Object.keys(this.$foldStyles).join(", ") + "]"); - - if (this.$foldStyle == style) - return; - - this.$foldStyle = style; - - if (style == "manual") - this.unfold(); - var mode = this.$foldMode; - this.$setFolding(null); - this.$setFolding(mode); - }; - - this.$setFolding = function(foldMode) { - if (this.$foldMode == foldMode) - return; - - this.$foldMode = foldMode; - - this.off('change', this.$updateFoldWidgets); - this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); - this._signal("changeAnnotation"); - - if (!foldMode || this.$foldStyle == "manual") { - this.foldWidgets = null; - return; - } - - this.foldWidgets = []; - this.getFoldWidget = foldMode.getFoldWidget.bind(foldMode, this, this.$foldStyle); - this.getFoldWidgetRange = foldMode.getFoldWidgetRange.bind(foldMode, this, this.$foldStyle); - - this.$updateFoldWidgets = this.updateFoldWidgets.bind(this); - this.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this); - this.on('change', this.$updateFoldWidgets); - this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); - }; - - this.getParentFoldRangeData = function (row, ignoreCurrent) { - var fw = this.foldWidgets; - if (!fw || (ignoreCurrent && fw[row])) - return {}; - - var i = row - 1, firstRange; - while (i >= 0) { - var c = fw[i]; - if (c == null) - c = fw[i] = this.getFoldWidget(i); - - if (c == "start") { - var range = this.getFoldWidgetRange(i); - if (!firstRange) - firstRange = range; - if (range && range.end.row >= row) - break; - } - i--; - } - - return { - range: i !== -1 && range, - firstRange: firstRange - }; - }; - - this.onFoldWidgetClick = function(row, e) { - e = e.domEvent; - var options = { - children: e.shiftKey, - all: e.ctrlKey || e.metaKey, - siblings: e.altKey - }; - - var range = this.$toggleFoldWidget(row, options); - if (!range) { - var el = (e.target || e.srcElement); - if (el && /ace_fold-widget/.test(el.className)) - el.className += " ace_invalid"; - } - }; - - this.$toggleFoldWidget = function(row, options) { - if (!this.getFoldWidget) - return; - var type = this.getFoldWidget(row); - var line = this.getLine(row); - - var dir = type === "end" ? -1 : 1; - var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir); - - if (fold) { - if (options.children || options.all) - this.removeFold(fold); - else - this.expandFold(fold); - return fold; - } - - var range = this.getFoldWidgetRange(row, true); - if (range && !range.isMultiLine()) { - fold = this.getFoldAt(range.start.row, range.start.column, 1); - if (fold && range.isEqual(fold.range)) { - this.removeFold(fold); - return fold; - } - } - - if (options.siblings) { - var data = this.getParentFoldRangeData(row); - if (data.range) { - var startRow = data.range.start.row + 1; - var endRow = data.range.end.row; - } - this.foldAll(startRow, endRow, options.all ? 10000 : 0); - } else if (options.children) { - endRow = range ? range.end.row : this.getLength(); - this.foldAll(row + 1, endRow, options.all ? 10000 : 0); - } else if (range) { - if (options.all) - range.collapseChildren = 10000; - this.addFold("...", range); - } - - return range; - }; - - - - this.toggleFoldWidget = function(toggleParent) { - var row = this.selection.getCursor().row; - row = this.getRowFoldStart(row); - var range = this.$toggleFoldWidget(row, {}); - - if (range) - return; - var data = this.getParentFoldRangeData(row, true); - range = data.range || data.firstRange; - - if (range) { - row = range.start.row; - var fold = this.getFoldAt(row, this.getLine(row).length, 1); - - if (fold) { - this.removeFold(fold); - } else { - this.addFold("...", range); - } - } - }; - - this.updateFoldWidgets = function(delta) { - var firstRow = delta.start.row; - var len = delta.end.row - firstRow; - - if (len === 0) { - this.foldWidgets[firstRow] = null; - } else if (delta.action == 'remove') { - this.foldWidgets.splice(firstRow, len + 1, null); - } else { - var args = Array(len + 1); - args.unshift(firstRow, 1); - this.foldWidgets.splice.apply(this.foldWidgets, args); - } - }; - this.tokenizerUpdateFoldWidgets = function(e) { - var rows = e.data; - if (rows.first != rows.last) { - if (this.foldWidgets.length > rows.first) - this.foldWidgets.splice(rows.first, this.foldWidgets.length); - } - }; -} - -exports.Folding = Folding; - -}); - -define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(require, exports, module) { -"use strict"; - -var TokenIterator = require("../token_iterator").TokenIterator; -var Range = require("../range").Range; - - -function BracketMatch() { - - this.findMatchingBracket = function(position, chr) { - if (position.column == 0) return null; - - var charBeforeCursor = chr || this.getLine(position.row).charAt(position.column-1); - if (charBeforeCursor == "") return null; - - var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/); - if (!match) - return null; - - if (match[1]) - return this.$findClosingBracket(match[1], position); - else - return this.$findOpeningBracket(match[2], position); - }; - - this.getBracketRange = function(pos) { - var line = this.getLine(pos.row); - var before = true, range; - - var chr = line.charAt(pos.column - 1); - var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); - if (!match) { - chr = line.charAt(pos.column); - pos = {row: pos.row, column: pos.column + 1}; - match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); - before = false; - } - if (!match) - return null; - - if (match[1]) { - var bracketPos = this.$findClosingBracket(match[1], pos); - if (!bracketPos) - return null; - range = Range.fromPoints(pos, bracketPos); - if (!before) { - range.end.column++; - range.start.column--; - } - range.cursor = range.end; - } else { - var bracketPos = this.$findOpeningBracket(match[2], pos); - if (!bracketPos) - return null; - range = Range.fromPoints(bracketPos, pos); - if (!before) { - range.start.column++; - range.end.column--; - } - range.cursor = range.start; - } - - return range; - }; - this.getMatchingBracketRanges = function(pos) { - var line = this.getLine(pos.row); - - var chr = line.charAt(pos.column - 1); - var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); - if (!match) { - chr = line.charAt(pos.column); - pos = {row: pos.row, column: pos.column + 1}; - match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); - } - - if (!match) - return null; - - var startRange = new Range(pos.row, pos.column - 1, pos.row, pos.column); - var bracketPos = match[1] ? this.$findClosingBracket(match[1], pos) - : this.$findOpeningBracket(match[2], pos); - if (!bracketPos) - return [startRange]; - var endRange = new Range(bracketPos.row, bracketPos.column, bracketPos.row, bracketPos.column + 1); - - return [startRange, endRange]; - }; - - this.$brackets = { - ")": "(", - "(": ")", - "]": "[", - "[": "]", - "{": "}", - "}": "{", - "<": ">", - ">": "<" - }; - - this.$findOpeningBracket = function(bracket, position, typeRe) { - var openBracket = this.$brackets[bracket]; - var depth = 1; - - var iterator = new TokenIterator(this, position.row, position.column); - var token = iterator.getCurrentToken(); - if (!token) - token = iterator.stepForward(); - if (!token) - return; - - if (!typeRe){ - typeRe = new RegExp( - "(\\.?" + - token.type.replace(".", "\\.").replace("rparen", ".paren") - .replace(/\b(?:end)\b/, "(?:start|begin|end)") - + ")+" - ); - } - var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2; - var value = token.value; - - while (true) { - - while (valueIndex >= 0) { - var chr = value.charAt(valueIndex); - if (chr == openBracket) { - depth -= 1; - if (depth == 0) { - return {row: iterator.getCurrentTokenRow(), - column: valueIndex + iterator.getCurrentTokenColumn()}; - } - } - else if (chr == bracket) { - depth += 1; - } - valueIndex -= 1; - } - do { - token = iterator.stepBackward(); - } while (token && !typeRe.test(token.type)); - - if (token == null) - break; - - value = token.value; - valueIndex = value.length - 1; - } - - return null; - }; - - this.$findClosingBracket = function(bracket, position, typeRe) { - var closingBracket = this.$brackets[bracket]; - var depth = 1; - - var iterator = new TokenIterator(this, position.row, position.column); - var token = iterator.getCurrentToken(); - if (!token) - token = iterator.stepForward(); - if (!token) - return; - - if (!typeRe){ - typeRe = new RegExp( - "(\\.?" + - token.type.replace(".", "\\.").replace("lparen", ".paren") - .replace(/\b(?:start|begin)\b/, "(?:start|begin|end)") - + ")+" - ); - } - var valueIndex = position.column - iterator.getCurrentTokenColumn(); - - while (true) { - - var value = token.value; - var valueLength = value.length; - while (valueIndex < valueLength) { - var chr = value.charAt(valueIndex); - if (chr == closingBracket) { - depth -= 1; - if (depth == 0) { - return {row: iterator.getCurrentTokenRow(), - column: valueIndex + iterator.getCurrentTokenColumn()}; - } - } - else if (chr == bracket) { - depth += 1; - } - valueIndex += 1; - } - do { - token = iterator.stepForward(); - } while (token && !typeRe.test(token.type)); - - if (token == null) - break; - - valueIndex = 0; - } - - return null; - }; -} -exports.BracketMatch = BracketMatch; - -}); - -define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/bidihandler","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var lang = require("./lib/lang"); -var BidiHandler = require("./bidihandler").BidiHandler; -var config = require("./config"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var Selection = require("./selection").Selection; -var TextMode = require("./mode/text").Mode; -var Range = require("./range").Range; -var Document = require("./document").Document; -var BackgroundTokenizer = require("./background_tokenizer").BackgroundTokenizer; -var SearchHighlight = require("./search_highlight").SearchHighlight; - -var EditSession = function(text, mode) { - this.$breakpoints = []; - this.$decorations = []; - this.$frontMarkers = {}; - this.$backMarkers = {}; - this.$markerId = 1; - this.$undoSelect = true; - - this.$foldData = []; - this.id = "session" + (++EditSession.$uid); - this.$foldData.toString = function() { - return this.join("\n"); - }; - this.on("changeFold", this.onChangeFold.bind(this)); - this.$onChange = this.onChange.bind(this); - - if (typeof text != "object" || !text.getLine) - text = new Document(text); - - this.setDocument(text); - this.selection = new Selection(this); - this.$bidiHandler = new BidiHandler(this); - - config.resetOptions(this); - this.setMode(mode); - config._signal("session", this); -}; - - -EditSession.$uid = 0; - -(function() { - - oop.implement(this, EventEmitter); - this.setDocument = function(doc) { - if (this.doc) - this.doc.off("change", this.$onChange); - - this.doc = doc; - doc.on("change", this.$onChange); - - if (this.bgTokenizer) - this.bgTokenizer.setDocument(this.getDocument()); - - this.resetCaches(); - }; - this.getDocument = function() { - return this.doc; - }; - this.$resetRowCache = function(docRow) { - if (!docRow) { - this.$docRowCache = []; - this.$screenRowCache = []; - return; - } - var l = this.$docRowCache.length; - var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1; - if (l > i) { - this.$docRowCache.splice(i, l); - this.$screenRowCache.splice(i, l); - } - }; - - this.$getRowCacheIndex = function(cacheArray, val) { - var low = 0; - var hi = cacheArray.length - 1; - - while (low <= hi) { - var mid = (low + hi) >> 1; - var c = cacheArray[mid]; - - if (val > c) - low = mid + 1; - else if (val < c) - hi = mid - 1; - else - return mid; - } - - return low -1; - }; - - this.resetCaches = function() { - this.$modified = true; - this.$wrapData = []; - this.$rowLengthCache = []; - this.$resetRowCache(0); - if (this.bgTokenizer) - this.bgTokenizer.start(0); - }; - - this.onChangeFold = function(e) { - var fold = e.data; - this.$resetRowCache(fold.start.row); - }; - - this.onChange = function(delta) { - this.$modified = true; - this.$bidiHandler.onChange(delta); - this.$resetRowCache(delta.start.row); - - var removedFolds = this.$updateInternalDataOnChange(delta); - if (!this.$fromUndo && this.$undoManager) { - if (removedFolds && removedFolds.length) { - this.$undoManager.add({ - action: "removeFolds", - folds: removedFolds - }, this.mergeUndoDeltas); - this.mergeUndoDeltas = true; - } - this.$undoManager.add(delta, this.mergeUndoDeltas); - this.mergeUndoDeltas = true; - - this.$informUndoManager.schedule(); - } - - this.bgTokenizer && this.bgTokenizer.$updateOnChange(delta); - this._signal("change", delta); - }; - this.setValue = function(text) { - this.doc.setValue(text); - this.selection.moveTo(0, 0); - - this.$resetRowCache(0); - this.setUndoManager(this.$undoManager); - this.getUndoManager().reset(); - }; - this.getValue = - this.toString = function() { - return this.doc.getValue(); - }; - this.getSelection = function() { - return this.selection; - }; - this.getState = function(row) { - return this.bgTokenizer.getState(row); - }; - this.getTokens = function(row) { - return this.bgTokenizer.getTokens(row); - }; - this.getTokenAt = function(row, column) { - var tokens = this.bgTokenizer.getTokens(row); - var token, c = 0; - if (column == null) { - var i = tokens.length - 1; - c = this.getLine(row).length; - } else { - for (var i = 0; i < tokens.length; i++) { - c += tokens[i].value.length; - if (c >= column) - break; - } - } - token = tokens[i]; - if (!token) - return null; - token.index = i; - token.start = c - token.value.length; - return token; - }; - this.setUndoManager = function(undoManager) { - this.$undoManager = undoManager; - - if (this.$informUndoManager) - this.$informUndoManager.cancel(); - - if (undoManager) { - var self = this; - undoManager.addSession(this); - this.$syncInformUndoManager = function() { - self.$informUndoManager.cancel(); - self.mergeUndoDeltas = false; - }; - this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager); - } else { - this.$syncInformUndoManager = function() {}; - } - }; - this.markUndoGroup = function() { - if (this.$syncInformUndoManager) - this.$syncInformUndoManager(); - }; - - this.$defaultUndoManager = { - undo: function() {}, - redo: function() {}, - hasUndo: function() {}, - hasRedo: function() {}, - reset: function() {}, - add: function() {}, - addSelection: function() {}, - startNewGroup: function() {}, - addSession: function() {} - }; - this.getUndoManager = function() { - return this.$undoManager || this.$defaultUndoManager; - }; - this.getTabString = function() { - if (this.getUseSoftTabs()) { - return lang.stringRepeat(" ", this.getTabSize()); - } else { - return "\t"; - } - }; - this.setUseSoftTabs = function(val) { - this.setOption("useSoftTabs", val); - }; - this.getUseSoftTabs = function() { - return this.$useSoftTabs && !this.$mode.$indentWithTabs; - }; - this.setTabSize = function(tabSize) { - this.setOption("tabSize", tabSize); - }; - this.getTabSize = function() { - return this.$tabSize; - }; - this.isTabStop = function(position) { - return this.$useSoftTabs && (position.column % this.$tabSize === 0); - }; - this.setNavigateWithinSoftTabs = function (navigateWithinSoftTabs) { - this.setOption("navigateWithinSoftTabs", navigateWithinSoftTabs); - }; - this.getNavigateWithinSoftTabs = function() { - return this.$navigateWithinSoftTabs; - }; - - this.$overwrite = false; - this.setOverwrite = function(overwrite) { - this.setOption("overwrite", overwrite); - }; - this.getOverwrite = function() { - return this.$overwrite; - }; - this.toggleOverwrite = function() { - this.setOverwrite(!this.$overwrite); - }; - this.addGutterDecoration = function(row, className) { - if (!this.$decorations[row]) - this.$decorations[row] = ""; - this.$decorations[row] += " " + className; - this._signal("changeBreakpoint", {}); - }; - this.removeGutterDecoration = function(row, className) { - this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, ""); - this._signal("changeBreakpoint", {}); - }; - this.getBreakpoints = function() { - return this.$breakpoints; - }; - this.setBreakpoints = function(rows) { - this.$breakpoints = []; - for (var i=0; i 0) - inToken = !!line.charAt(column - 1).match(this.tokenRe); - - if (!inToken) - inToken = !!line.charAt(column).match(this.tokenRe); - - if (inToken) - var re = this.tokenRe; - else if (/^\s+$/.test(line.slice(column-1, column+1))) - var re = /\s/; - else - var re = this.nonTokenRe; - - var start = column; - if (start > 0) { - do { - start--; - } - while (start >= 0 && line.charAt(start).match(re)); - start++; - } - - var end = column; - while (end < line.length && line.charAt(end).match(re)) { - end++; - } - - return new Range(row, start, row, end); - }; - this.getAWordRange = function(row, column) { - var wordRange = this.getWordRange(row, column); - var line = this.getLine(wordRange.end.row); - - while (line.charAt(wordRange.end.column).match(/[ \t]/)) { - wordRange.end.column += 1; - } - return wordRange; - }; - this.setNewLineMode = function(newLineMode) { - this.doc.setNewLineMode(newLineMode); - }; - this.getNewLineMode = function() { - return this.doc.getNewLineMode(); - }; - this.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); }; - this.getUseWorker = function() { return this.$useWorker; }; - this.onReloadTokenizer = function(e) { - var rows = e.data; - this.bgTokenizer.start(rows.first); - this._signal("tokenizerUpdate", e); - }; - - this.$modes = config.$modes; - this.$mode = null; - this.$modeId = null; - this.setMode = function(mode, cb) { - if (mode && typeof mode === "object") { - if (mode.getTokenizer) - return this.$onChangeMode(mode); - var options = mode; - var path = options.path; - } else { - path = mode || "ace/mode/text"; - } - if (!this.$modes["ace/mode/text"]) - this.$modes["ace/mode/text"] = new TextMode(); - - if (this.$modes[path] && !options) { - this.$onChangeMode(this.$modes[path]); - cb && cb(); - return; - } - this.$modeId = path; - config.loadModule(["mode", path], function(m) { - if (this.$modeId !== path) - return cb && cb(); - if (this.$modes[path] && !options) { - this.$onChangeMode(this.$modes[path]); - } else if (m && m.Mode) { - m = new m.Mode(options); - if (!options) { - this.$modes[path] = m; - m.$id = path; - } - this.$onChangeMode(m); - } - cb && cb(); - }.bind(this)); - if (!this.$mode) - this.$onChangeMode(this.$modes["ace/mode/text"], true); - }; - - this.$onChangeMode = function(mode, $isPlaceholder) { - if (!$isPlaceholder) - this.$modeId = mode.$id; - if (this.$mode === mode) - return; - - var oldMode = this.$mode; - this.$mode = mode; - - this.$stopWorker(); - - if (this.$useWorker) - this.$startWorker(); - - var tokenizer = mode.getTokenizer(); - - if(tokenizer.on !== undefined) { - var onReloadTokenizer = this.onReloadTokenizer.bind(this); - tokenizer.on("update", onReloadTokenizer); - } - - if (!this.bgTokenizer) { - this.bgTokenizer = new BackgroundTokenizer(tokenizer); - var _self = this; - this.bgTokenizer.on("update", function(e) { - _self._signal("tokenizerUpdate", e); - }); - } else { - this.bgTokenizer.setTokenizer(tokenizer); - } - - this.bgTokenizer.setDocument(this.getDocument()); - - this.tokenRe = mode.tokenRe; - this.nonTokenRe = mode.nonTokenRe; - - - if (!$isPlaceholder) { - if (mode.attachToSession) - mode.attachToSession(this); - this.$options.wrapMethod.set.call(this, this.$wrapMethod); - this.$setFolding(mode.foldingRules); - this.bgTokenizer.start(0); - this._emit("changeMode", {oldMode: oldMode, mode: mode}); - } - }; - - this.$stopWorker = function() { - if (this.$worker) { - this.$worker.terminate(); - this.$worker = null; - } - }; - - this.$startWorker = function() { - try { - this.$worker = this.$mode.createWorker(this); - } catch (e) { - config.warn("Could not load worker", e); - this.$worker = null; - } - }; - this.getMode = function() { - return this.$mode; - }; - - this.$scrollTop = 0; - this.setScrollTop = function(scrollTop) { - if (this.$scrollTop === scrollTop || isNaN(scrollTop)) - return; - - this.$scrollTop = scrollTop; - this._signal("changeScrollTop", scrollTop); - }; - this.getScrollTop = function() { - return this.$scrollTop; - }; - - this.$scrollLeft = 0; - this.setScrollLeft = function(scrollLeft) { - if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft)) - return; - - this.$scrollLeft = scrollLeft; - this._signal("changeScrollLeft", scrollLeft); - }; - this.getScrollLeft = function() { - return this.$scrollLeft; - }; - this.getScreenWidth = function() { - this.$computeWidth(); - if (this.lineWidgets) - return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth); - return this.screenWidth; - }; - - this.getLineWidgetMaxWidth = function() { - if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth; - var width = 0; - this.lineWidgets.forEach(function(w) { - if (w && w.screenWidth > width) - width = w.screenWidth; - }); - return this.lineWidgetWidth = width; - }; - - this.$computeWidth = function(force) { - if (this.$modified || force) { - this.$modified = false; - - if (this.$useWrapMode) - return this.screenWidth = this.$wrapLimit; - - var lines = this.doc.getAllLines(); - var cache = this.$rowLengthCache; - var longestScreenLine = 0; - var foldIndex = 0; - var foldLine = this.$foldData[foldIndex]; - var foldStart = foldLine ? foldLine.start.row : Infinity; - var len = lines.length; - - for (var i = 0; i < len; i++) { - if (i > foldStart) { - i = foldLine.end.row + 1; - if (i >= len) - break; - foldLine = this.$foldData[foldIndex++]; - foldStart = foldLine ? foldLine.start.row : Infinity; - } - - if (cache[i] == null) - cache[i] = this.$getStringScreenWidth(lines[i])[0]; - - if (cache[i] > longestScreenLine) - longestScreenLine = cache[i]; - } - this.screenWidth = longestScreenLine; - } - }; - this.getLine = function(row) { - return this.doc.getLine(row); - }; - this.getLines = function(firstRow, lastRow) { - return this.doc.getLines(firstRow, lastRow); - }; - this.getLength = function() { - return this.doc.getLength(); - }; - this.getTextRange = function(range) { - return this.doc.getTextRange(range || this.selection.getRange()); - }; - this.insert = function(position, text) { - return this.doc.insert(position, text); - }; - this.remove = function(range) { - return this.doc.remove(range); - }; - this.removeFullLines = function(firstRow, lastRow){ - return this.doc.removeFullLines(firstRow, lastRow); - }; - this.undoChanges = function(deltas, dontSelect) { - if (!deltas.length) - return; - - this.$fromUndo = true; - for (var i = deltas.length - 1; i != -1; i--) { - var delta = deltas[i]; - if (delta.action == "insert" || delta.action == "remove") { - this.doc.revertDelta(delta); - } else if (delta.folds) { - this.addFolds(delta.folds); - } - } - if (!dontSelect && this.$undoSelect) { - if (deltas.selectionBefore) - this.selection.fromJSON(deltas.selectionBefore); - else - this.selection.setRange(this.$getUndoSelection(deltas, true)); - } - this.$fromUndo = false; - }; - this.redoChanges = function(deltas, dontSelect) { - if (!deltas.length) - return; - - this.$fromUndo = true; - for (var i = 0; i < deltas.length; i++) { - var delta = deltas[i]; - if (delta.action == "insert" || delta.action == "remove") { - this.doc.$safeApplyDelta(delta); - } - } - - if (!dontSelect && this.$undoSelect) { - if (deltas.selectionAfter) - this.selection.fromJSON(deltas.selectionAfter); - else - this.selection.setRange(this.$getUndoSelection(deltas, false)); - } - this.$fromUndo = false; - }; - this.setUndoSelect = function(enable) { - this.$undoSelect = enable; - }; - - this.$getUndoSelection = function(deltas, isUndo) { - function isInsert(delta) { - return isUndo ? delta.action !== "insert" : delta.action === "insert"; - } - - var range, point; - - for (var i = 0; i < deltas.length; i++) { - var delta = deltas[i]; - if (!delta.start) continue; // skip folds - if (!range) { - if (isInsert(delta)) { - range = Range.fromPoints(delta.start, delta.end); - } else { - range = Range.fromPoints(delta.start, delta.start); - } - continue; - } - - if (isInsert(delta)) { - point = delta.start; - if (range.compare(point.row, point.column) == -1) { - range.setStart(point); - } - point = delta.end; - if (range.compare(point.row, point.column) == 1) { - range.setEnd(point); - } - } else { - point = delta.start; - if (range.compare(point.row, point.column) == -1) { - range = Range.fromPoints(delta.start, delta.start); - } - } - } - return range; - }; - this.replace = function(range, text) { - return this.doc.replace(range, text); - }; - this.moveText = function(fromRange, toPosition, copy) { - var text = this.getTextRange(fromRange); - var folds = this.getFoldsInRange(fromRange); - - var toRange = Range.fromPoints(toPosition, toPosition); - if (!copy) { - this.remove(fromRange); - var rowDiff = fromRange.start.row - fromRange.end.row; - var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column; - if (collDiff) { - if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column) - toRange.start.column += collDiff; - if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column) - toRange.end.column += collDiff; - } - if (rowDiff && toRange.start.row >= fromRange.end.row) { - toRange.start.row += rowDiff; - toRange.end.row += rowDiff; - } - } - - toRange.end = this.insert(toRange.start, text); - if (folds.length) { - var oldStart = fromRange.start; - var newStart = toRange.start; - var rowDiff = newStart.row - oldStart.row; - var collDiff = newStart.column - oldStart.column; - this.addFolds(folds.map(function(x) { - x = x.clone(); - if (x.start.row == oldStart.row) - x.start.column += collDiff; - if (x.end.row == oldStart.row) - x.end.column += collDiff; - x.start.row += rowDiff; - x.end.row += rowDiff; - return x; - })); - } - - return toRange; - }; - this.indentRows = function(startRow, endRow, indentString) { - indentString = indentString.replace(/\t/g, this.getTabString()); - for (var row=startRow; row<=endRow; row++) - this.doc.insertInLine({row: row, column: 0}, indentString); - }; - this.outdentRows = function (range) { - var rowRange = range.collapseRows(); - var deleteRange = new Range(0, 0, 0, 0); - var size = this.getTabSize(); - - for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) { - var line = this.getLine(i); - - deleteRange.start.row = i; - deleteRange.end.row = i; - for (var j = 0; j < size; ++j) - if (line.charAt(j) != ' ') - break; - if (j < size && line.charAt(j) == '\t') { - deleteRange.start.column = j; - deleteRange.end.column = j + 1; - } else { - deleteRange.start.column = 0; - deleteRange.end.column = j; - } - this.remove(deleteRange); - } - }; - - this.$moveLines = function(firstRow, lastRow, dir) { - firstRow = this.getRowFoldStart(firstRow); - lastRow = this.getRowFoldEnd(lastRow); - if (dir < 0) { - var row = this.getRowFoldStart(firstRow + dir); - if (row < 0) return 0; - var diff = row-firstRow; - } else if (dir > 0) { - var row = this.getRowFoldEnd(lastRow + dir); - if (row > this.doc.getLength()-1) return 0; - var diff = row-lastRow; - } else { - firstRow = this.$clipRowToDocument(firstRow); - lastRow = this.$clipRowToDocument(lastRow); - var diff = lastRow - firstRow + 1; - } - - var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE); - var folds = this.getFoldsInRange(range).map(function(x){ - x = x.clone(); - x.start.row += diff; - x.end.row += diff; - return x; - }); - - var lines = dir == 0 - ? this.doc.getLines(firstRow, lastRow) - : this.doc.removeFullLines(firstRow, lastRow); - this.doc.insertFullLines(firstRow+diff, lines); - folds.length && this.addFolds(folds); - return diff; - }; - this.moveLinesUp = function(firstRow, lastRow) { - return this.$moveLines(firstRow, lastRow, -1); - }; - this.moveLinesDown = function(firstRow, lastRow) { - return this.$moveLines(firstRow, lastRow, 1); - }; - this.duplicateLines = function(firstRow, lastRow) { - return this.$moveLines(firstRow, lastRow, 0); - }; - - - this.$clipRowToDocument = function(row) { - return Math.max(0, Math.min(row, this.doc.getLength()-1)); - }; - - this.$clipColumnToRow = function(row, column) { - if (column < 0) - return 0; - return Math.min(this.doc.getLine(row).length, column); - }; - - - this.$clipPositionToDocument = function(row, column) { - column = Math.max(0, column); - - if (row < 0) { - row = 0; - column = 0; - } else { - var len = this.doc.getLength(); - if (row >= len) { - row = len - 1; - column = this.doc.getLine(len-1).length; - } else { - column = Math.min(this.doc.getLine(row).length, column); - } - } - - return { - row: row, - column: column - }; - }; - - this.$clipRangeToDocument = function(range) { - if (range.start.row < 0) { - range.start.row = 0; - range.start.column = 0; - } else { - range.start.column = this.$clipColumnToRow( - range.start.row, - range.start.column - ); - } - - var len = this.doc.getLength() - 1; - if (range.end.row > len) { - range.end.row = len; - range.end.column = this.doc.getLine(len).length; - } else { - range.end.column = this.$clipColumnToRow( - range.end.row, - range.end.column - ); - } - return range; - }; - this.$wrapLimit = 80; - this.$useWrapMode = false; - this.$wrapLimitRange = { - min : null, - max : null - }; - this.setUseWrapMode = function(useWrapMode) { - if (useWrapMode != this.$useWrapMode) { - this.$useWrapMode = useWrapMode; - this.$modified = true; - this.$resetRowCache(0); - if (useWrapMode) { - var len = this.getLength(); - this.$wrapData = Array(len); - this.$updateWrapData(0, len - 1); - } - - this._signal("changeWrapMode"); - } - }; - this.getUseWrapMode = function() { - return this.$useWrapMode; - }; - this.setWrapLimitRange = function(min, max) { - if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) { - this.$wrapLimitRange = { min: min, max: max }; - this.$modified = true; - this.$bidiHandler.markAsDirty(); - if (this.$useWrapMode) - this._signal("changeWrapMode"); - } - }; - this.adjustWrapLimit = function(desiredLimit, $printMargin) { - var limits = this.$wrapLimitRange; - if (limits.max < 0) - limits = {min: $printMargin, max: $printMargin}; - var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max); - if (wrapLimit != this.$wrapLimit && wrapLimit > 1) { - this.$wrapLimit = wrapLimit; - this.$modified = true; - if (this.$useWrapMode) { - this.$updateWrapData(0, this.getLength() - 1); - this.$resetRowCache(0); - this._signal("changeWrapLimit"); - } - return true; - } - return false; - }; - - this.$constrainWrapLimit = function(wrapLimit, min, max) { - if (min) - wrapLimit = Math.max(min, wrapLimit); - - if (max) - wrapLimit = Math.min(max, wrapLimit); - - return wrapLimit; - }; - this.getWrapLimit = function() { - return this.$wrapLimit; - }; - this.setWrapLimit = function (limit) { - this.setWrapLimitRange(limit, limit); - }; - this.getWrapLimitRange = function() { - return { - min : this.$wrapLimitRange.min, - max : this.$wrapLimitRange.max - }; - }; - - this.$updateInternalDataOnChange = function(delta) { - var useWrapMode = this.$useWrapMode; - var action = delta.action; - var start = delta.start; - var end = delta.end; - var firstRow = start.row; - var lastRow = end.row; - var len = lastRow - firstRow; - var removedFolds = null; - - this.$updating = true; - if (len != 0) { - if (action === "remove") { - this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len); - - var foldLines = this.$foldData; - removedFolds = this.getFoldsInRange(delta); - this.removeFolds(removedFolds); - - var foldLine = this.getFoldLine(end.row); - var idx = 0; - if (foldLine) { - foldLine.addRemoveChars(end.row, end.column, start.column - end.column); - foldLine.shiftRow(-len); - - var foldLineBefore = this.getFoldLine(firstRow); - if (foldLineBefore && foldLineBefore !== foldLine) { - foldLineBefore.merge(foldLine); - foldLine = foldLineBefore; - } - idx = foldLines.indexOf(foldLine) + 1; - } - - for (idx; idx < foldLines.length; idx++) { - var foldLine = foldLines[idx]; - if (foldLine.start.row >= end.row) { - foldLine.shiftRow(-len); - } - } - - lastRow = firstRow; - } else { - var args = Array(len); - args.unshift(firstRow, 0); - var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache; - arr.splice.apply(arr, args); - var foldLines = this.$foldData; - var foldLine = this.getFoldLine(firstRow); - var idx = 0; - if (foldLine) { - var cmp = foldLine.range.compareInside(start.row, start.column); - if (cmp == 0) { - foldLine = foldLine.split(start.row, start.column); - if (foldLine) { - foldLine.shiftRow(len); - foldLine.addRemoveChars(lastRow, 0, end.column - start.column); - } - } else - if (cmp == -1) { - foldLine.addRemoveChars(firstRow, 0, end.column - start.column); - foldLine.shiftRow(len); - } - idx = foldLines.indexOf(foldLine) + 1; - } - - for (idx; idx < foldLines.length; idx++) { - var foldLine = foldLines[idx]; - if (foldLine.start.row >= firstRow) { - foldLine.shiftRow(len); - } - } - } - } else { - len = Math.abs(delta.start.column - delta.end.column); - if (action === "remove") { - removedFolds = this.getFoldsInRange(delta); - this.removeFolds(removedFolds); - - len = -len; - } - var foldLine = this.getFoldLine(firstRow); - if (foldLine) { - foldLine.addRemoveChars(firstRow, start.column, len); - } - } - - if (useWrapMode && this.$wrapData.length != this.doc.getLength()) { - console.error("doc.getLength() and $wrapData.length have to be the same!"); - } - this.$updating = false; - - if (useWrapMode) - this.$updateWrapData(firstRow, lastRow); - else - this.$updateRowLengthCache(firstRow, lastRow); - - return removedFolds; - }; - - this.$updateRowLengthCache = function(firstRow, lastRow, b) { - this.$rowLengthCache[firstRow] = null; - this.$rowLengthCache[lastRow] = null; - }; - - this.$updateWrapData = function(firstRow, lastRow) { - var lines = this.doc.getAllLines(); - var tabSize = this.getTabSize(); - var wrapData = this.$wrapData; - var wrapLimit = this.$wrapLimit; - var tokens; - var foldLine; - - var row = firstRow; - lastRow = Math.min(lastRow, lines.length - 1); - while (row <= lastRow) { - foldLine = this.getFoldLine(row, foldLine); - if (!foldLine) { - tokens = this.$getDisplayTokens(lines[row]); - wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); - row ++; - } else { - tokens = []; - foldLine.walk(function(placeholder, row, column, lastColumn) { - var walkTokens; - if (placeholder != null) { - walkTokens = this.$getDisplayTokens( - placeholder, tokens.length); - walkTokens[0] = PLACEHOLDER_START; - for (var i = 1; i < walkTokens.length; i++) { - walkTokens[i] = PLACEHOLDER_BODY; - } - } else { - walkTokens = this.$getDisplayTokens( - lines[row].substring(lastColumn, column), - tokens.length); - } - tokens = tokens.concat(walkTokens); - }.bind(this), - foldLine.end.row, - lines[foldLine.end.row].length + 1 - ); - - wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); - row = foldLine.end.row + 1; - } - } - }; - var CHAR = 1, - CHAR_EXT = 2, - PLACEHOLDER_START = 3, - PLACEHOLDER_BODY = 4, - PUNCTUATION = 9, - SPACE = 10, - TAB = 11, - TAB_SPACE = 12; - - - this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) { - if (tokens.length == 0) { - return []; - } - - var splits = []; - var displayLength = tokens.length; - var lastSplit = 0, lastDocSplit = 0; - - var isCode = this.$wrapAsCode; - - var indentedSoftWrap = this.$indentedSoftWrap; - var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8) - || indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2); - - function getWrapIndent() { - var indentation = 0; - if (maxIndent === 0) - return indentation; - if (indentedSoftWrap) { - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (token == SPACE) - indentation += 1; - else if (token == TAB) - indentation += tabSize; - else if (token == TAB_SPACE) - continue; - else - break; - } - } - if (isCode && indentedSoftWrap !== false) - indentation += tabSize; - return Math.min(indentation, maxIndent); - } - function addSplit(screenPos) { - var len = screenPos - lastSplit; - for (var i = lastSplit; i < screenPos; i++) { - var ch = tokens[i]; - if (ch === 12 || ch === 2) len -= 1; - } - - if (!splits.length) { - indent = getWrapIndent(); - splits.indent = indent; - } - lastDocSplit += len; - splits.push(lastDocSplit); - lastSplit = screenPos; - } - var indent = 0; - while (displayLength - lastSplit > wrapLimit - indent) { - var split = lastSplit + wrapLimit - indent; - if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) { - addSplit(split); - continue; - } - if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) { - for (split; split != lastSplit - 1; split--) { - if (tokens[split] == PLACEHOLDER_START) { - break; - } - } - if (split > lastSplit) { - addSplit(split); - continue; - } - split = lastSplit + wrapLimit; - for (split; split < tokens.length; split++) { - if (tokens[split] != PLACEHOLDER_BODY) { - break; - } - } - if (split == tokens.length) { - break; // Breaks the while-loop. - } - addSplit(split); - continue; - } - var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1); - while (split > minSplit && tokens[split] < PLACEHOLDER_START) { - split --; - } - if (isCode) { - while (split > minSplit && tokens[split] < PLACEHOLDER_START) { - split --; - } - while (split > minSplit && tokens[split] == PUNCTUATION) { - split --; - } - } else { - while (split > minSplit && tokens[split] < SPACE) { - split --; - } - } - if (split > minSplit) { - addSplit(++split); - continue; - } - split = lastSplit + wrapLimit; - if (tokens[split] == CHAR_EXT) - split--; - addSplit(split - indent); - } - return splits; - }; - this.$getDisplayTokens = function(str, offset) { - var arr = []; - var tabSize; - offset = offset || 0; - - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c == 9) { - tabSize = this.getScreenTabSize(arr.length + offset); - arr.push(TAB); - for (var n = 1; n < tabSize; n++) { - arr.push(TAB_SPACE); - } - } - else if (c == 32) { - arr.push(SPACE); - } else if((c > 39 && c < 48) || (c > 57 && c < 64)) { - arr.push(PUNCTUATION); - } - else if (c >= 0x1100 && isFullWidth(c)) { - arr.push(CHAR, CHAR_EXT); - } else { - arr.push(CHAR); - } - } - return arr; - }; - this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { - if (maxScreenColumn == 0) - return [0, 0]; - if (maxScreenColumn == null) - maxScreenColumn = Infinity; - screenColumn = screenColumn || 0; - - var c, column; - for (column = 0; column < str.length; column++) { - c = str.charCodeAt(column); - if (c == 9) { - screenColumn += this.getScreenTabSize(screenColumn); - } - else if (c >= 0x1100 && isFullWidth(c)) { - screenColumn += 2; - } else { - screenColumn += 1; - } - if (screenColumn > maxScreenColumn) { - break; - } - } - - return [screenColumn, column]; - }; - - this.lineWidgets = null; - this.getRowLength = function(row) { - var h = 1; - if (this.lineWidgets) - h += this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; - - if (!this.$useWrapMode || !this.$wrapData[row]) - return h; - else - return this.$wrapData[row].length + h; - }; - this.getRowLineCount = function(row) { - if (!this.$useWrapMode || !this.$wrapData[row]) { - return 1; - } else { - return this.$wrapData[row].length + 1; - } - }; - - this.getRowWrapIndent = function(screenRow) { - if (this.$useWrapMode) { - var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); - var splits = this.$wrapData[pos.row]; - return splits.length && splits[0] < pos.column ? splits.indent : 0; - } else { - return 0; - } - }; - this.getScreenLastRowColumn = function(screenRow) { - var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); - return this.documentToScreenColumn(pos.row, pos.column); - }; - this.getDocumentLastRowColumn = function(docRow, docColumn) { - var screenRow = this.documentToScreenRow(docRow, docColumn); - return this.getScreenLastRowColumn(screenRow); - }; - this.getDocumentLastRowColumnPosition = function(docRow, docColumn) { - var screenRow = this.documentToScreenRow(docRow, docColumn); - return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10); - }; - this.getRowSplitData = function(row) { - if (!this.$useWrapMode) { - return undefined; - } else { - return this.$wrapData[row]; - } - }; - this.getScreenTabSize = function(screenColumn) { - return this.$tabSize - (screenColumn % this.$tabSize | 0); - }; - - - this.screenToDocumentRow = function(screenRow, screenColumn) { - return this.screenToDocumentPosition(screenRow, screenColumn).row; - }; - - - this.screenToDocumentColumn = function(screenRow, screenColumn) { - return this.screenToDocumentPosition(screenRow, screenColumn).column; - }; - this.screenToDocumentPosition = function(screenRow, screenColumn, offsetX) { - if (screenRow < 0) - return {row: 0, column: 0}; - - var line; - var docRow = 0; - var docColumn = 0; - var column; - var row = 0; - var rowLength = 0; - - var rowCache = this.$screenRowCache; - var i = this.$getRowCacheIndex(rowCache, screenRow); - var l = rowCache.length; - if (l && i >= 0) { - var row = rowCache[i]; - var docRow = this.$docRowCache[i]; - var doCache = screenRow > rowCache[l - 1]; - } else { - var doCache = !l; - } - - var maxRow = this.getLength() - 1; - var foldLine = this.getNextFoldLine(docRow); - var foldStart = foldLine ? foldLine.start.row : Infinity; - - while (row <= screenRow) { - rowLength = this.getRowLength(docRow); - if (row + rowLength > screenRow || docRow >= maxRow) { - break; - } else { - row += rowLength; - docRow++; - if (docRow > foldStart) { - docRow = foldLine.end.row+1; - foldLine = this.getNextFoldLine(docRow, foldLine); - foldStart = foldLine ? foldLine.start.row : Infinity; - } - } - - if (doCache) { - this.$docRowCache.push(docRow); - this.$screenRowCache.push(row); - } - } - - if (foldLine && foldLine.start.row <= docRow) { - line = this.getFoldDisplayLine(foldLine); - docRow = foldLine.start.row; - } else if (row + rowLength <= screenRow || docRow > maxRow) { - return { - row: maxRow, - column: this.getLine(maxRow).length - }; - } else { - line = this.getLine(docRow); - foldLine = null; - } - var wrapIndent = 0, splitIndex = Math.floor(screenRow - row); - if (this.$useWrapMode) { - var splits = this.$wrapData[docRow]; - if (splits) { - column = splits[splitIndex]; - if(splitIndex > 0 && splits.length) { - wrapIndent = splits.indent; - docColumn = splits[splitIndex - 1] || splits[splits.length - 1]; - line = line.substring(docColumn); - } - } - } - - if (offsetX !== undefined && this.$bidiHandler.isBidiRow(row + splitIndex, docRow, splitIndex)) - screenColumn = this.$bidiHandler.offsetToCol(offsetX); - - docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1]; - if (this.$useWrapMode && docColumn >= column) - docColumn = column - 1; - - if (foldLine) - return foldLine.idxToPosition(docColumn); - - return {row: docRow, column: docColumn}; - }; - this.documentToScreenPosition = function(docRow, docColumn) { - if (typeof docColumn === "undefined") - var pos = this.$clipPositionToDocument(docRow.row, docRow.column); - else - pos = this.$clipPositionToDocument(docRow, docColumn); - - docRow = pos.row; - docColumn = pos.column; - - var screenRow = 0; - var foldStartRow = null; - var fold = null; - fold = this.getFoldAt(docRow, docColumn, 1); - if (fold) { - docRow = fold.start.row; - docColumn = fold.start.column; - } - - var rowEnd, row = 0; - - - var rowCache = this.$docRowCache; - var i = this.$getRowCacheIndex(rowCache, docRow); - var l = rowCache.length; - if (l && i >= 0) { - var row = rowCache[i]; - var screenRow = this.$screenRowCache[i]; - var doCache = docRow > rowCache[l - 1]; - } else { - var doCache = !l; - } - - var foldLine = this.getNextFoldLine(row); - var foldStart = foldLine ?foldLine.start.row :Infinity; - - while (row < docRow) { - if (row >= foldStart) { - rowEnd = foldLine.end.row + 1; - if (rowEnd > docRow) - break; - foldLine = this.getNextFoldLine(rowEnd, foldLine); - foldStart = foldLine ?foldLine.start.row :Infinity; - } - else { - rowEnd = row + 1; - } - - screenRow += this.getRowLength(row); - row = rowEnd; - - if (doCache) { - this.$docRowCache.push(row); - this.$screenRowCache.push(screenRow); - } - } - var textLine = ""; - if (foldLine && row >= foldStart) { - textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn); - foldStartRow = foldLine.start.row; - } else { - textLine = this.getLine(docRow).substring(0, docColumn); - foldStartRow = docRow; - } - var wrapIndent = 0; - if (this.$useWrapMode) { - var wrapRow = this.$wrapData[foldStartRow]; - if (wrapRow) { - var screenRowOffset = 0; - while (textLine.length >= wrapRow[screenRowOffset]) { - screenRow ++; - screenRowOffset++; - } - textLine = textLine.substring( - wrapRow[screenRowOffset - 1] || 0, textLine.length - ); - wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0; - } - } - - if (this.lineWidgets && this.lineWidgets[row] && this.lineWidgets[row].rowsAbove) - screenRow += this.lineWidgets[row].rowsAbove; - - return { - row: screenRow, - column: wrapIndent + this.$getStringScreenWidth(textLine)[0] - }; - }; - this.documentToScreenColumn = function(row, docColumn) { - return this.documentToScreenPosition(row, docColumn).column; - }; - this.documentToScreenRow = function(docRow, docColumn) { - return this.documentToScreenPosition(docRow, docColumn).row; - }; - this.getScreenLength = function() { - var screenRows = 0; - var fold = null; - if (!this.$useWrapMode) { - screenRows = this.getLength(); - var foldData = this.$foldData; - for (var i = 0; i < foldData.length; i++) { - fold = foldData[i]; - screenRows -= fold.end.row - fold.start.row; - } - } else { - var lastRow = this.$wrapData.length; - var row = 0, i = 0; - var fold = this.$foldData[i++]; - var foldStart = fold ? fold.start.row :Infinity; - - while (row < lastRow) { - var splits = this.$wrapData[row]; - screenRows += splits ? splits.length + 1 : 1; - row ++; - if (row > foldStart) { - row = fold.end.row+1; - fold = this.$foldData[i++]; - foldStart = fold ?fold.start.row :Infinity; - } - } - } - if (this.lineWidgets) - screenRows += this.$getWidgetScreenLength(); - - return screenRows; - }; - this.$setFontMetrics = function(fm) { - if (!this.$enableVarChar) return; - this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { - if (maxScreenColumn === 0) - return [0, 0]; - if (!maxScreenColumn) - maxScreenColumn = Infinity; - screenColumn = screenColumn || 0; - - var c, column; - for (column = 0; column < str.length; column++) { - c = str.charAt(column); - if (c === "\t") { - screenColumn += this.getScreenTabSize(screenColumn); - } else { - screenColumn += fm.getCharacterWidth(c); - } - if (screenColumn > maxScreenColumn) { - break; - } - } - - return [screenColumn, column]; - }; - }; - - this.destroy = function() { - if (this.bgTokenizer) { - this.bgTokenizer.setDocument(null); - this.bgTokenizer = null; - } - this.$stopWorker(); - this.removeAllListeners(); - if (this.doc) { - this.doc.off("change", this.$onChange); - } - this.selection.detach(); - }; - - this.isFullWidth = isFullWidth; - function isFullWidth(c) { - if (c < 0x1100) - return false; - return c >= 0x1100 && c <= 0x115F || - c >= 0x11A3 && c <= 0x11A7 || - c >= 0x11FA && c <= 0x11FF || - c >= 0x2329 && c <= 0x232A || - c >= 0x2E80 && c <= 0x2E99 || - c >= 0x2E9B && c <= 0x2EF3 || - c >= 0x2F00 && c <= 0x2FD5 || - c >= 0x2FF0 && c <= 0x2FFB || - c >= 0x3000 && c <= 0x303E || - c >= 0x3041 && c <= 0x3096 || - c >= 0x3099 && c <= 0x30FF || - c >= 0x3105 && c <= 0x312D || - c >= 0x3131 && c <= 0x318E || - c >= 0x3190 && c <= 0x31BA || - c >= 0x31C0 && c <= 0x31E3 || - c >= 0x31F0 && c <= 0x321E || - c >= 0x3220 && c <= 0x3247 || - c >= 0x3250 && c <= 0x32FE || - c >= 0x3300 && c <= 0x4DBF || - c >= 0x4E00 && c <= 0xA48C || - c >= 0xA490 && c <= 0xA4C6 || - c >= 0xA960 && c <= 0xA97C || - c >= 0xAC00 && c <= 0xD7A3 || - c >= 0xD7B0 && c <= 0xD7C6 || - c >= 0xD7CB && c <= 0xD7FB || - c >= 0xF900 && c <= 0xFAFF || - c >= 0xFE10 && c <= 0xFE19 || - c >= 0xFE30 && c <= 0xFE52 || - c >= 0xFE54 && c <= 0xFE66 || - c >= 0xFE68 && c <= 0xFE6B || - c >= 0xFF01 && c <= 0xFF60 || - c >= 0xFFE0 && c <= 0xFFE6; - } - -}).call(EditSession.prototype); - -require("./edit_session/folding").Folding.call(EditSession.prototype); -require("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype); - - -config.defineOptions(EditSession.prototype, "session", { - wrap: { - set: function(value) { - if (!value || value == "off") - value = false; - else if (value == "free") - value = true; - else if (value == "printMargin") - value = -1; - else if (typeof value == "string") - value = parseInt(value, 10) || false; - - if (this.$wrap == value) - return; - this.$wrap = value; - if (!value) { - this.setUseWrapMode(false); - } else { - var col = typeof value == "number" ? value : null; - this.setWrapLimitRange(col, col); - this.setUseWrapMode(true); - } - }, - get: function() { - if (this.getUseWrapMode()) { - if (this.$wrap == -1) - return "printMargin"; - if (!this.getWrapLimitRange().min) - return "free"; - return this.$wrap; - } - return "off"; - }, - handlesSet: true - }, - wrapMethod: { - set: function(val) { - val = val == "auto" - ? this.$mode.type != "text" - : val != "text"; - if (val != this.$wrapAsCode) { - this.$wrapAsCode = val; - if (this.$useWrapMode) { - this.$useWrapMode = false; - this.setUseWrapMode(true); - } - } - }, - initialValue: "auto" - }, - indentedSoftWrap: { - set: function() { - if (this.$useWrapMode) { - this.$useWrapMode = false; - this.setUseWrapMode(true); - } - }, - initialValue: true - }, - firstLineNumber: { - set: function() {this._signal("changeBreakpoint");}, - initialValue: 1 - }, - useWorker: { - set: function(useWorker) { - this.$useWorker = useWorker; - - this.$stopWorker(); - if (useWorker) - this.$startWorker(); - }, - initialValue: true - }, - useSoftTabs: {initialValue: true}, - tabSize: { - set: function(tabSize) { - tabSize = parseInt(tabSize); - if (tabSize > 0 && this.$tabSize !== tabSize) { - this.$modified = true; - this.$rowLengthCache = []; - this.$tabSize = tabSize; - this._signal("changeTabSize"); - } - }, - initialValue: 4, - handlesSet: true - }, - navigateWithinSoftTabs: {initialValue: false}, - foldStyle: { - set: function(val) {this.setFoldStyle(val);}, - handlesSet: true - }, - overwrite: { - set: function(val) {this._signal("changeOverwrite");}, - initialValue: false - }, - newLineMode: { - set: function(val) {this.doc.setNewLineMode(val);}, - get: function() {return this.doc.getNewLineMode();}, - handlesSet: true - }, - mode: { - set: function(val) { this.setMode(val); }, - get: function() { return this.$modeId; }, - handlesSet: true - } -}); - -exports.EditSession = EditSession; -}); - -define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(require, exports, module) { -"use strict"; - -var lang = require("./lib/lang"); -var oop = require("./lib/oop"); -var Range = require("./range").Range; - -var Search = function() { - this.$options = {}; -}; - -(function() { - this.set = function(options) { - oop.mixin(this.$options, options); - return this; - }; - this.getOptions = function() { - return lang.copyObject(this.$options); - }; - this.setOptions = function(options) { - this.$options = options; - }; - this.find = function(session) { - var options = this.$options; - var iterator = this.$matchIterator(session, options); - if (!iterator) - return false; - - var firstRange = null; - iterator.forEach(function(sr, sc, er, ec) { - firstRange = new Range(sr, sc, er, ec); - if (sc == ec && options.start && options.start.start - && options.skipCurrent != false && firstRange.isEqual(options.start) - ) { - firstRange = null; - return false; - } - - return true; - }); - - return firstRange; - }; - this.findAll = function(session) { - var options = this.$options; - if (!options.needle) - return []; - this.$assembleRegExp(options); - - var range = options.range; - var lines = range - ? session.getLines(range.start.row, range.end.row) - : session.doc.getAllLines(); - - var ranges = []; - var re = options.re; - if (options.$isMultiLine) { - var len = re.length; - var maxRow = lines.length - len; - var prevRange; - outer: for (var row = re.offset || 0; row <= maxRow; row++) { - for (var j = 0; j < len; j++) - if (lines[row + j].search(re[j]) == -1) - continue outer; - - var startLine = lines[row]; - var line = lines[row + len - 1]; - var startIndex = startLine.length - startLine.match(re[0])[0].length; - var endIndex = line.match(re[len - 1])[0].length; - - if (prevRange && prevRange.end.row === row && - prevRange.end.column > startIndex - ) { - continue; - } - ranges.push(prevRange = new Range( - row, startIndex, row + len - 1, endIndex - )); - if (len > 2) - row = row + len - 2; - } - } else { - for (var i = 0; i < lines.length; i++) { - var matches = lang.getMatchOffsets(lines[i], re); - for (var j = 0; j < matches.length; j++) { - var match = matches[j]; - ranges.push(new Range(i, match.offset, i, match.offset + match.length)); - } - } - } - - if (range) { - var startColumn = range.start.column; - var endColumn = range.start.column; - var i = 0, j = ranges.length - 1; - while (i < j && ranges[i].start.column < startColumn && ranges[i].start.row == range.start.row) - i++; - - while (i < j && ranges[j].end.column > endColumn && ranges[j].end.row == range.end.row) - j--; - - ranges = ranges.slice(i, j + 1); - for (i = 0, j = ranges.length; i < j; i++) { - ranges[i].start.row += range.start.row; - ranges[i].end.row += range.start.row; - } - } - - return ranges; - }; - this.replace = function(input, replacement) { - var options = this.$options; - - var re = this.$assembleRegExp(options); - if (options.$isMultiLine) - return replacement; - - if (!re) - return; - - var match = re.exec(input); - if (!match || match[0].length != input.length) - return null; - - replacement = input.replace(re, replacement); - if (options.preserveCase) { - replacement = replacement.split(""); - for (var i = Math.min(input.length, input.length); i--; ) { - var ch = input[i]; - if (ch && ch.toLowerCase() != ch) - replacement[i] = replacement[i].toUpperCase(); - else - replacement[i] = replacement[i].toLowerCase(); - } - replacement = replacement.join(""); - } - - return replacement; - }; - - this.$assembleRegExp = function(options, $disableFakeMultiline) { - if (options.needle instanceof RegExp) - return options.re = options.needle; - - var needle = options.needle; - - if (!options.needle) - return options.re = false; - - if (!options.regExp) - needle = lang.escapeRegExp(needle); - - if (options.wholeWord) - needle = addWordBoundary(needle, options); - - var modifier = options.caseSensitive ? "gm" : "gmi"; - - options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle); - if (options.$isMultiLine) - return options.re = this.$assembleMultilineRegExp(needle, modifier); - - try { - var re = new RegExp(needle, modifier); - } catch(e) { - re = false; - } - return options.re = re; - }; - - this.$assembleMultilineRegExp = function(needle, modifier) { - var parts = needle.replace(/\r\n|\r|\n/g, "$\n^").split("\n"); - var re = []; - for (var i = 0; i < parts.length; i++) try { - re.push(new RegExp(parts[i], modifier)); - } catch(e) { - return false; - } - return re; - }; - - this.$matchIterator = function(session, options) { - var re = this.$assembleRegExp(options); - if (!re) - return false; - var backwards = options.backwards == true; - var skipCurrent = options.skipCurrent != false; - - var range = options.range; - var start = options.start; - if (!start) - start = range ? range[backwards ? "end" : "start"] : session.selection.getRange(); - - if (start.start) - start = start[skipCurrent != backwards ? "end" : "start"]; - - var firstRow = range ? range.start.row : 0; - var lastRow = range ? range.end.row : session.getLength() - 1; - - if (backwards) { - var forEach = function(callback) { - var row = start.row; - if (forEachInLine(row, start.column, callback)) - return; - for (row--; row >= firstRow; row--) - if (forEachInLine(row, Number.MAX_VALUE, callback)) - return; - if (options.wrap == false) - return; - for (row = lastRow, firstRow = start.row; row >= firstRow; row--) - if (forEachInLine(row, Number.MAX_VALUE, callback)) - return; - }; - } - else { - var forEach = function(callback) { - var row = start.row; - if (forEachInLine(row, start.column, callback)) - return; - for (row = row + 1; row <= lastRow; row++) - if (forEachInLine(row, 0, callback)) - return; - if (options.wrap == false) - return; - for (row = firstRow, lastRow = start.row; row <= lastRow; row++) - if (forEachInLine(row, 0, callback)) - return; - }; - } - - if (options.$isMultiLine) { - var len = re.length; - var forEachInLine = function(row, offset, callback) { - var startRow = backwards ? row - len + 1 : row; - if (startRow < 0 || startRow + len > session.getLength()) return; - var line = session.getLine(startRow); - var startIndex = line.search(re[0]); - if (!backwards && startIndex < offset || startIndex === -1) return; - for (var i = 1; i < len; i++) { - line = session.getLine(startRow + i); - if (line.search(re[i]) == -1) - return; - } - var endIndex = line.match(re[len - 1])[0].length; - if (backwards && endIndex > offset) return; - if (callback(startRow, startIndex, startRow + len - 1, endIndex)) - return true; - }; - } - else if (backwards) { - var forEachInLine = function(row, endIndex, callback) { - var line = session.getLine(row); - var matches = []; - var m, last = 0; - re.lastIndex = 0; - while((m = re.exec(line))) { - var length = m[0].length; - last = m.index; - if (!length) { - if (last >= line.length) break; - re.lastIndex = last += 1; - } - if (m.index + length > endIndex) - break; - matches.push(m.index, length); - } - for (var i = matches.length - 1; i >= 0; i -= 2) { - var column = matches[i - 1]; - var length = matches[i]; - if (callback(row, column, row, column + length)) - return true; - } - }; - } - else { - var forEachInLine = function(row, startIndex, callback) { - var line = session.getLine(row); - var last; - var m; - re.lastIndex = startIndex; - while((m = re.exec(line))) { - var length = m[0].length; - last = m.index; - if (callback(row, last, row,last + length)) - return true; - if (!length) { - re.lastIndex = last += 1; - if (last >= line.length) return false; - } - } - }; - } - return {forEach: forEach}; - }; - -}).call(Search.prototype); - -function addWordBoundary(needle, options) { - function wordBoundary(c) { - if (/\w/.test(c) || options.regExp) return "\\b"; - return ""; - } - return wordBoundary(needle[0]) + needle - + wordBoundary(needle[needle.length - 1]); -} - -exports.Search = Search; -}); - -define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(require, exports, module) { -"use strict"; - -var keyUtil = require("../lib/keys"); -var useragent = require("../lib/useragent"); -var KEY_MODS = keyUtil.KEY_MODS; - -function HashHandler(config, platform) { - this.platform = platform || (useragent.isMac ? "mac" : "win"); - this.commands = {}; - this.commandKeyBinding = {}; - this.addCommands(config); - this.$singleCommand = true; -} - -function MultiHashHandler(config, platform) { - HashHandler.call(this, config, platform); - this.$singleCommand = false; -} - -MultiHashHandler.prototype = HashHandler.prototype; - -(function() { - - - this.addCommand = function(command) { - if (this.commands[command.name]) - this.removeCommand(command); - - this.commands[command.name] = command; - - if (command.bindKey) - this._buildKeyHash(command); - }; - - this.removeCommand = function(command, keepCommand) { - var name = command && (typeof command === 'string' ? command : command.name); - command = this.commands[name]; - if (!keepCommand) - delete this.commands[name]; - var ckb = this.commandKeyBinding; - for (var keyId in ckb) { - var cmdGroup = ckb[keyId]; - if (cmdGroup == command) { - delete ckb[keyId]; - } else if (Array.isArray(cmdGroup)) { - var i = cmdGroup.indexOf(command); - if (i != -1) { - cmdGroup.splice(i, 1); - if (cmdGroup.length == 1) - ckb[keyId] = cmdGroup[0]; - } - } - } - }; - - this.bindKey = function(key, command, position) { - if (typeof key == "object" && key) { - if (position == undefined) - position = key.position; - key = key[this.platform]; - } - if (!key) - return; - if (typeof command == "function") - return this.addCommand({exec: command, bindKey: key, name: command.name || key}); - - key.split("|").forEach(function(keyPart) { - var chain = ""; - if (keyPart.indexOf(" ") != -1) { - var parts = keyPart.split(/\s+/); - keyPart = parts.pop(); - parts.forEach(function(keyPart) { - var binding = this.parseKeys(keyPart); - var id = KEY_MODS[binding.hashId] + binding.key; - chain += (chain ? " " : "") + id; - this._addCommandToBinding(chain, "chainKeys"); - }, this); - chain += " "; - } - var binding = this.parseKeys(keyPart); - var id = KEY_MODS[binding.hashId] + binding.key; - this._addCommandToBinding(chain + id, command, position); - }, this); - }; - - function getPosition(command) { - return typeof command == "object" && command.bindKey - && command.bindKey.position - || (command.isDefault ? -100 : 0); - } - this._addCommandToBinding = function(keyId, command, position) { - var ckb = this.commandKeyBinding, i; - if (!command) { - delete ckb[keyId]; - } else if (!ckb[keyId] || this.$singleCommand) { - ckb[keyId] = command; - } else { - if (!Array.isArray(ckb[keyId])) { - ckb[keyId] = [ckb[keyId]]; - } else if ((i = ckb[keyId].indexOf(command)) != -1) { - ckb[keyId].splice(i, 1); - } - - if (typeof position != "number") { - position = getPosition(command); - } - - var commands = ckb[keyId]; - for (i = 0; i < commands.length; i++) { - var other = commands[i]; - var otherPos = getPosition(other); - if (otherPos > position) - break; - } - commands.splice(i, 0, command); - } - }; - - this.addCommands = function(commands) { - commands && Object.keys(commands).forEach(function(name) { - var command = commands[name]; - if (!command) - return; - - if (typeof command === "string") - return this.bindKey(command, name); - - if (typeof command === "function") - command = { exec: command }; - - if (typeof command !== "object") - return; - - if (!command.name) - command.name = name; - - this.addCommand(command); - }, this); - }; - - this.removeCommands = function(commands) { - Object.keys(commands).forEach(function(name) { - this.removeCommand(commands[name]); - }, this); - }; - - this.bindKeys = function(keyList) { - Object.keys(keyList).forEach(function(key) { - this.bindKey(key, keyList[key]); - }, this); - }; - - this._buildKeyHash = function(command) { - this.bindKey(command.bindKey, command); - }; - this.parseKeys = function(keys) { - var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x;}); - var key = parts.pop(); - - var keyCode = keyUtil[key]; - if (keyUtil.FUNCTION_KEYS[keyCode]) - key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase(); - else if (!parts.length) - return {key: key, hashId: -1}; - else if (parts.length == 1 && parts[0] == "shift") - return {key: key.toUpperCase(), hashId: -1}; - - var hashId = 0; - for (var i = parts.length; i--;) { - var modifier = keyUtil.KEY_MODS[parts[i]]; - if (modifier == null) { - if (typeof console != "undefined") - console.error("invalid modifier " + parts[i] + " in " + keys); - return false; - } - hashId |= modifier; - } - return {key: key, hashId: hashId}; - }; - - this.findKeyCommand = function findKeyCommand(hashId, keyString) { - var key = KEY_MODS[hashId] + keyString; - return this.commandKeyBinding[key]; - }; - - this.handleKeyboard = function(data, hashId, keyString, keyCode) { - if (keyCode < 0) return; - var key = KEY_MODS[hashId] + keyString; - var command = this.commandKeyBinding[key]; - if (data.$keyChain) { - data.$keyChain += " " + key; - command = this.commandKeyBinding[data.$keyChain] || command; - } - - if (command) { - if (command == "chainKeys" || command[command.length - 1] == "chainKeys") { - data.$keyChain = data.$keyChain || key; - return {command: "null"}; - } - } - - if (data.$keyChain) { - if ((!hashId || hashId == 4) && keyString.length == 1) - data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input - else if (hashId == -1 || keyCode > 0) - data.$keyChain = ""; // reset keyChain - } - return {command: command}; - }; - - this.getStatusText = function(editor, data) { - return data.$keyChain || ""; - }; - -}).call(HashHandler.prototype); - -exports.HashHandler = HashHandler; -exports.MultiHashHandler = MultiHashHandler; -}); - -define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var MultiHashHandler = require("../keyboard/hash_handler").MultiHashHandler; -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var CommandManager = function(platform, commands) { - MultiHashHandler.call(this, commands, platform); - this.byName = this.commands; - this.setDefaultHandler("exec", function(e) { - return e.command.exec(e.editor, e.args || {}); - }); -}; - -oop.inherits(CommandManager, MultiHashHandler); - -(function() { - - oop.implement(this, EventEmitter); - - this.exec = function(command, editor, args) { - if (Array.isArray(command)) { - for (var i = command.length; i--; ) { - if (this.exec(command[i], editor, args)) return true; - } - return false; - } - - if (typeof command === "string") - command = this.commands[command]; - - if (!command) - return false; - - if (editor && editor.$readOnly && !command.readOnly) - return false; - - if (this.$checkCommandState != false && command.isAvailable && !command.isAvailable(editor)) - return false; - - var e = {editor: editor, command: command, args: args}; - e.returnValue = this._emit("exec", e); - this._signal("afterExec", e); - - return e.returnValue === false ? false : true; - }; - - this.toggleRecording = function(editor) { - if (this.$inReplay) - return; - - editor && editor._emit("changeStatus"); - if (this.recording) { - this.macro.pop(); - this.off("exec", this.$addCommandToMacro); - - if (!this.macro.length) - this.macro = this.oldMacro; - - return this.recording = false; - } - if (!this.$addCommandToMacro) { - this.$addCommandToMacro = function(e) { - this.macro.push([e.command, e.args]); - }.bind(this); - } - - this.oldMacro = this.macro; - this.macro = []; - this.on("exec", this.$addCommandToMacro); - return this.recording = true; - }; - - this.replay = function(editor) { - if (this.$inReplay || !this.macro) - return; - - if (this.recording) - return this.toggleRecording(editor); - - try { - this.$inReplay = true; - this.macro.forEach(function(x) { - if (typeof x == "string") - this.exec(x, editor); - else - this.exec(x[0], editor, x[1]); - }, this); - } finally { - this.$inReplay = false; - } - }; - - this.trimMacro = function(m) { - return m.map(function(x){ - if (typeof x[0] != "string") - x[0] = x[0].name; - if (!x[1]) - x = x[0]; - return x; - }); - }; - -}).call(CommandManager.prototype); - -exports.CommandManager = CommandManager; - -}); - -define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(require, exports, module) { -"use strict"; - -var lang = require("../lib/lang"); -var config = require("../config"); -var Range = require("../range").Range; - -function bindKey(win, mac) { - return {win: win, mac: mac}; -} -exports.commands = [{ - name: "showSettingsMenu", - description: "Show settings menu", - bindKey: bindKey("Ctrl-,", "Command-,"), - exec: function(editor) { - config.loadModule("ace/ext/settings_menu", function(module) { - module.init(editor); - editor.showSettingsMenu(); - }); - }, - readOnly: true -}, { - name: "goToNextError", - description: "Go to next error", - bindKey: bindKey("Alt-E", "F4"), - exec: function(editor) { - config.loadModule("./ext/error_marker", function(module) { - module.showErrorMarker(editor, 1); - }); - }, - scrollIntoView: "animate", - readOnly: true -}, { - name: "goToPreviousError", - description: "Go to previous error", - bindKey: bindKey("Alt-Shift-E", "Shift-F4"), - exec: function(editor) { - config.loadModule("./ext/error_marker", function(module) { - module.showErrorMarker(editor, -1); - }); - }, - scrollIntoView: "animate", - readOnly: true -}, { - name: "selectall", - description: "Select all", - bindKey: bindKey("Ctrl-A", "Command-A"), - exec: function(editor) { editor.selectAll(); }, - readOnly: true -}, { - name: "centerselection", - description: "Center selection", - bindKey: bindKey(null, "Ctrl-L"), - exec: function(editor) { editor.centerSelection(); }, - readOnly: true -}, { - name: "gotoline", - description: "Go to line...", - bindKey: bindKey("Ctrl-L", "Command-L"), - exec: function(editor, line) { - if (typeof line === "number" && !isNaN(line)) - editor.gotoLine(line); - editor.prompt({ $type: "gotoLine" }); - }, - readOnly: true -}, { - name: "fold", - bindKey: bindKey("Alt-L|Ctrl-F1", "Command-Alt-L|Command-F1"), - exec: function(editor) { editor.session.toggleFold(false); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "unfold", - bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"), - exec: function(editor) { editor.session.toggleFold(true); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "toggleFoldWidget", - description: "Toggle fold widget", - bindKey: bindKey("F2", "F2"), - exec: function(editor) { editor.session.toggleFoldWidget(); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "toggleParentFoldWidget", - description: "Toggle parent fold widget", - bindKey: bindKey("Alt-F2", "Alt-F2"), - exec: function(editor) { editor.session.toggleFoldWidget(true); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "foldall", - description: "Fold all", - bindKey: bindKey(null, "Ctrl-Command-Option-0"), - exec: function(editor) { editor.session.foldAll(); }, - scrollIntoView: "center", - readOnly: true -}, { - name: "foldAllComments", - description: "Fold all comments", - bindKey: bindKey(null, "Ctrl-Command-Option-0"), - exec: function(editor) { editor.session.foldAllComments(); }, - scrollIntoView: "center", - readOnly: true -}, { - name: "foldOther", - description: "Fold other", - bindKey: bindKey("Alt-0", "Command-Option-0"), - exec: function(editor) { - editor.session.foldAll(); - editor.session.unfold(editor.selection.getAllRanges()); - }, - scrollIntoView: "center", - readOnly: true -}, { - name: "unfoldall", - description: "Unfold all", - bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"), - exec: function(editor) { editor.session.unfold(); }, - scrollIntoView: "center", - readOnly: true -}, { - name: "findnext", - description: "Find next", - bindKey: bindKey("Ctrl-K", "Command-G"), - exec: function(editor) { editor.findNext(); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "findprevious", - description: "Find previous", - bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"), - exec: function(editor) { editor.findPrevious(); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "selectOrFindNext", - description: "Select or find next", - bindKey: bindKey("Alt-K", "Ctrl-G"), - exec: function(editor) { - if (editor.selection.isEmpty()) - editor.selection.selectWord(); - else - editor.findNext(); - }, - readOnly: true -}, { - name: "selectOrFindPrevious", - description: "Select or find previous", - bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"), - exec: function(editor) { - if (editor.selection.isEmpty()) - editor.selection.selectWord(); - else - editor.findPrevious(); - }, - readOnly: true -}, { - name: "find", - description: "Find", - bindKey: bindKey("Ctrl-F", "Command-F"), - exec: function(editor) { - config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor);}); - }, - readOnly: true -}, { - name: "overwrite", - description: "Overwrite", - bindKey: "Insert", - exec: function(editor) { editor.toggleOverwrite(); }, - readOnly: true -}, { - name: "selecttostart", - description: "Select to start", - bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Home|Command-Shift-Up"), - exec: function(editor) { editor.getSelection().selectFileStart(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "gotostart", - description: "Go to start", - bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"), - exec: function(editor) { editor.navigateFileStart(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "selectup", - description: "Select up", - bindKey: bindKey("Shift-Up", "Shift-Up|Ctrl-Shift-P"), - exec: function(editor) { editor.getSelection().selectUp(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "golineup", - description: "Go line up", - bindKey: bindKey("Up", "Up|Ctrl-P"), - exec: function(editor, args) { editor.navigateUp(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selecttoend", - description: "Select to end", - bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-End|Command-Shift-Down"), - exec: function(editor) { editor.getSelection().selectFileEnd(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "gotoend", - description: "Go to end", - bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"), - exec: function(editor) { editor.navigateFileEnd(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "selectdown", - description: "Select down", - bindKey: bindKey("Shift-Down", "Shift-Down|Ctrl-Shift-N"), - exec: function(editor) { editor.getSelection().selectDown(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "golinedown", - description: "Go line down", - bindKey: bindKey("Down", "Down|Ctrl-N"), - exec: function(editor, args) { editor.navigateDown(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectwordleft", - description: "Select word left", - bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), - exec: function(editor) { editor.getSelection().selectWordLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotowordleft", - description: "Go to word left", - bindKey: bindKey("Ctrl-Left", "Option-Left"), - exec: function(editor) { editor.navigateWordLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selecttolinestart", - description: "Select to line start", - bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left|Ctrl-Shift-A"), - exec: function(editor) { editor.getSelection().selectLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotolinestart", - description: "Go to line start", - bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), - exec: function(editor) { editor.navigateLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectleft", - description: "Select left", - bindKey: bindKey("Shift-Left", "Shift-Left|Ctrl-Shift-B"), - exec: function(editor) { editor.getSelection().selectLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotoleft", - description: "Go to left", - bindKey: bindKey("Left", "Left|Ctrl-B"), - exec: function(editor, args) { editor.navigateLeft(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectwordright", - description: "Select word right", - bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), - exec: function(editor) { editor.getSelection().selectWordRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotowordright", - description: "Go to word right", - bindKey: bindKey("Ctrl-Right", "Option-Right"), - exec: function(editor) { editor.navigateWordRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selecttolineend", - description: "Select to line end", - bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right|Shift-End|Ctrl-Shift-E"), - exec: function(editor) { editor.getSelection().selectLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotolineend", - description: "Go to line end", - bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), - exec: function(editor) { editor.navigateLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectright", - description: "Select right", - bindKey: bindKey("Shift-Right", "Shift-Right"), - exec: function(editor) { editor.getSelection().selectRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotoright", - description: "Go to right", - bindKey: bindKey("Right", "Right|Ctrl-F"), - exec: function(editor, args) { editor.navigateRight(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectpagedown", - description: "Select page down", - bindKey: "Shift-PageDown", - exec: function(editor) { editor.selectPageDown(); }, - readOnly: true -}, { - name: "pagedown", - description: "Page down", - bindKey: bindKey(null, "Option-PageDown"), - exec: function(editor) { editor.scrollPageDown(); }, - readOnly: true -}, { - name: "gotopagedown", - description: "Go to page down", - bindKey: bindKey("PageDown", "PageDown|Ctrl-V"), - exec: function(editor) { editor.gotoPageDown(); }, - readOnly: true -}, { - name: "selectpageup", - description: "Select page up", - bindKey: "Shift-PageUp", - exec: function(editor) { editor.selectPageUp(); }, - readOnly: true -}, { - name: "pageup", - description: "Page up", - bindKey: bindKey(null, "Option-PageUp"), - exec: function(editor) { editor.scrollPageUp(); }, - readOnly: true -}, { - name: "gotopageup", - description: "Go to page up", - bindKey: "PageUp", - exec: function(editor) { editor.gotoPageUp(); }, - readOnly: true -}, { - name: "scrollup", - description: "Scroll up", - bindKey: bindKey("Ctrl-Up", null), - exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); }, - readOnly: true -}, { - name: "scrolldown", - description: "Scroll down", - bindKey: bindKey("Ctrl-Down", null), - exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); }, - readOnly: true -}, { - name: "selectlinestart", - description: "Select line start", - bindKey: "Shift-Home", - exec: function(editor) { editor.getSelection().selectLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectlineend", - description: "Select line end", - bindKey: "Shift-End", - exec: function(editor) { editor.getSelection().selectLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "togglerecording", - description: "Toggle recording", - bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"), - exec: function(editor) { editor.commands.toggleRecording(editor); }, - readOnly: true -}, { - name: "replaymacro", - description: "Replay macro", - bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"), - exec: function(editor) { editor.commands.replay(editor); }, - readOnly: true -}, { - name: "jumptomatching", - description: "Jump to matching", - bindKey: bindKey("Ctrl-\\|Ctrl-P", "Command-\\"), - exec: function(editor) { editor.jumpToMatching(); }, - multiSelectAction: "forEach", - scrollIntoView: "animate", - readOnly: true -}, { - name: "selecttomatching", - description: "Select to matching", - bindKey: bindKey("Ctrl-Shift-\\|Ctrl-Shift-P", "Command-Shift-\\"), - exec: function(editor) { editor.jumpToMatching(true); }, - multiSelectAction: "forEach", - scrollIntoView: "animate", - readOnly: true -}, { - name: "expandToMatching", - description: "Expand to matching", - bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"), - exec: function(editor) { editor.jumpToMatching(true, true); }, - multiSelectAction: "forEach", - scrollIntoView: "animate", - readOnly: true -}, { - name: "passKeysToBrowser", - description: "Pass keys to browser", - bindKey: bindKey(null, null), - exec: function() {}, - passEvent: true, - readOnly: true -}, { - name: "copy", - description: "Copy", - exec: function(editor) { - }, - readOnly: true -}, -{ - name: "cut", - description: "Cut", - exec: function(editor) { - var cutLine = editor.$copyWithEmptySelection && editor.selection.isEmpty(); - var range = cutLine ? editor.selection.getLineRange() : editor.selection.getRange(); - editor._emit("cut", range); - - if (!range.isEmpty()) - editor.session.remove(range); - editor.clearSelection(); - }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "paste", - description: "Paste", - exec: function(editor, args) { - editor.$handlePaste(args); - }, - scrollIntoView: "cursor" -}, { - name: "removeline", - description: "Remove line", - bindKey: bindKey("Ctrl-D", "Command-D"), - exec: function(editor) { editor.removeLines(); }, - scrollIntoView: "cursor", - multiSelectAction: "forEachLine" -}, { - name: "duplicateSelection", - description: "Duplicate selection", - bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"), - exec: function(editor) { editor.duplicateSelection(); }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "sortlines", - description: "Sort lines", - bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"), - exec: function(editor) { editor.sortLines(); }, - scrollIntoView: "selection", - multiSelectAction: "forEachLine" -}, { - name: "togglecomment", - description: "Toggle comment", - bindKey: bindKey("Ctrl-/", "Command-/"), - exec: function(editor) { editor.toggleCommentLines(); }, - multiSelectAction: "forEachLine", - scrollIntoView: "selectionPart" -}, { - name: "toggleBlockComment", - description: "Toggle block comment", - bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"), - exec: function(editor) { editor.toggleBlockComment(); }, - multiSelectAction: "forEach", - scrollIntoView: "selectionPart" -}, { - name: "modifyNumberUp", - description: "Modify number up", - bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"), - exec: function(editor) { editor.modifyNumber(1); }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "modifyNumberDown", - description: "Modify number down", - bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"), - exec: function(editor) { editor.modifyNumber(-1); }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "replace", - description: "Replace", - bindKey: bindKey("Ctrl-H", "Command-Option-F"), - exec: function(editor) { - config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true);}); - } -}, { - name: "undo", - description: "Undo", - bindKey: bindKey("Ctrl-Z", "Command-Z"), - exec: function(editor) { editor.undo(); } -}, { - name: "redo", - description: "Redo", - bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"), - exec: function(editor) { editor.redo(); } -}, { - name: "copylinesup", - description: "Copy lines up", - bindKey: bindKey("Alt-Shift-Up", "Command-Option-Up"), - exec: function(editor) { editor.copyLinesUp(); }, - scrollIntoView: "cursor" -}, { - name: "movelinesup", - description: "Move lines up", - bindKey: bindKey("Alt-Up", "Option-Up"), - exec: function(editor) { editor.moveLinesUp(); }, - scrollIntoView: "cursor" -}, { - name: "copylinesdown", - description: "Copy lines down", - bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"), - exec: function(editor) { editor.copyLinesDown(); }, - scrollIntoView: "cursor" -}, { - name: "movelinesdown", - description: "Move lines down", - bindKey: bindKey("Alt-Down", "Option-Down"), - exec: function(editor) { editor.moveLinesDown(); }, - scrollIntoView: "cursor" -}, { - name: "del", - description: "Delete", - bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"), - exec: function(editor) { editor.remove("right"); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "backspace", - description: "Backspace", - bindKey: bindKey( - "Shift-Backspace|Backspace", - "Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H" - ), - exec: function(editor) { editor.remove("left"); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "cut_or_delete", - description: "Cut or delete", - bindKey: bindKey("Shift-Delete", null), - exec: function(editor) { - if (editor.selection.isEmpty()) { - editor.remove("left"); - } else { - return false; - } - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolinestart", - description: "Remove to line start", - bindKey: bindKey("Alt-Backspace", "Command-Backspace"), - exec: function(editor) { editor.removeToLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolineend", - description: "Remove to line end", - bindKey: bindKey("Alt-Delete", "Ctrl-K|Command-Delete"), - exec: function(editor) { editor.removeToLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolinestarthard", - description: "Remove to line start hard", - bindKey: bindKey("Ctrl-Shift-Backspace", null), - exec: function(editor) { - var range = editor.selection.getRange(); - range.start.column = 0; - editor.session.remove(range); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolineendhard", - description: "Remove to line end hard", - bindKey: bindKey("Ctrl-Shift-Delete", null), - exec: function(editor) { - var range = editor.selection.getRange(); - range.end.column = Number.MAX_VALUE; - editor.session.remove(range); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removewordleft", - description: "Remove word left", - bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), - exec: function(editor) { editor.removeWordLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removewordright", - description: "Remove word right", - bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), - exec: function(editor) { editor.removeWordRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "outdent", - description: "Outdent", - bindKey: bindKey("Shift-Tab", "Shift-Tab"), - exec: function(editor) { editor.blockOutdent(); }, - multiSelectAction: "forEach", - scrollIntoView: "selectionPart" -}, { - name: "indent", - description: "Indent", - bindKey: bindKey("Tab", "Tab"), - exec: function(editor) { editor.indent(); }, - multiSelectAction: "forEach", - scrollIntoView: "selectionPart" -}, { - name: "blockoutdent", - description: "Block outdent", - bindKey: bindKey("Ctrl-[", "Ctrl-["), - exec: function(editor) { editor.blockOutdent(); }, - multiSelectAction: "forEachLine", - scrollIntoView: "selectionPart" -}, { - name: "blockindent", - description: "Block indent", - bindKey: bindKey("Ctrl-]", "Ctrl-]"), - exec: function(editor) { editor.blockIndent(); }, - multiSelectAction: "forEachLine", - scrollIntoView: "selectionPart" -}, { - name: "insertstring", - description: "Insert string", - exec: function(editor, str) { editor.insert(str); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "inserttext", - description: "Insert text", - exec: function(editor, args) { - editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "splitline", - description: "Split line", - bindKey: bindKey(null, "Ctrl-O"), - exec: function(editor) { editor.splitLine(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "transposeletters", - description: "Transpose letters", - bindKey: bindKey("Alt-Shift-X", "Ctrl-T"), - exec: function(editor) { editor.transposeLetters(); }, - multiSelectAction: function(editor) {editor.transposeSelections(1); }, - scrollIntoView: "cursor" -}, { - name: "touppercase", - description: "To uppercase", - bindKey: bindKey("Ctrl-U", "Ctrl-U"), - exec: function(editor) { editor.toUpperCase(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "tolowercase", - description: "To lowercase", - bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), - exec: function(editor) { editor.toLowerCase(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "autoindent", - description: "Auto Indent", - bindKey: bindKey(null, null), - exec: function(editor) { editor.autoIndent(); }, - multiSelectAction: "forEachLine", - scrollIntoView: "animate" -}, { - name: "expandtoline", - description: "Expand to line", - bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"), - exec: function(editor) { - var range = editor.selection.getRange(); - - range.start.column = range.end.column = 0; - range.end.row++; - editor.selection.setRange(range, false); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "joinlines", - description: "Join lines", - bindKey: bindKey(null, null), - exec: function(editor) { - var isBackwards = editor.selection.isBackwards(); - var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor(); - var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead(); - var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length; - var selectedText = editor.session.doc.getTextRange(editor.selection.getRange()); - var selectedCount = selectedText.replace(/\n\s*/, " ").length; - var insertLine = editor.session.doc.getLine(selectionStart.row); - - for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) { - var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i))); - if (curLine.length !== 0) { - curLine = " " + curLine; - } - insertLine += curLine; - } - - if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) { - insertLine += editor.session.doc.getNewLineCharacter(); - } - - editor.clearSelection(); - editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine); - - if (selectedCount > 0) { - editor.selection.moveCursorTo(selectionStart.row, selectionStart.column); - editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount); - } else { - firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol; - editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol); - } - }, - multiSelectAction: "forEach", - readOnly: true -}, { - name: "invertSelection", - description: "Invert selection", - bindKey: bindKey(null, null), - exec: function(editor) { - var endRow = editor.session.doc.getLength() - 1; - var endCol = editor.session.doc.getLine(endRow).length; - var ranges = editor.selection.rangeList.ranges; - var newRanges = []; - if (ranges.length < 1) { - ranges = [editor.selection.getRange()]; - } - - for (var i = 0; i < ranges.length; i++) { - if (i == (ranges.length - 1)) { - if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) { - newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol)); - } - } - - if (i === 0) { - if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) { - newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column)); - } - } else { - newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column)); - } - } - - editor.exitMultiSelectMode(); - editor.clearSelection(); - - for(var i = 0; i < newRanges.length; i++) { - editor.selection.addRange(newRanges[i], false); - } - }, - readOnly: true, - scrollIntoView: "none" -}, { - name: "addLineAfter", - description: "Add new line after the current line", - exec: function(editor) { - editor.selection.clearSelection(); - editor.navigateLineEnd(); - editor.insert("\n"); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "addLineBefore", - description: "Add new line before the current line", - exec: function(editor) { - editor.selection.clearSelection(); - var cursor = editor.getCursorPosition(); - editor.selection.moveTo(cursor.row - 1, Number.MAX_VALUE); - editor.insert("\n"); - if (cursor.row === 0) editor.navigateUp(); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "openCommandPallete", - description: "Open command pallete", - bindKey: bindKey("F1", "F1"), - exec: function(editor) { - editor.prompt({ $type: "commands" }); - }, - readOnly: true -}, { - name: "modeSelect", - description: "Change language mode...", - bindKey: bindKey(null, null), - exec: function(editor) { - editor.prompt({ $type: "modes" }); - }, - readOnly: true -}]; - -for (var i = 1; i < 9; i++) { - exports.commands.push({ - name: "foldToLevel" + i, - description: "Fold To Level " + i, - level: i, - exec: function(editor) { editor.session.foldToLevel(this.level); }, - scrollIntoView: "center", - readOnly: true - }); -} - -}); - -define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config","ace/token_iterator","ace/clipboard"], function(require, exports, module) { -"use strict"; - -require("./lib/fixoldbrowsers"); - -var oop = require("./lib/oop"); -var dom = require("./lib/dom"); -var lang = require("./lib/lang"); -var useragent = require("./lib/useragent"); -var TextInput = require("./keyboard/textinput").TextInput; -var MouseHandler = require("./mouse/mouse_handler").MouseHandler; -var FoldHandler = require("./mouse/fold_handler").FoldHandler; -var KeyBinding = require("./keyboard/keybinding").KeyBinding; -var EditSession = require("./edit_session").EditSession; -var Search = require("./search").Search; -var Range = require("./range").Range; -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var CommandManager = require("./commands/command_manager").CommandManager; -var defaultCommands = require("./commands/default_commands").commands; -var config = require("./config"); -var TokenIterator = require("./token_iterator").TokenIterator; - -var clipboard = require("./clipboard"); -var Editor = function(renderer, session, options) { - this.$toDestroy = []; - var container = renderer.getContainerElement(); - this.container = container; - this.renderer = renderer; - this.id = "editor" + (++Editor.$uid); - - this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands); - if (typeof document == "object") { - this.textInput = new TextInput(renderer.getTextAreaContainer(), this); - this.renderer.textarea = this.textInput.getElement(); - this.$mouseHandler = new MouseHandler(this); - new FoldHandler(this); - } - - this.keyBinding = new KeyBinding(this); - - this.$search = new Search().set({ - wrap: true - }); - - this.$historyTracker = this.$historyTracker.bind(this); - this.commands.on("exec", this.$historyTracker); - - this.$initOperationListeners(); - - this._$emitInputEvent = lang.delayedCall(function() { - this._signal("input", {}); - if (this.session && this.session.bgTokenizer) - this.session.bgTokenizer.scheduleStart(); - }.bind(this)); - - this.on("change", function(_, _self) { - _self._$emitInputEvent.schedule(31); - }); - - this.setSession(session || options && options.session || new EditSession("")); - config.resetOptions(this); - if (options) - this.setOptions(options); - config._signal("editor", this); -}; - -Editor.$uid = 0; - -(function(){ - - oop.implement(this, EventEmitter); - - this.$initOperationListeners = function() { - this.commands.on("exec", this.startOperation.bind(this), true); - this.commands.on("afterExec", this.endOperation.bind(this), true); - - this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this, true)); - this.on("change", function() { - if (!this.curOp) { - this.startOperation(); - this.curOp.selectionBefore = this.$lastSel; - } - this.curOp.docChanged = true; - }.bind(this), true); - - this.on("changeSelection", function() { - if (!this.curOp) { - this.startOperation(); - this.curOp.selectionBefore = this.$lastSel; - } - this.curOp.selectionChanged = true; - }.bind(this), true); - }; - - this.curOp = null; - this.prevOp = {}; - this.startOperation = function(commandEvent) { - if (this.curOp) { - if (!commandEvent || this.curOp.command) - return; - this.prevOp = this.curOp; - } - if (!commandEvent) { - this.previousCommand = null; - commandEvent = {}; - } - - this.$opResetTimer.schedule(); - this.curOp = this.session.curOp = { - command: commandEvent.command || {}, - args: commandEvent.args, - scrollTop: this.renderer.scrollTop - }; - this.curOp.selectionBefore = this.selection.toJSON(); - }; - - this.endOperation = function(e) { - if (this.curOp && this.session) { - if (e && e.returnValue === false || !this.session) - return (this.curOp = null); - if (e == true && this.curOp.command && this.curOp.command.name == "mouse") - return; - this._signal("beforeEndOperation"); - if (!this.curOp) return; - var command = this.curOp.command; - var scrollIntoView = command && command.scrollIntoView; - if (scrollIntoView) { - switch (scrollIntoView) { - case "center-animate": - scrollIntoView = "animate"; - case "center": - this.renderer.scrollCursorIntoView(null, 0.5); - break; - case "animate": - case "cursor": - this.renderer.scrollCursorIntoView(); - break; - case "selectionPart": - var range = this.selection.getRange(); - var config = this.renderer.layerConfig; - if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) { - this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead); - } - break; - default: - break; - } - if (scrollIntoView == "animate") - this.renderer.animateScrolling(this.curOp.scrollTop); - } - var sel = this.selection.toJSON(); - this.curOp.selectionAfter = sel; - this.$lastSel = this.selection.toJSON(); - this.session.getUndoManager().addSelection(sel); - this.prevOp = this.curOp; - this.curOp = null; - } - }; - this.$mergeableCommands = ["backspace", "del", "insertstring"]; - this.$historyTracker = function(e) { - if (!this.$mergeUndoDeltas) - return; - - var prev = this.prevOp; - var mergeableCommands = this.$mergeableCommands; - var shouldMerge = prev.command && (e.command.name == prev.command.name); - if (e.command.name == "insertstring") { - var text = e.args; - if (this.mergeNextCommand === undefined) - this.mergeNextCommand = true; - - shouldMerge = shouldMerge - && this.mergeNextCommand // previous command allows to coalesce with - && (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type - - this.mergeNextCommand = true; - } else { - shouldMerge = shouldMerge - && mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable - } - - if ( - this.$mergeUndoDeltas != "always" - && Date.now() - this.sequenceStartTime > 2000 - ) { - shouldMerge = false; // the sequence is too long - } - - if (shouldMerge) - this.session.mergeUndoDeltas = true; - else if (mergeableCommands.indexOf(e.command.name) !== -1) - this.sequenceStartTime = Date.now(); - }; - this.setKeyboardHandler = function(keyboardHandler, cb) { - if (keyboardHandler && typeof keyboardHandler === "string" && keyboardHandler != "ace") { - this.$keybindingId = keyboardHandler; - var _self = this; - config.loadModule(["keybinding", keyboardHandler], function(module) { - if (_self.$keybindingId == keyboardHandler) - _self.keyBinding.setKeyboardHandler(module && module.handler); - cb && cb(); - }); - } else { - this.$keybindingId = null; - this.keyBinding.setKeyboardHandler(keyboardHandler); - cb && cb(); - } - }; - this.getKeyboardHandler = function() { - return this.keyBinding.getKeyboardHandler(); - }; - this.setSession = function(session) { - if (this.session == session) - return; - if (this.curOp) this.endOperation(); - this.curOp = {}; - - var oldSession = this.session; - if (oldSession) { - this.session.off("change", this.$onDocumentChange); - this.session.off("changeMode", this.$onChangeMode); - this.session.off("tokenizerUpdate", this.$onTokenizerUpdate); - this.session.off("changeTabSize", this.$onChangeTabSize); - this.session.off("changeWrapLimit", this.$onChangeWrapLimit); - this.session.off("changeWrapMode", this.$onChangeWrapMode); - this.session.off("changeFold", this.$onChangeFold); - this.session.off("changeFrontMarker", this.$onChangeFrontMarker); - this.session.off("changeBackMarker", this.$onChangeBackMarker); - this.session.off("changeBreakpoint", this.$onChangeBreakpoint); - this.session.off("changeAnnotation", this.$onChangeAnnotation); - this.session.off("changeOverwrite", this.$onCursorChange); - this.session.off("changeScrollTop", this.$onScrollTopChange); - this.session.off("changeScrollLeft", this.$onScrollLeftChange); - - var selection = this.session.getSelection(); - selection.off("changeCursor", this.$onCursorChange); - selection.off("changeSelection", this.$onSelectionChange); - } - - this.session = session; - if (session) { - this.$onDocumentChange = this.onDocumentChange.bind(this); - session.on("change", this.$onDocumentChange); - this.renderer.setSession(session); - - this.$onChangeMode = this.onChangeMode.bind(this); - session.on("changeMode", this.$onChangeMode); - - this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this); - session.on("tokenizerUpdate", this.$onTokenizerUpdate); - - this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer); - session.on("changeTabSize", this.$onChangeTabSize); - - this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this); - session.on("changeWrapLimit", this.$onChangeWrapLimit); - - this.$onChangeWrapMode = this.onChangeWrapMode.bind(this); - session.on("changeWrapMode", this.$onChangeWrapMode); - - this.$onChangeFold = this.onChangeFold.bind(this); - session.on("changeFold", this.$onChangeFold); - - this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this); - this.session.on("changeFrontMarker", this.$onChangeFrontMarker); - - this.$onChangeBackMarker = this.onChangeBackMarker.bind(this); - this.session.on("changeBackMarker", this.$onChangeBackMarker); - - this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this); - this.session.on("changeBreakpoint", this.$onChangeBreakpoint); - - this.$onChangeAnnotation = this.onChangeAnnotation.bind(this); - this.session.on("changeAnnotation", this.$onChangeAnnotation); - - this.$onCursorChange = this.onCursorChange.bind(this); - this.session.on("changeOverwrite", this.$onCursorChange); - - this.$onScrollTopChange = this.onScrollTopChange.bind(this); - this.session.on("changeScrollTop", this.$onScrollTopChange); - - this.$onScrollLeftChange = this.onScrollLeftChange.bind(this); - this.session.on("changeScrollLeft", this.$onScrollLeftChange); - - this.selection = session.getSelection(); - this.selection.on("changeCursor", this.$onCursorChange); - - this.$onSelectionChange = this.onSelectionChange.bind(this); - this.selection.on("changeSelection", this.$onSelectionChange); - - this.onChangeMode(); - - this.onCursorChange(); - - this.onScrollTopChange(); - this.onScrollLeftChange(); - this.onSelectionChange(); - this.onChangeFrontMarker(); - this.onChangeBackMarker(); - this.onChangeBreakpoint(); - this.onChangeAnnotation(); - this.session.getUseWrapMode() && this.renderer.adjustWrapLimit(); - this.renderer.updateFull(); - } else { - this.selection = null; - this.renderer.setSession(session); - } - - this._signal("changeSession", { - session: session, - oldSession: oldSession - }); - - this.curOp = null; - - oldSession && oldSession._signal("changeEditor", {oldEditor: this}); - session && session._signal("changeEditor", {editor: this}); - - if (session && session.bgTokenizer) - session.bgTokenizer.scheduleStart(); - }; - this.getSession = function() { - return this.session; - }; - this.setValue = function(val, cursorPos) { - this.session.doc.setValue(val); - - if (!cursorPos) - this.selectAll(); - else if (cursorPos == 1) - this.navigateFileEnd(); - else if (cursorPos == -1) - this.navigateFileStart(); - - return val; - }; - this.getValue = function() { - return this.session.getValue(); - }; - this.getSelection = function() { - return this.selection; - }; - this.resize = function(force) { - this.renderer.onResize(force); - }; - this.setTheme = function(theme, cb) { - this.renderer.setTheme(theme, cb); - }; - this.getTheme = function() { - return this.renderer.getTheme(); - }; - this.setStyle = function(style) { - this.renderer.setStyle(style); - }; - this.unsetStyle = function(style) { - this.renderer.unsetStyle(style); - }; - this.getFontSize = function () { - return this.getOption("fontSize") || - dom.computedStyle(this.container).fontSize; - }; - this.setFontSize = function(size) { - this.setOption("fontSize", size); - }; - - this.$highlightBrackets = function() { - if (this.$highlightPending) { - return; - } - var self = this; - this.$highlightPending = true; - setTimeout(function () { - self.$highlightPending = false; - var session = self.session; - if (!session || !session.bgTokenizer) return; - if (session.$bracketHighlight) { - session.$bracketHighlight.markerIds.forEach(function(id) { - session.removeMarker(id); - }); - session.$bracketHighlight = null; - } - var ranges = session.getMatchingBracketRanges(self.getCursorPosition()); - if (!ranges && session.$mode.getMatching) - ranges = session.$mode.getMatching(self.session); - if (!ranges) - return; - - var markerType = "ace_bracket"; - if (!Array.isArray(ranges)) { - ranges = [ranges]; - } else if (ranges.length == 1) { - markerType = "ace_error_bracket"; - } - if (ranges.length == 2) { - if (Range.comparePoints(ranges[0].end, ranges[1].start) == 0) - ranges = [Range.fromPoints(ranges[0].start, ranges[1].end)]; - else if (Range.comparePoints(ranges[0].start, ranges[1].end) == 0) - ranges = [Range.fromPoints(ranges[1].start, ranges[0].end)]; - } - - session.$bracketHighlight = { - ranges: ranges, - markerIds: ranges.map(function(range) { - return session.addMarker(range, markerType, "text"); - }) - }; - }, 50); - }; - this.$highlightTags = function() { - if (this.$highlightTagPending) - return; - var self = this; - this.$highlightTagPending = true; - setTimeout(function() { - self.$highlightTagPending = false; - - var session = self.session; - if (!session || !session.bgTokenizer) return; - - var pos = self.getCursorPosition(); - var iterator = new TokenIterator(self.session, pos.row, pos.column); - var token = iterator.getCurrentToken(); - - if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) { - session.removeMarker(session.$tagHighlight); - session.$tagHighlight = null; - return; - } - - if (token.type.indexOf("tag-open") !== -1) { - token = iterator.stepForward(); - if (!token) - return; - } - - var tag = token.value; - var currentTag = token.value; - var depth = 0; - var prevToken = iterator.stepBackward(); - - if (prevToken.value === '<'){ - do { - prevToken = token; - token = iterator.stepForward(); - - if (token) { - if (token.type.indexOf('tag-name') !== -1) { - currentTag = token.value; - if (tag === currentTag) { - if (prevToken.value === '<') { - depth++; - } else if (prevToken.value === '') { // self closing tag - depth--; - } - } - - } while (token && depth >= 0); - } else { - do { - token = prevToken; - prevToken = iterator.stepBackward(); - - if (token) { - if (token.type.indexOf('tag-name') !== -1) { - if (tag === token.value) { - if (prevToken.value === '<') { - depth++; - } else if (prevToken.value === '') { // self closing tag - var stepCount = 0; - var tmpToken = prevToken; - while (tmpToken) { - if (tmpToken.type.indexOf('tag-name') !== -1 && tmpToken.value === tag) { - depth--; - break; - } else if (tmpToken.value === '<') { - break; - } - tmpToken = iterator.stepBackward(); - stepCount++; - } - for (var i = 0; i < stepCount; i++) { - iterator.stepForward(); - } - } - } - } while (prevToken && depth <= 0); - iterator.stepForward(); - } - - if (!token) { - session.removeMarker(session.$tagHighlight); - session.$tagHighlight = null; - return; - } - - var row = iterator.getCurrentTokenRow(); - var column = iterator.getCurrentTokenColumn(); - var range = new Range(row, column, row, column+token.value.length); - var sbm = session.$backMarkers[session.$tagHighlight]; - if (session.$tagHighlight && sbm != undefined && range.compareRange(sbm.range) !== 0) { - session.removeMarker(session.$tagHighlight); - session.$tagHighlight = null; - } - - if (!session.$tagHighlight) - session.$tagHighlight = session.addMarker(range, "ace_bracket", "text"); - }, 50); - }; - this.focus = function() { - var _self = this; - setTimeout(function() { - if (!_self.isFocused()) - _self.textInput.focus(); - }); - this.textInput.focus(); - }; - this.isFocused = function() { - return this.textInput.isFocused(); - }; - this.blur = function() { - this.textInput.blur(); - }; - this.onFocus = function(e) { - if (this.$isFocused) - return; - this.$isFocused = true; - this.renderer.showCursor(); - this.renderer.visualizeFocus(); - this._emit("focus", e); - }; - this.onBlur = function(e) { - if (!this.$isFocused) - return; - this.$isFocused = false; - this.renderer.hideCursor(); - this.renderer.visualizeBlur(); - this._emit("blur", e); - }; - - this.$cursorChange = function() { - this.renderer.updateCursor(); - this.$highlightBrackets(); - this.$highlightTags(); - this.$updateHighlightActiveLine(); - }; - this.onDocumentChange = function(delta) { - var wrap = this.session.$useWrapMode; - var lastRow = (delta.start.row == delta.end.row ? delta.end.row : Infinity); - this.renderer.updateLines(delta.start.row, lastRow, wrap); - - this._signal("change", delta); - this.$cursorChange(); - }; - - this.onTokenizerUpdate = function(e) { - var rows = e.data; - this.renderer.updateLines(rows.first, rows.last); - }; - - - this.onScrollTopChange = function() { - this.renderer.scrollToY(this.session.getScrollTop()); - }; - - this.onScrollLeftChange = function() { - this.renderer.scrollToX(this.session.getScrollLeft()); - }; - this.onCursorChange = function() { - this.$cursorChange(); - this._signal("changeSelection"); - }; - - this.$updateHighlightActiveLine = function() { - var session = this.getSession(); - - var highlight; - if (this.$highlightActiveLine) { - if (this.$selectionStyle != "line" || !this.selection.isMultiLine()) - highlight = this.getCursorPosition(); - if (this.renderer.theme && this.renderer.theme.$selectionColorConflict && !this.selection.isEmpty()) - highlight = false; - if (this.renderer.$maxLines && this.session.getLength() === 1 && !(this.renderer.$minLines > 1)) - highlight = false; - } - - if (session.$highlightLineMarker && !highlight) { - session.removeMarker(session.$highlightLineMarker.id); - session.$highlightLineMarker = null; - } else if (!session.$highlightLineMarker && highlight) { - var range = new Range(highlight.row, highlight.column, highlight.row, Infinity); - range.id = session.addMarker(range, "ace_active-line", "screenLine"); - session.$highlightLineMarker = range; - } else if (highlight) { - session.$highlightLineMarker.start.row = highlight.row; - session.$highlightLineMarker.end.row = highlight.row; - session.$highlightLineMarker.start.column = highlight.column; - session._signal("changeBackMarker"); - } - }; - - this.onSelectionChange = function(e) { - var session = this.session; - - if (session.$selectionMarker) { - session.removeMarker(session.$selectionMarker); - } - session.$selectionMarker = null; - - if (!this.selection.isEmpty()) { - var range = this.selection.getRange(); - var style = this.getSelectionStyle(); - session.$selectionMarker = session.addMarker(range, "ace_selection", style); - } else { - this.$updateHighlightActiveLine(); - } - - var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp(); - this.session.highlight(re); - - this._signal("changeSelection"); - }; - - this.$getSelectionHighLightRegexp = function() { - var session = this.session; - - var selection = this.getSelectionRange(); - if (selection.isEmpty() || selection.isMultiLine()) - return; - - var startColumn = selection.start.column; - var endColumn = selection.end.column; - var line = session.getLine(selection.start.row); - - var needle = line.substring(startColumn, endColumn); - if (needle.length > 5000 || !/[\w\d]/.test(needle)) - return; - - var re = this.$search.$assembleRegExp({ - wholeWord: true, - caseSensitive: true, - needle: needle - }); - - var wordWithBoundary = line.substring(startColumn - 1, endColumn + 1); - if (!re.test(wordWithBoundary)) - return; - - return re; - }; - - - this.onChangeFrontMarker = function() { - this.renderer.updateFrontMarkers(); - }; - - this.onChangeBackMarker = function() { - this.renderer.updateBackMarkers(); - }; - - - this.onChangeBreakpoint = function() { - this.renderer.updateBreakpoints(); - }; - - this.onChangeAnnotation = function() { - this.renderer.setAnnotations(this.session.getAnnotations()); - }; - - - this.onChangeMode = function(e) { - this.renderer.updateText(); - this._emit("changeMode", e); - }; - - - this.onChangeWrapLimit = function() { - this.renderer.updateFull(); - }; - - this.onChangeWrapMode = function() { - this.renderer.onResize(true); - }; - - - this.onChangeFold = function() { - this.$updateHighlightActiveLine(); - this.renderer.updateFull(); - }; - this.getSelectedText = function() { - return this.session.getTextRange(this.getSelectionRange()); - }; - this.getCopyText = function() { - var text = this.getSelectedText(); - var nl = this.session.doc.getNewLineCharacter(); - var copyLine= false; - if (!text && this.$copyWithEmptySelection) { - copyLine = true; - var ranges = this.selection.getAllRanges(); - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (i && ranges[i - 1].start.row == range.start.row) - continue; - text += this.session.getLine(range.start.row) + nl; - } - } - var e = {text: text}; - this._signal("copy", e); - clipboard.lineMode = copyLine ? e.text : false; - return e.text; - }; - this.onCopy = function() { - this.commands.exec("copy", this); - }; - this.onCut = function() { - this.commands.exec("cut", this); - }; - this.onPaste = function(text, event) { - var e = {text: text, event: event}; - this.commands.exec("paste", this, e); - }; - - this.$handlePaste = function(e) { - if (typeof e == "string") - e = {text: e}; - this._signal("paste", e); - var text = e.text; - - var lineMode = text === clipboard.lineMode; - var session = this.session; - if (!this.inMultiSelectMode || this.inVirtualSelectionMode) { - if (lineMode) - session.insert({ row: this.selection.lead.row, column: 0 }, text); - else - this.insert(text); - } else if (lineMode) { - this.selection.rangeList.ranges.forEach(function(range) { - session.insert({ row: range.start.row, column: 0 }, text); - }); - } else { - var lines = text.split(/\r\n|\r|\n/); - var ranges = this.selection.rangeList.ranges; - - var isFullLine = lines.length == 2 && (!lines[0] || !lines[1]); - if (lines.length != ranges.length || isFullLine) - return this.commands.exec("insertstring", this, text); - - for (var i = ranges.length; i--;) { - var range = ranges[i]; - if (!range.isEmpty()) - session.remove(range); - - session.insert(range.start, lines[i]); - } - } - }; - - this.execCommand = function(command, args) { - return this.commands.exec(command, this, args); - }; - this.insert = function(text, pasted) { - var session = this.session; - var mode = session.getMode(); - var cursor = this.getCursorPosition(); - - if (this.getBehavioursEnabled() && !pasted) { - var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text); - if (transform) { - if (text !== transform.text) { - if (!this.inVirtualSelectionMode) { - this.session.mergeUndoDeltas = false; - this.mergeNextCommand = false; - } - } - text = transform.text; - - } - } - - if (text == "\t") - text = this.session.getTabString(); - if (!this.selection.isEmpty()) { - var range = this.getSelectionRange(); - cursor = this.session.remove(range); - this.clearSelection(); - } - else if (this.session.getOverwrite() && text.indexOf("\n") == -1) { - var range = new Range.fromPoints(cursor, cursor); - range.end.column += text.length; - this.session.remove(range); - } - - if (text == "\n" || text == "\r\n") { - var line = session.getLine(cursor.row); - if (cursor.column > line.search(/\S|$/)) { - var d = line.substr(cursor.column).search(/\S|$/); - session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d); - } - } - this.clearSelection(); - - var start = cursor.column; - var lineState = session.getState(cursor.row); - var line = session.getLine(cursor.row); - var shouldOutdent = mode.checkOutdent(lineState, line, text); - session.insert(cursor, text); - - if (transform && transform.selection) { - if (transform.selection.length == 2) { // Transform relative to the current column - this.selection.setSelectionRange( - new Range(cursor.row, start + transform.selection[0], - cursor.row, start + transform.selection[1])); - } else { // Transform relative to the current row. - this.selection.setSelectionRange( - new Range(cursor.row + transform.selection[0], - transform.selection[1], - cursor.row + transform.selection[2], - transform.selection[3])); - } - } - if (this.$enableAutoIndent) { - if (session.getDocument().isNewLine(text)) { - var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString()); - - session.insert({row: cursor.row+1, column: 0}, lineIndent); - } - if (shouldOutdent) - mode.autoOutdent(lineState, session, cursor.row); - } - }; - - this.autoIndent = function () { - var session = this.session; - var mode = session.getMode(); - - var startRow, endRow; - if (this.selection.isEmpty()) { - startRow = 0; - endRow = session.doc.getLength() - 1; - } else { - var selectedRange = this.getSelectionRange(); - - startRow = selectedRange.start.row; - endRow = selectedRange.end.row; - } - - var prevLineState = ""; - var prevLine = ""; - var lineIndent = ""; - var line, currIndent, range; - var tab = session.getTabString(); - - for (var row = startRow; row <= endRow; row++) { - if (row > 0) { - prevLineState = session.getState(row - 1); - prevLine = session.getLine(row - 1); - lineIndent = mode.getNextLineIndent(prevLineState, prevLine, tab); - } - - line = session.getLine(row); - currIndent = mode.$getIndent(line); - if (lineIndent !== currIndent) { - if (currIndent.length > 0) { - range = new Range(row, 0, row, currIndent.length); - session.remove(range); - } - if (lineIndent.length > 0) { - session.insert({row: row, column: 0}, lineIndent); - } - } - - mode.autoOutdent(prevLineState, session, row); - } - }; - - - this.onTextInput = function(text, composition) { - if (!composition) - return this.keyBinding.onTextInput(text); - - this.startOperation({command: { name: "insertstring" }}); - var applyComposition = this.applyComposition.bind(this, text, composition); - if (this.selection.rangeCount) - this.forEachSelection(applyComposition); - else - applyComposition(); - this.endOperation(); - }; - - this.applyComposition = function(text, composition) { - if (composition.extendLeft || composition.extendRight) { - var r = this.selection.getRange(); - r.start.column -= composition.extendLeft; - r.end.column += composition.extendRight; - if (r.start.column < 0) { - r.start.row--; - r.start.column += this.session.getLine(r.start.row).length + 1; - } - this.selection.setRange(r); - if (!text && !r.isEmpty()) - this.remove(); - } - if (text || !this.selection.isEmpty()) - this.insert(text, true); - if (composition.restoreStart || composition.restoreEnd) { - var r = this.selection.getRange(); - r.start.column -= composition.restoreStart; - r.end.column -= composition.restoreEnd; - this.selection.setRange(r); - } - }; - - this.onCommandKey = function(e, hashId, keyCode) { - return this.keyBinding.onCommandKey(e, hashId, keyCode); - }; - this.setOverwrite = function(overwrite) { - this.session.setOverwrite(overwrite); - }; - this.getOverwrite = function() { - return this.session.getOverwrite(); - }; - this.toggleOverwrite = function() { - this.session.toggleOverwrite(); - }; - this.setScrollSpeed = function(speed) { - this.setOption("scrollSpeed", speed); - }; - this.getScrollSpeed = function() { - return this.getOption("scrollSpeed"); - }; - this.setDragDelay = function(dragDelay) { - this.setOption("dragDelay", dragDelay); - }; - this.getDragDelay = function() { - return this.getOption("dragDelay"); - }; - this.setSelectionStyle = function(val) { - this.setOption("selectionStyle", val); - }; - this.getSelectionStyle = function() { - return this.getOption("selectionStyle"); - }; - this.setHighlightActiveLine = function(shouldHighlight) { - this.setOption("highlightActiveLine", shouldHighlight); - }; - this.getHighlightActiveLine = function() { - return this.getOption("highlightActiveLine"); - }; - this.setHighlightGutterLine = function(shouldHighlight) { - this.setOption("highlightGutterLine", shouldHighlight); - }; - - this.getHighlightGutterLine = function() { - return this.getOption("highlightGutterLine"); - }; - this.setHighlightSelectedWord = function(shouldHighlight) { - this.setOption("highlightSelectedWord", shouldHighlight); - }; - this.getHighlightSelectedWord = function() { - return this.$highlightSelectedWord; - }; - - this.setAnimatedScroll = function(shouldAnimate){ - this.renderer.setAnimatedScroll(shouldAnimate); - }; - - this.getAnimatedScroll = function(){ - return this.renderer.getAnimatedScroll(); - }; - this.setShowInvisibles = function(showInvisibles) { - this.renderer.setShowInvisibles(showInvisibles); - }; - this.getShowInvisibles = function() { - return this.renderer.getShowInvisibles(); - }; - - this.setDisplayIndentGuides = function(display) { - this.renderer.setDisplayIndentGuides(display); - }; - - this.getDisplayIndentGuides = function() { - return this.renderer.getDisplayIndentGuides(); - }; - this.setShowPrintMargin = function(showPrintMargin) { - this.renderer.setShowPrintMargin(showPrintMargin); - }; - this.getShowPrintMargin = function() { - return this.renderer.getShowPrintMargin(); - }; - this.setPrintMarginColumn = function(showPrintMargin) { - this.renderer.setPrintMarginColumn(showPrintMargin); - }; - this.getPrintMarginColumn = function() { - return this.renderer.getPrintMarginColumn(); - }; - this.setReadOnly = function(readOnly) { - this.setOption("readOnly", readOnly); - }; - this.getReadOnly = function() { - return this.getOption("readOnly"); - }; - this.setBehavioursEnabled = function (enabled) { - this.setOption("behavioursEnabled", enabled); - }; - this.getBehavioursEnabled = function () { - return this.getOption("behavioursEnabled"); - }; - this.setWrapBehavioursEnabled = function (enabled) { - this.setOption("wrapBehavioursEnabled", enabled); - }; - this.getWrapBehavioursEnabled = function () { - return this.getOption("wrapBehavioursEnabled"); - }; - this.setShowFoldWidgets = function(show) { - this.setOption("showFoldWidgets", show); - - }; - this.getShowFoldWidgets = function() { - return this.getOption("showFoldWidgets"); - }; - - this.setFadeFoldWidgets = function(fade) { - this.setOption("fadeFoldWidgets", fade); - }; - - this.getFadeFoldWidgets = function() { - return this.getOption("fadeFoldWidgets"); - }; - this.remove = function(dir) { - if (this.selection.isEmpty()){ - if (dir == "left") - this.selection.selectLeft(); - else - this.selection.selectRight(); - } - - var range = this.getSelectionRange(); - if (this.getBehavioursEnabled()) { - var session = this.session; - var state = session.getState(range.start.row); - var new_range = session.getMode().transformAction(state, 'deletion', this, session, range); - - if (range.end.column === 0) { - var text = session.getTextRange(range); - if (text[text.length - 1] == "\n") { - var line = session.getLine(range.end.row); - if (/^\s+$/.test(line)) { - range.end.column = line.length; - } - } - } - if (new_range) - range = new_range; - } - - this.session.remove(range); - this.clearSelection(); - }; - this.removeWordRight = function() { - if (this.selection.isEmpty()) - this.selection.selectWordRight(); - - this.session.remove(this.getSelectionRange()); - this.clearSelection(); - }; - this.removeWordLeft = function() { - if (this.selection.isEmpty()) - this.selection.selectWordLeft(); - - this.session.remove(this.getSelectionRange()); - this.clearSelection(); - }; - this.removeToLineStart = function() { - if (this.selection.isEmpty()) - this.selection.selectLineStart(); - if (this.selection.isEmpty()) - this.selection.selectLeft(); - this.session.remove(this.getSelectionRange()); - this.clearSelection(); - }; - this.removeToLineEnd = function() { - if (this.selection.isEmpty()) - this.selection.selectLineEnd(); - - var range = this.getSelectionRange(); - if (range.start.column == range.end.column && range.start.row == range.end.row) { - range.end.column = 0; - range.end.row++; - } - - this.session.remove(range); - this.clearSelection(); - }; - this.splitLine = function() { - if (!this.selection.isEmpty()) { - this.session.remove(this.getSelectionRange()); - this.clearSelection(); - } - - var cursor = this.getCursorPosition(); - this.insert("\n"); - this.moveCursorToPosition(cursor); - }; - this.transposeLetters = function() { - if (!this.selection.isEmpty()) { - return; - } - - var cursor = this.getCursorPosition(); - var column = cursor.column; - if (column === 0) - return; - - var line = this.session.getLine(cursor.row); - var swap, range; - if (column < line.length) { - swap = line.charAt(column) + line.charAt(column-1); - range = new Range(cursor.row, column-1, cursor.row, column+1); - } - else { - swap = line.charAt(column-1) + line.charAt(column-2); - range = new Range(cursor.row, column-2, cursor.row, column); - } - this.session.replace(range, swap); - this.session.selection.moveToPosition(range.end); - }; - this.toLowerCase = function() { - var originalRange = this.getSelectionRange(); - if (this.selection.isEmpty()) { - this.selection.selectWord(); - } - - var range = this.getSelectionRange(); - var text = this.session.getTextRange(range); - this.session.replace(range, text.toLowerCase()); - this.selection.setSelectionRange(originalRange); - }; - this.toUpperCase = function() { - var originalRange = this.getSelectionRange(); - if (this.selection.isEmpty()) { - this.selection.selectWord(); - } - - var range = this.getSelectionRange(); - var text = this.session.getTextRange(range); - this.session.replace(range, text.toUpperCase()); - this.selection.setSelectionRange(originalRange); - }; - this.indent = function() { - var session = this.session; - var range = this.getSelectionRange(); - - if (range.start.row < range.end.row) { - var rows = this.$getSelectedRows(); - session.indentRows(rows.first, rows.last, "\t"); - return; - } else if (range.start.column < range.end.column) { - var text = session.getTextRange(range); - if (!/^\s+$/.test(text)) { - var rows = this.$getSelectedRows(); - session.indentRows(rows.first, rows.last, "\t"); - return; - } - } - - var line = session.getLine(range.start.row); - var position = range.start; - var size = session.getTabSize(); - var column = session.documentToScreenColumn(position.row, position.column); - - if (this.session.getUseSoftTabs()) { - var count = (size - column % size); - var indentString = lang.stringRepeat(" ", count); - } else { - var count = column % size; - while (line[range.start.column - 1] == " " && count) { - range.start.column--; - count--; - } - this.selection.setSelectionRange(range); - indentString = "\t"; - } - return this.insert(indentString); - }; - this.blockIndent = function() { - var rows = this.$getSelectedRows(); - this.session.indentRows(rows.first, rows.last, "\t"); - }; - this.blockOutdent = function() { - var selection = this.session.getSelection(); - this.session.outdentRows(selection.getRange()); - }; - this.sortLines = function() { - var rows = this.$getSelectedRows(); - var session = this.session; - - var lines = []; - for (var i = rows.first; i <= rows.last; i++) - lines.push(session.getLine(i)); - - lines.sort(function(a, b) { - if (a.toLowerCase() < b.toLowerCase()) return -1; - if (a.toLowerCase() > b.toLowerCase()) return 1; - return 0; - }); - - var deleteRange = new Range(0, 0, 0, 0); - for (var i = rows.first; i <= rows.last; i++) { - var line = session.getLine(i); - deleteRange.start.row = i; - deleteRange.end.row = i; - deleteRange.end.column = line.length; - session.replace(deleteRange, lines[i-rows.first]); - } - }; - this.toggleCommentLines = function() { - var state = this.session.getState(this.getCursorPosition().row); - var rows = this.$getSelectedRows(); - this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last); - }; - - this.toggleBlockComment = function() { - var cursor = this.getCursorPosition(); - var state = this.session.getState(cursor.row); - var range = this.getSelectionRange(); - this.session.getMode().toggleBlockComment(state, this.session, range, cursor); - }; - this.getNumberAt = function(row, column) { - var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g; - _numberRx.lastIndex = 0; - - var s = this.session.getLine(row); - while (_numberRx.lastIndex < column) { - var m = _numberRx.exec(s); - if(m.index <= column && m.index+m[0].length >= column){ - var number = { - value: m[0], - start: m.index, - end: m.index+m[0].length - }; - return number; - } - } - return null; - }; - this.modifyNumber = function(amount) { - var row = this.selection.getCursor().row; - var column = this.selection.getCursor().column; - var charRange = new Range(row, column-1, row, column); - - var c = this.session.getTextRange(charRange); - if (!isNaN(parseFloat(c)) && isFinite(c)) { - var nr = this.getNumberAt(row, column); - if (nr) { - var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end; - var decimals = nr.start + nr.value.length - fp; - - var t = parseFloat(nr.value); - t *= Math.pow(10, decimals); - - - if(fp !== nr.end && column < fp){ - amount *= Math.pow(10, nr.end - column - 1); - } else { - amount *= Math.pow(10, nr.end - column); - } - - t += amount; - t /= Math.pow(10, decimals); - var nnr = t.toFixed(decimals); - var replaceRange = new Range(row, nr.start, row, nr.end); - this.session.replace(replaceRange, nnr); - this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length)); - - } - } else { - this.toggleWord(); - } - }; - - this.$toggleWordPairs = [ - ["first", "last"], - ["true", "false"], - ["yes", "no"], - ["width", "height"], - ["top", "bottom"], - ["right", "left"], - ["on", "off"], - ["x", "y"], - ["get", "set"], - ["max", "min"], - ["horizontal", "vertical"], - ["show", "hide"], - ["add", "remove"], - ["up", "down"], - ["before", "after"], - ["even", "odd"], - ["in", "out"], - ["inside", "outside"], - ["next", "previous"], - ["increase", "decrease"], - ["attach", "detach"], - ["&&", "||"], - ["==", "!="] - ]; - - this.toggleWord = function () { - var row = this.selection.getCursor().row; - var column = this.selection.getCursor().column; - this.selection.selectWord(); - var currentState = this.getSelectedText(); - var currWordStart = this.selection.getWordRange().start.column; - var wordParts = currentState.replace(/([a-z]+|[A-Z]+)(?=[A-Z_]|$)/g, '$1 ').split(/\s/); - var delta = column - currWordStart - 1; - if (delta < 0) delta = 0; - var curLength = 0, itLength = 0; - var that = this; - if (currentState.match(/[A-Za-z0-9_]+/)) { - wordParts.forEach(function (item, i) { - itLength = curLength + item.length; - if (delta >= curLength && delta <= itLength) { - currentState = item; - that.selection.clearSelection(); - that.moveCursorTo(row, curLength + currWordStart); - that.selection.selectTo(row, itLength + currWordStart); - } - curLength = itLength; - }); - } - - var wordPairs = this.$toggleWordPairs; - var reg; - for (var i = 0; i < wordPairs.length; i++) { - var item = wordPairs[i]; - for (var j = 0; j <= 1; j++) { - var negate = +!j; - var firstCondition = currentState.match(new RegExp('^\\s?_?(' + lang.escapeRegExp(item[j]) + ')\\s?$', 'i')); - if (firstCondition) { - var secondCondition = currentState.match(new RegExp('([_]|^|\\s)(' + lang.escapeRegExp(firstCondition[1]) + ')($|\\s)', 'g')); - if (secondCondition) { - reg = currentState.replace(new RegExp(lang.escapeRegExp(item[j]), 'i'), function (result) { - var res = item[negate]; - if (result.toUpperCase() == result) { - res = res.toUpperCase(); - } else if (result.charAt(0).toUpperCase() == result.charAt(0)) { - res = res.substr(0, 0) + item[negate].charAt(0).toUpperCase() + res.substr(1); - } - return res; - }); - this.insert(reg); - reg = ""; - } - } - } - } - }; - this.removeLines = function() { - var rows = this.$getSelectedRows(); - this.session.removeFullLines(rows.first, rows.last); - this.clearSelection(); - }; - - this.duplicateSelection = function() { - var sel = this.selection; - var doc = this.session; - var range = sel.getRange(); - var reverse = sel.isBackwards(); - if (range.isEmpty()) { - var row = range.start.row; - doc.duplicateLines(row, row); - } else { - var point = reverse ? range.start : range.end; - var endPoint = doc.insert(point, doc.getTextRange(range), false); - range.start = point; - range.end = endPoint; - - sel.setSelectionRange(range, reverse); - } - }; - this.moveLinesDown = function() { - this.$moveLines(1, false); - }; - this.moveLinesUp = function() { - this.$moveLines(-1, false); - }; - this.moveText = function(range, toPosition, copy) { - return this.session.moveText(range, toPosition, copy); - }; - this.copyLinesUp = function() { - this.$moveLines(-1, true); - }; - this.copyLinesDown = function() { - this.$moveLines(1, true); - }; - this.$moveLines = function(dir, copy) { - var rows, moved; - var selection = this.selection; - if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) { - var range = selection.toOrientedRange(); - rows = this.$getSelectedRows(range); - moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir); - if (copy && dir == -1) moved = 0; - range.moveBy(moved, 0); - selection.fromOrientedRange(range); - } else { - var ranges = selection.rangeList.ranges; - selection.rangeList.detach(this.session); - this.inVirtualSelectionMode = true; - - var diff = 0; - var totalDiff = 0; - var l = ranges.length; - for (var i = 0; i < l; i++) { - var rangeIndex = i; - ranges[i].moveBy(diff, 0); - rows = this.$getSelectedRows(ranges[i]); - var first = rows.first; - var last = rows.last; - while (++i < l) { - if (totalDiff) ranges[i].moveBy(totalDiff, 0); - var subRows = this.$getSelectedRows(ranges[i]); - if (copy && subRows.first != last) - break; - else if (!copy && subRows.first > last + 1) - break; - last = subRows.last; - } - i--; - diff = this.session.$moveLines(first, last, copy ? 0 : dir); - if (copy && dir == -1) rangeIndex = i + 1; - while (rangeIndex <= i) { - ranges[rangeIndex].moveBy(diff, 0); - rangeIndex++; - } - if (!copy) diff = 0; - totalDiff += diff; - } - - selection.fromOrientedRange(selection.ranges[0]); - selection.rangeList.attach(this.session); - this.inVirtualSelectionMode = false; - } - }; - this.$getSelectedRows = function(range) { - range = (range || this.getSelectionRange()).collapseRows(); - - return { - first: this.session.getRowFoldStart(range.start.row), - last: this.session.getRowFoldEnd(range.end.row) - }; - }; - - this.onCompositionStart = function(compositionState) { - this.renderer.showComposition(compositionState); - }; - - this.onCompositionUpdate = function(text) { - this.renderer.setCompositionText(text); - }; - - this.onCompositionEnd = function() { - this.renderer.hideComposition(); - }; - this.getFirstVisibleRow = function() { - return this.renderer.getFirstVisibleRow(); - }; - this.getLastVisibleRow = function() { - return this.renderer.getLastVisibleRow(); - }; - this.isRowVisible = function(row) { - return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow()); - }; - this.isRowFullyVisible = function(row) { - return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow()); - }; - this.$getVisibleRowCount = function() { - return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1; - }; - - this.$moveByPage = function(dir, select) { - var renderer = this.renderer; - var config = this.renderer.layerConfig; - var rows = dir * Math.floor(config.height / config.lineHeight); - - if (select === true) { - this.selection.$moveSelection(function(){ - this.moveCursorBy(rows, 0); - }); - } else if (select === false) { - this.selection.moveCursorBy(rows, 0); - this.selection.clearSelection(); - } - - var scrollTop = renderer.scrollTop; - - renderer.scrollBy(0, rows * config.lineHeight); - if (select != null) - renderer.scrollCursorIntoView(null, 0.5); - - renderer.animateScrolling(scrollTop); - }; - this.selectPageDown = function() { - this.$moveByPage(1, true); - }; - this.selectPageUp = function() { - this.$moveByPage(-1, true); - }; - this.gotoPageDown = function() { - this.$moveByPage(1, false); - }; - this.gotoPageUp = function() { - this.$moveByPage(-1, false); - }; - this.scrollPageDown = function() { - this.$moveByPage(1); - }; - this.scrollPageUp = function() { - this.$moveByPage(-1); - }; - this.scrollToRow = function(row) { - this.renderer.scrollToRow(row); - }; - this.scrollToLine = function(line, center, animate, callback) { - this.renderer.scrollToLine(line, center, animate, callback); - }; - this.centerSelection = function() { - var range = this.getSelectionRange(); - var pos = { - row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2), - column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2) - }; - this.renderer.alignCursor(pos, 0.5); - }; - this.getCursorPosition = function() { - return this.selection.getCursor(); - }; - this.getCursorPositionScreen = function() { - return this.session.documentToScreenPosition(this.getCursorPosition()); - }; - this.getSelectionRange = function() { - return this.selection.getRange(); - }; - this.selectAll = function() { - this.selection.selectAll(); - }; - this.clearSelection = function() { - this.selection.clearSelection(); - }; - this.moveCursorTo = function(row, column) { - this.selection.moveCursorTo(row, column); - }; - this.moveCursorToPosition = function(pos) { - this.selection.moveCursorToPosition(pos); - }; - this.jumpToMatching = function(select, expand) { - var cursor = this.getCursorPosition(); - var iterator = new TokenIterator(this.session, cursor.row, cursor.column); - var prevToken = iterator.getCurrentToken(); - var token = prevToken || iterator.stepForward(); - - if (!token) return; - var matchType; - var found = false; - var depth = {}; - var i = cursor.column - token.start; - var bracketType; - var brackets = { - ")": "(", - "(": "(", - "]": "[", - "[": "[", - "{": "{", - "}": "{" - }; - - do { - if (token.value.match(/[{}()\[\]]/g)) { - for (; i < token.value.length && !found; i++) { - if (!brackets[token.value[i]]) { - continue; - } - - bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen"); - - if (isNaN(depth[bracketType])) { - depth[bracketType] = 0; - } - - switch (token.value[i]) { - case '(': - case '[': - case '{': - depth[bracketType]++; - break; - case ')': - case ']': - case '}': - depth[bracketType]--; - - if (depth[bracketType] === -1) { - matchType = 'bracket'; - found = true; - } - break; - } - } - } - else if (token.type.indexOf('tag-name') !== -1) { - if (isNaN(depth[token.value])) { - depth[token.value] = 0; - } - - if (prevToken.value === '<') { - depth[token.value]++; - } - else if (prevToken.value === '= 0; --i) { - if(this.$tryReplace(ranges[i], replacement)) { - replaced++; - } - } - - this.selection.setSelectionRange(selection); - - return replaced; - }; - - this.$tryReplace = function(range, replacement) { - var input = this.session.getTextRange(range); - replacement = this.$search.replace(input, replacement); - if (replacement !== null) { - range.end = this.session.replace(range, replacement); - return range; - } else { - return null; - } - }; - this.getLastSearchOptions = function() { - return this.$search.getOptions(); - }; - this.find = function(needle, options, animate) { - if (!options) - options = {}; - - if (typeof needle == "string" || needle instanceof RegExp) - options.needle = needle; - else if (typeof needle == "object") - oop.mixin(options, needle); - - var range = this.selection.getRange(); - if (options.needle == null) { - needle = this.session.getTextRange(range) - || this.$search.$options.needle; - if (!needle) { - range = this.session.getWordRange(range.start.row, range.start.column); - needle = this.session.getTextRange(range); - } - this.$search.set({needle: needle}); - } - - this.$search.set(options); - if (!options.start) - this.$search.set({start: range}); - - var newRange = this.$search.find(this.session); - if (options.preventScroll) - return newRange; - if (newRange) { - this.revealRange(newRange, animate); - return newRange; - } - if (options.backwards) - range.start = range.end; - else - range.end = range.start; - this.selection.setRange(range); - }; - this.findNext = function(options, animate) { - this.find({skipCurrent: true, backwards: false}, options, animate); - }; - this.findPrevious = function(options, animate) { - this.find(options, {skipCurrent: true, backwards: true}, animate); - }; - - this.revealRange = function(range, animate) { - this.session.unfold(range); - this.selection.setSelectionRange(range); - - var scrollTop = this.renderer.scrollTop; - this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5); - if (animate !== false) - this.renderer.animateScrolling(scrollTop); - }; - this.undo = function() { - this.session.getUndoManager().undo(this.session); - this.renderer.scrollCursorIntoView(null, 0.5); - }; - this.redo = function() { - this.session.getUndoManager().redo(this.session); - this.renderer.scrollCursorIntoView(null, 0.5); - }; - this.destroy = function() { - if (this.$toDestroy) { - this.$toDestroy.forEach(function(el) { - el.destroy(); - }); - this.$toDestroy = null; - } - if (this.$mouseHandler) - this.$mouseHandler.destroy(); - this.renderer.destroy(); - this._signal("destroy", this); - if (this.session) - this.session.destroy(); - if (this._$emitInputEvent) - this._$emitInputEvent.cancel(); - this.removeAllListeners(); - }; - this.setAutoScrollEditorIntoView = function(enable) { - if (!enable) - return; - var rect; - var self = this; - var shouldScroll = false; - if (!this.$scrollAnchor) - this.$scrollAnchor = document.createElement("div"); - var scrollAnchor = this.$scrollAnchor; - scrollAnchor.style.cssText = "position:absolute"; - this.container.insertBefore(scrollAnchor, this.container.firstChild); - var onChangeSelection = this.on("changeSelection", function() { - shouldScroll = true; - }); - var onBeforeRender = this.renderer.on("beforeRender", function() { - if (shouldScroll) - rect = self.renderer.container.getBoundingClientRect(); - }); - var onAfterRender = this.renderer.on("afterRender", function() { - if (shouldScroll && rect && (self.isFocused() - || self.searchBox && self.searchBox.isFocused()) - ) { - var renderer = self.renderer; - var pos = renderer.$cursorLayer.$pixelPos; - var config = renderer.layerConfig; - var top = pos.top - config.offset; - if (pos.top >= 0 && top + rect.top < 0) { - shouldScroll = true; - } else if (pos.top < config.height && - pos.top + rect.top + config.lineHeight > window.innerHeight) { - shouldScroll = false; - } else { - shouldScroll = null; - } - if (shouldScroll != null) { - scrollAnchor.style.top = top + "px"; - scrollAnchor.style.left = pos.left + "px"; - scrollAnchor.style.height = config.lineHeight + "px"; - scrollAnchor.scrollIntoView(shouldScroll); - } - shouldScroll = rect = null; - } - }); - this.setAutoScrollEditorIntoView = function(enable) { - if (enable) - return; - delete this.setAutoScrollEditorIntoView; - this.off("changeSelection", onChangeSelection); - this.renderer.off("afterRender", onAfterRender); - this.renderer.off("beforeRender", onBeforeRender); - }; - }; - - - this.$resetCursorStyle = function() { - var style = this.$cursorStyle || "ace"; - var cursorLayer = this.renderer.$cursorLayer; - if (!cursorLayer) - return; - cursorLayer.setSmoothBlinking(/smooth/.test(style)); - cursorLayer.isBlinking = !this.$readOnly && style != "wide"; - dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style)); - }; - this.prompt = function(message, options, callback) { - var editor = this; - config.loadModule("./ext/prompt", function (module) { - module.prompt(editor, message, options, callback); - }); - }; - -}).call(Editor.prototype); - - - -config.defineOptions(Editor.prototype, "editor", { - selectionStyle: { - set: function(style) { - this.onSelectionChange(); - this._signal("changeSelectionStyle", {data: style}); - }, - initialValue: "line" - }, - highlightActiveLine: { - set: function() {this.$updateHighlightActiveLine();}, - initialValue: true - }, - highlightSelectedWord: { - set: function(shouldHighlight) {this.$onSelectionChange();}, - initialValue: true - }, - readOnly: { - set: function(readOnly) { - this.textInput.setReadOnly(readOnly); - this.$resetCursorStyle(); - }, - initialValue: false - }, - copyWithEmptySelection: { - set: function(value) { - this.textInput.setCopyWithEmptySelection(value); - }, - initialValue: false - }, - cursorStyle: { - set: function(val) { this.$resetCursorStyle(); }, - values: ["ace", "slim", "smooth", "wide"], - initialValue: "ace" - }, - mergeUndoDeltas: { - values: [false, true, "always"], - initialValue: true - }, - behavioursEnabled: {initialValue: true}, - wrapBehavioursEnabled: {initialValue: true}, - enableAutoIndent: {initialValue: true}, - autoScrollEditorIntoView: { - set: function(val) {this.setAutoScrollEditorIntoView(val);} - }, - keyboardHandler: { - set: function(val) { this.setKeyboardHandler(val); }, - get: function() { return this.$keybindingId; }, - handlesSet: true - }, - value: { - set: function(val) { this.session.setValue(val); }, - get: function() { return this.getValue(); }, - handlesSet: true, - hidden: true - }, - session: { - set: function(val) { this.setSession(val); }, - get: function() { return this.session; }, - handlesSet: true, - hidden: true - }, - - showLineNumbers: { - set: function(show) { - this.renderer.$gutterLayer.setShowLineNumbers(show); - this.renderer.$loop.schedule(this.renderer.CHANGE_GUTTER); - if (show && this.$relativeLineNumbers) - relativeNumberRenderer.attach(this); - else - relativeNumberRenderer.detach(this); - }, - initialValue: true - }, - relativeLineNumbers: { - set: function(value) { - if (this.$showLineNumbers && value) - relativeNumberRenderer.attach(this); - else - relativeNumberRenderer.detach(this); - } - }, - placeholder: { - set: function(message) { - if (!this.$updatePlaceholder) { - this.$updatePlaceholder = function() { - var value = this.session && (this.renderer.$composition || this.getValue()); - if (value && this.renderer.placeholderNode) { - this.renderer.off("afterRender", this.$updatePlaceholder); - dom.removeCssClass(this.container, "ace_hasPlaceholder"); - this.renderer.placeholderNode.remove(); - this.renderer.placeholderNode = null; - } else if (!value && !this.renderer.placeholderNode) { - this.renderer.on("afterRender", this.$updatePlaceholder); - dom.addCssClass(this.container, "ace_hasPlaceholder"); - var el = dom.createElement("div"); - el.className = "ace_placeholder"; - el.textContent = this.$placeholder || ""; - this.renderer.placeholderNode = el; - this.renderer.content.appendChild(this.renderer.placeholderNode); - } else if (!value && this.renderer.placeholderNode) { - this.renderer.placeholderNode.textContent = this.$placeholder || ""; - } - }.bind(this); - this.on("input", this.$updatePlaceholder); - } - this.$updatePlaceholder(); - } - }, - - hScrollBarAlwaysVisible: "renderer", - vScrollBarAlwaysVisible: "renderer", - highlightGutterLine: "renderer", - animatedScroll: "renderer", - showInvisibles: "renderer", - showPrintMargin: "renderer", - printMarginColumn: "renderer", - printMargin: "renderer", - fadeFoldWidgets: "renderer", - showFoldWidgets: "renderer", - displayIndentGuides: "renderer", - showGutter: "renderer", - fontSize: "renderer", - fontFamily: "renderer", - maxLines: "renderer", - minLines: "renderer", - scrollPastEnd: "renderer", - fixedWidthGutter: "renderer", - theme: "renderer", - hasCssTransforms: "renderer", - maxPixelHeight: "renderer", - useTextareaForIME: "renderer", - - scrollSpeed: "$mouseHandler", - dragDelay: "$mouseHandler", - dragEnabled: "$mouseHandler", - focusTimeout: "$mouseHandler", - tooltipFollowsMouse: "$mouseHandler", - - firstLineNumber: "session", - overwrite: "session", - newLineMode: "session", - useWorker: "session", - useSoftTabs: "session", - navigateWithinSoftTabs: "session", - tabSize: "session", - wrap: "session", - indentedSoftWrap: "session", - foldStyle: "session", - mode: "session" -}); - - -var relativeNumberRenderer = { - getText: function(session, row) { - return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9 ? "\xb7" : ""))) + ""; - }, - getWidth: function(session, lastLineNumber, config) { - return Math.max( - lastLineNumber.toString().length, - (config.lastRow + 1).toString().length, - 2 - ) * config.characterWidth; - }, - update: function(e, editor) { - editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER); - }, - attach: function(editor) { - editor.renderer.$gutterLayer.$renderer = this; - editor.on("changeSelection", this.update); - this.update(null, editor); - }, - detach: function(editor) { - if (editor.renderer.$gutterLayer.$renderer == this) - editor.renderer.$gutterLayer.$renderer = null; - editor.off("changeSelection", this.update); - this.update(null, editor); - } -}; - -exports.Editor = Editor; -}); - -define("ace/undomanager",["require","exports","module","ace/range"], function(require, exports, module) { -"use strict"; -var UndoManager = function() { - this.$maxRev = 0; - this.$fromUndo = false; - this.reset(); -}; - -(function() { - - this.addSession = function(session) { - this.$session = session; - }; - this.add = function(delta, allowMerge, session) { - if (this.$fromUndo) return; - if (delta == this.$lastDelta) return; - if (!this.$keepRedoStack) this.$redoStack.length = 0; - if (allowMerge === false || !this.lastDeltas) { - this.lastDeltas = []; - this.$undoStack.push(this.lastDeltas); - delta.id = this.$rev = ++this.$maxRev; - } - if (delta.action == "remove" || delta.action == "insert") - this.$lastDelta = delta; - this.lastDeltas.push(delta); - }; - - this.addSelection = function(selection, rev) { - this.selections.push({ - value: selection, - rev: rev || this.$rev - }); - }; - - this.startNewGroup = function() { - this.lastDeltas = null; - return this.$rev; - }; - - this.markIgnored = function(from, to) { - if (to == null) to = this.$rev + 1; - var stack = this.$undoStack; - for (var i = stack.length; i--;) { - var delta = stack[i][0]; - if (delta.id <= from) - break; - if (delta.id < to) - delta.ignore = true; - } - this.lastDeltas = null; - }; - - this.getSelection = function(rev, after) { - var stack = this.selections; - for (var i = stack.length; i--;) { - var selection = stack[i]; - if (selection.rev < rev) { - if (after) - selection = stack[i + 1]; - return selection; - } - } - }; - - this.getRevision = function() { - return this.$rev; - }; - - this.getDeltas = function(from, to) { - if (to == null) to = this.$rev + 1; - var stack = this.$undoStack; - var end = null, start = 0; - for (var i = stack.length; i--;) { - var delta = stack[i][0]; - if (delta.id < to && !end) - end = i+1; - if (delta.id <= from) { - start = i + 1; - break; - } - } - return stack.slice(start, end); - }; - - this.getChangedRanges = function(from, to) { - if (to == null) to = this.$rev + 1; - - }; - - this.getChangedLines = function(from, to) { - if (to == null) to = this.$rev + 1; - - }; - this.undo = function(session, dontSelect) { - this.lastDeltas = null; - var stack = this.$undoStack; - - if (!rearrangeUndoStack(stack, stack.length)) - return; - - if (!session) - session = this.$session; - - if (this.$redoStackBaseRev !== this.$rev && this.$redoStack.length) - this.$redoStack = []; - - this.$fromUndo = true; - - var deltaSet = stack.pop(); - var undoSelectionRange = null; - if (deltaSet) { - undoSelectionRange = session.undoChanges(deltaSet, dontSelect); - this.$redoStack.push(deltaSet); - this.$syncRev(); - } - - this.$fromUndo = false; - - return undoSelectionRange; - }; - this.redo = function(session, dontSelect) { - this.lastDeltas = null; - - if (!session) - session = this.$session; - - this.$fromUndo = true; - if (this.$redoStackBaseRev != this.$rev) { - var diff = this.getDeltas(this.$redoStackBaseRev, this.$rev + 1); - rebaseRedoStack(this.$redoStack, diff); - this.$redoStackBaseRev = this.$rev; - this.$redoStack.forEach(function(x) { - x[0].id = ++this.$maxRev; - }, this); - } - var deltaSet = this.$redoStack.pop(); - var redoSelectionRange = null; - - if (deltaSet) { - redoSelectionRange = session.redoChanges(deltaSet, dontSelect); - this.$undoStack.push(deltaSet); - this.$syncRev(); - } - this.$fromUndo = false; - - return redoSelectionRange; - }; - - this.$syncRev = function() { - var stack = this.$undoStack; - var nextDelta = stack[stack.length - 1]; - var id = nextDelta && nextDelta[0].id || 0; - this.$redoStackBaseRev = id; - this.$rev = id; - }; - this.reset = function() { - this.lastDeltas = null; - this.$lastDelta = null; - this.$undoStack = []; - this.$redoStack = []; - this.$rev = 0; - this.mark = 0; - this.$redoStackBaseRev = this.$rev; - this.selections = []; - }; - this.canUndo = function() { - return this.$undoStack.length > 0; - }; - this.canRedo = function() { - return this.$redoStack.length > 0; - }; - this.bookmark = function(rev) { - if (rev == undefined) - rev = this.$rev; - this.mark = rev; - }; - this.isAtBookmark = function() { - return this.$rev === this.mark; - }; - - this.toJSON = function() { - - }; - - this.fromJSON = function() { - - }; - - this.hasUndo = this.canUndo; - this.hasRedo = this.canRedo; - this.isClean = this.isAtBookmark; - this.markClean = this.bookmark; - - this.$prettyPrint = function(delta) { - if (delta) return stringifyDelta(delta); - return stringifyDelta(this.$undoStack) + "\n---\n" + stringifyDelta(this.$redoStack); - }; -}).call(UndoManager.prototype); - -function rearrangeUndoStack(stack, pos) { - for (var i = pos; i--; ) { - var deltaSet = stack[i]; - if (deltaSet && !deltaSet[0].ignore) { - while(i < pos - 1) { - var swapped = swapGroups(stack[i], stack[i + 1]); - stack[i] = swapped[0]; - stack[i + 1] = swapped[1]; - i++; - } - return true; - } - } -} - -var Range = require("./range").Range; -var cmp = Range.comparePoints; -var comparePoints = Range.comparePoints; - -function $updateMarkers(delta) { - var isInsert = delta.action == "insert"; - var start = delta.start; - var end = delta.end; - var rowShift = (end.row - start.row) * (isInsert ? 1 : -1); - var colShift = (end.column - start.column) * (isInsert ? 1 : -1); - if (isInsert) end = start; - - for (var i in this.marks) { - var point = this.marks[i]; - var cmp = comparePoints(point, start); - if (cmp < 0) { - continue; // delta starts after the range - } - if (cmp === 0) { - if (isInsert) { - if (point.bias == 1) { - cmp = 1; - } - else { - point.bias == -1; - continue; - } - } - } - var cmp2 = isInsert ? cmp : comparePoints(point, end); - if (cmp2 > 0) { - point.row += rowShift; - point.column += point.row == end.row ? colShift : 0; - continue; - } - if (!isInsert && cmp2 <= 0) { - point.row = start.row; - point.column = start.column; - if (cmp2 === 0) - point.bias = 1; - } - } -} - - - -function clonePos(pos) { - return {row: pos.row,column: pos.column}; -} -function cloneDelta(d) { - return { - start: clonePos(d.start), - end: clonePos(d.end), - action: d.action, - lines: d.lines.slice() - }; -} -function stringifyDelta(d) { - d = d || this; - if (Array.isArray(d)) { - return d.map(stringifyDelta).join("\n"); - } - var type = ""; - if (d.action) { - type = d.action == "insert" ? "+" : "-"; - type += "[" + d.lines + "]"; - } else if (d.value) { - if (Array.isArray(d.value)) { - type = d.value.map(stringifyRange).join("\n"); - } else { - type = stringifyRange(d.value); - } - } - if (d.start) { - type += stringifyRange(d); - } - if (d.id || d.rev) { - type += "\t(" + (d.id || d.rev) + ")"; - } - return type; -} -function stringifyRange(r) { - return r.start.row + ":" + r.start.column - + "=>" + r.end.row + ":" + r.end.column; -} - -function swap(d1, d2) { - var i1 = d1.action == "insert"; - var i2 = d2.action == "insert"; - - if (i1 && i2) { - if (cmp(d2.start, d1.end) >= 0) { - shift(d2, d1, -1); - } else if (cmp(d2.start, d1.start) <= 0) { - shift(d1, d2, +1); - } else { - return null; - } - } else if (i1 && !i2) { - if (cmp(d2.start, d1.end) >= 0) { - shift(d2, d1, -1); - } else if (cmp(d2.end, d1.start) <= 0) { - shift(d1, d2, -1); - } else { - return null; - } - } else if (!i1 && i2) { - if (cmp(d2.start, d1.start) >= 0) { - shift(d2, d1, +1); - } else if (cmp(d2.start, d1.start) <= 0) { - shift(d1, d2, +1); - } else { - return null; - } - } else if (!i1 && !i2) { - if (cmp(d2.start, d1.start) >= 0) { - shift(d2, d1, +1); - } else if (cmp(d2.end, d1.start) <= 0) { - shift(d1, d2, -1); - } else { - return null; - } - } - return [d2, d1]; -} -function swapGroups(ds1, ds2) { - for (var i = ds1.length; i--; ) { - for (var j = 0; j < ds2.length; j++) { - if (!swap(ds1[i], ds2[j])) { - while (i < ds1.length) { - while (j--) { - swap(ds2[j], ds1[i]); - } - j = ds2.length; - i++; - } - return [ds1, ds2]; - } - } - } - ds1.selectionBefore = ds2.selectionBefore = - ds1.selectionAfter = ds2.selectionAfter = null; - return [ds2, ds1]; -} -function xform(d1, c1) { - var i1 = d1.action == "insert"; - var i2 = c1.action == "insert"; - - if (i1 && i2) { - if (cmp(d1.start, c1.start) < 0) { - shift(c1, d1, 1); - } else { - shift(d1, c1, 1); - } - } else if (i1 && !i2) { - if (cmp(d1.start, c1.end) >= 0) { - shift(d1, c1, -1); - } else if (cmp(d1.start, c1.start) <= 0) { - shift(c1, d1, +1); - } else { - shift(d1, Range.fromPoints(c1.start, d1.start), -1); - shift(c1, d1, +1); - } - } else if (!i1 && i2) { - if (cmp(c1.start, d1.end) >= 0) { - shift(c1, d1, -1); - } else if (cmp(c1.start, d1.start) <= 0) { - shift(d1, c1, +1); - } else { - shift(c1, Range.fromPoints(d1.start, c1.start), -1); - shift(d1, c1, +1); - } - } else if (!i1 && !i2) { - if (cmp(c1.start, d1.end) >= 0) { - shift(c1, d1, -1); - } else if (cmp(c1.end, d1.start) <= 0) { - shift(d1, c1, -1); - } else { - var before, after; - if (cmp(d1.start, c1.start) < 0) { - before = d1; - d1 = splitDelta(d1, c1.start); - } - if (cmp(d1.end, c1.end) > 0) { - after = splitDelta(d1, c1.end); - } - - shiftPos(c1.end, d1.start, d1.end, -1); - if (after && !before) { - d1.lines = after.lines; - d1.start = after.start; - d1.end = after.end; - after = d1; - } - - return [c1, before, after].filter(Boolean); - } - } - return [c1, d1]; -} - -function shift(d1, d2, dir) { - shiftPos(d1.start, d2.start, d2.end, dir); - shiftPos(d1.end, d2.start, d2.end, dir); -} -function shiftPos(pos, start, end, dir) { - if (pos.row == (dir == 1 ? start : end).row) { - pos.column += dir * (end.column - start.column); - } - pos.row += dir * (end.row - start.row); -} -function splitDelta(c, pos) { - var lines = c.lines; - var end = c.end; - c.end = clonePos(pos); - var rowsBefore = c.end.row - c.start.row; - var otherLines = lines.splice(rowsBefore, lines.length); - - var col = rowsBefore ? pos.column : pos.column - c.start.column; - lines.push(otherLines[0].substring(0, col)); - otherLines[0] = otherLines[0].substr(col) ; - var rest = { - start: clonePos(pos), - end: end, - lines: otherLines, - action: c.action - }; - return rest; -} - -function moveDeltasByOne(redoStack, d) { - d = cloneDelta(d); - for (var j = redoStack.length; j--;) { - var deltaSet = redoStack[j]; - for (var i = 0; i < deltaSet.length; i++) { - var x = deltaSet[i]; - var xformed = xform(x, d); - d = xformed[0]; - if (xformed.length != 2) { - if (xformed[2]) { - deltaSet.splice(i + 1, 1, xformed[1], xformed[2]); - i++; - } else if (!xformed[1]) { - deltaSet.splice(i, 1); - i--; - } - } - } - if (!deltaSet.length) { - redoStack.splice(j, 1); - } - } - return redoStack; -} -function rebaseRedoStack(redoStack, deltaSets) { - for (var i = 0; i < deltaSets.length; i++) { - var deltas = deltaSets[i]; - for (var j = 0; j < deltas.length; j++) { - moveDeltasByOne(redoStack, deltas[j]); - } - } -} - -exports.UndoManager = UndoManager; - -}); - -define("ace/layer/lines",["require","exports","module","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -var dom = require("../lib/dom"); - -var Lines = function(element, canvasHeight) { - this.element = element; - this.canvasHeight = canvasHeight || 500000; - this.element.style.height = (this.canvasHeight * 2) + "px"; - - this.cells = []; - this.cellCache = []; - this.$offsetCoefficient = 0; -}; - -(function() { - - this.moveContainer = function(config) { - dom.translate(this.element, 0, -((config.firstRowScreen * config.lineHeight) % this.canvasHeight) - config.offset * this.$offsetCoefficient); - }; - - this.pageChanged = function(oldConfig, newConfig) { - return ( - Math.floor((oldConfig.firstRowScreen * oldConfig.lineHeight) / this.canvasHeight) !== - Math.floor((newConfig.firstRowScreen * newConfig.lineHeight) / this.canvasHeight) - ); - }; - - this.computeLineTop = function(row, config, session) { - var screenTop = config.firstRowScreen * config.lineHeight; - var screenPage = Math.floor(screenTop / this.canvasHeight); - var lineTop = session.documentToScreenRow(row, 0) * config.lineHeight; - return lineTop - (screenPage * this.canvasHeight); - }; - - this.computeLineHeight = function(row, config, session) { - return config.lineHeight * session.getRowLineCount(row); - }; - - this.getLength = function() { - return this.cells.length; - }; - - this.get = function(index) { - return this.cells[index]; - }; - - this.shift = function() { - this.$cacheCell(this.cells.shift()); - }; - - this.pop = function() { - this.$cacheCell(this.cells.pop()); - }; - - this.push = function(cell) { - if (Array.isArray(cell)) { - this.cells.push.apply(this.cells, cell); - var fragment = dom.createFragment(this.element); - for (var i=0; i foldStart) { - row = fold.end.row + 1; - fold = session.getNextFoldLine(row, fold); - foldStart = fold ? fold.start.row : Infinity; - } - if (row > lastRow) { - while (this.$lines.getLength() > index + 1) - this.$lines.pop(); - - break; - } - - cell = this.$lines.get(++index); - if (cell) { - cell.row = row; - } else { - cell = this.$lines.createCell(row, config, this.session, onCreateCell); - this.$lines.push(cell); - } - - this.$renderCell(cell, config, fold, row); - row++; - } - - this._signal("afterRender"); - this.$updateGutterWidth(config); - }; - - this.$updateGutterWidth = function(config) { - var session = this.session; - - var gutterRenderer = session.gutterRenderer || this.$renderer; - - var firstLineNumber = session.$firstLineNumber; - var lastLineText = this.$lines.last() ? this.$lines.last().text : ""; - - if (this.$fixedWidth || session.$useWrapMode) - lastLineText = session.getLength() + firstLineNumber - 1; - - var gutterWidth = gutterRenderer - ? gutterRenderer.getWidth(session, lastLineText, config) - : lastLineText.toString().length * config.characterWidth; - - var padding = this.$padding || this.$computePadding(); - gutterWidth += padding.left + padding.right; - if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) { - this.gutterWidth = gutterWidth; - this.element.parentNode.style.width = - this.element.style.width = Math.ceil(this.gutterWidth) + "px"; - this._signal("changeGutterWidth", gutterWidth); - } - }; - - this.$updateCursorRow = function() { - if (!this.$highlightGutterLine) - return; - - var position = this.session.selection.getCursor(); - if (this.$cursorRow === position.row) - return; - - this.$cursorRow = position.row; - }; - - this.updateLineHighlight = function() { - if (!this.$highlightGutterLine) - return; - var row = this.session.selection.cursor.row; - this.$cursorRow = row; - - if (this.$cursorCell && this.$cursorCell.row == row) - return; - if (this.$cursorCell) - this.$cursorCell.element.className = this.$cursorCell.element.className.replace("ace_gutter-active-line ", ""); - var cells = this.$lines.cells; - this.$cursorCell = null; - for (var i = 0; i < cells.length; i++) { - var cell = cells[i]; - if (cell.row >= this.$cursorRow) { - if (cell.row > this.$cursorRow) { - var fold = this.session.getFoldLine(this.$cursorRow); - if (i > 0 && fold && fold.start.row == cells[i - 1].row) - cell = cells[i - 1]; - else - break; - } - cell.element.className = "ace_gutter-active-line " + cell.element.className; - this.$cursorCell = cell; - break; - } - } - }; - - this.scrollLines = function(config) { - var oldConfig = this.config; - this.config = config; - - this.$updateCursorRow(); - if (this.$lines.pageChanged(oldConfig, config)) - return this.update(config); - - this.$lines.moveContainer(config); - - var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar - this.session.getLength() - 1); - var oldLastRow = this.oldLastRow; - this.oldLastRow = lastRow; - - if (!oldConfig || oldLastRow < config.firstRow) - return this.update(config); - - if (lastRow < oldConfig.firstRow) - return this.update(config); - - if (oldConfig.firstRow < config.firstRow) - for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--) - this.$lines.shift(); - - if (oldLastRow > lastRow) - for (var row=this.session.getFoldedRowCount(lastRow + 1, oldLastRow); row>0; row--) - this.$lines.pop(); - - if (config.firstRow < oldConfig.firstRow) { - this.$lines.unshift(this.$renderLines(config, config.firstRow, oldConfig.firstRow - 1)); - } - - if (lastRow > oldLastRow) { - this.$lines.push(this.$renderLines(config, oldLastRow + 1, lastRow)); - } - - this.updateLineHighlight(); - - this._signal("afterRender"); - this.$updateGutterWidth(config); - }; - - this.$renderLines = function(config, firstRow, lastRow) { - var fragment = []; - var row = firstRow; - var foldLine = this.session.getNextFoldLine(row); - var foldStart = foldLine ? foldLine.start.row : Infinity; - - while (true) { - if (row > foldStart) { - row = foldLine.end.row+1; - foldLine = this.session.getNextFoldLine(row, foldLine); - foldStart = foldLine ? foldLine.start.row : Infinity; - } - if (row > lastRow) - break; - - var cell = this.$lines.createCell(row, config, this.session, onCreateCell); - this.$renderCell(cell, config, foldLine, row); - fragment.push(cell); - - row++; - } - return fragment; - }; - - this.$renderCell = function(cell, config, fold, row) { - var element = cell.element; - - var session = this.session; - - var textNode = element.childNodes[0]; - var foldWidget = element.childNodes[1]; - - var firstLineNumber = session.$firstLineNumber; - - var breakpoints = session.$breakpoints; - var decorations = session.$decorations; - var gutterRenderer = session.gutterRenderer || this.$renderer; - var foldWidgets = this.$showFoldWidgets && session.foldWidgets; - var foldStart = fold ? fold.start.row : Number.MAX_VALUE; - - var className = "ace_gutter-cell "; - if (this.$highlightGutterLine) { - if (row == this.$cursorRow || (fold && row < this.$cursorRow && row >= foldStart && this.$cursorRow <= fold.end.row)) { - className += "ace_gutter-active-line "; - if (this.$cursorCell != cell) { - if (this.$cursorCell) - this.$cursorCell.element.className = this.$cursorCell.element.className.replace("ace_gutter-active-line ", ""); - this.$cursorCell = cell; - } - } - } - - if (breakpoints[row]) - className += breakpoints[row]; - if (decorations[row]) - className += decorations[row]; - if (this.$annotations[row]) - className += this.$annotations[row].className; - if (element.className != className) - element.className = className; - - if (foldWidgets) { - var c = foldWidgets[row]; - if (c == null) - c = foldWidgets[row] = session.getFoldWidget(row); - } - - if (c) { - var className = "ace_fold-widget ace_" + c; - if (c == "start" && row == foldStart && row < fold.end.row) - className += " ace_closed"; - else - className += " ace_open"; - if (foldWidget.className != className) - foldWidget.className = className; - - var foldHeight = config.lineHeight + "px"; - dom.setStyle(foldWidget.style, "height", foldHeight); - dom.setStyle(foldWidget.style, "display", "inline-block"); - } else { - if (foldWidget) { - dom.setStyle(foldWidget.style, "display", "none"); - } - } - - var text = (gutterRenderer - ? gutterRenderer.getText(session, row) - : row + firstLineNumber).toString(); - - if (text !== textNode.data) { - textNode.data = text; - } - - dom.setStyle(cell.element.style, "height", this.$lines.computeLineHeight(row, config, session) + "px"); - dom.setStyle(cell.element.style, "top", this.$lines.computeLineTop(row, config, session) + "px"); - - cell.text = text; - return cell; - }; - - this.$fixedWidth = false; - - this.$highlightGutterLine = true; - this.$renderer = ""; - this.setHighlightGutterLine = function(highlightGutterLine) { - this.$highlightGutterLine = highlightGutterLine; - }; - - this.$showLineNumbers = true; - this.$renderer = ""; - this.setShowLineNumbers = function(show) { - this.$renderer = !show && { - getWidth: function() {return 0;}, - getText: function() {return "";} - }; - }; - - this.getShowLineNumbers = function() { - return this.$showLineNumbers; - }; - - this.$showFoldWidgets = true; - this.setShowFoldWidgets = function(show) { - if (show) - dom.addCssClass(this.element, "ace_folding-enabled"); - else - dom.removeCssClass(this.element, "ace_folding-enabled"); - - this.$showFoldWidgets = show; - this.$padding = null; - }; - - this.getShowFoldWidgets = function() { - return this.$showFoldWidgets; - }; - - this.$computePadding = function() { - if (!this.element.firstChild) - return {left: 0, right: 0}; - var style = dom.computedStyle(this.element.firstChild); - this.$padding = {}; - this.$padding.left = (parseInt(style.borderLeftWidth) || 0) - + (parseInt(style.paddingLeft) || 0) + 1; - this.$padding.right = (parseInt(style.borderRightWidth) || 0) - + (parseInt(style.paddingRight) || 0); - return this.$padding; - }; - - this.getRegion = function(point) { - var padding = this.$padding || this.$computePadding(); - var rect = this.element.getBoundingClientRect(); - if (point.x < padding.left + rect.left) - return "markers"; - if (this.$showFoldWidgets && point.x > rect.right - padding.right) - return "foldWidgets"; - }; - -}).call(Gutter.prototype); - -function onCreateCell(element) { - var textNode = document.createTextNode(''); - element.appendChild(textNode); - - var foldWidget = dom.createElement("span"); - element.appendChild(foldWidget); - - return element; -} - -exports.Gutter = Gutter; - -}); - -define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -var Range = require("../range").Range; -var dom = require("../lib/dom"); - -var Marker = function(parentEl) { - this.element = dom.createElement("div"); - this.element.className = "ace_layer ace_marker-layer"; - parentEl.appendChild(this.element); -}; - -(function() { - - this.$padding = 0; - - this.setPadding = function(padding) { - this.$padding = padding; - }; - this.setSession = function(session) { - this.session = session; - }; - - this.setMarkers = function(markers) { - this.markers = markers; - }; - - this.elt = function(className, css) { - var x = this.i != -1 && this.element.childNodes[this.i]; - if (!x) { - x = document.createElement("div"); - this.element.appendChild(x); - this.i = -1; - } else { - this.i++; - } - x.style.cssText = css; - x.className = className; - }; - - this.update = function(config) { - if (!config) return; - - this.config = config; - - this.i = 0; - var html; - for (var key in this.markers) { - var marker = this.markers[key]; - - if (!marker.range) { - marker.update(html, this, this.session, config); - continue; - } - - var range = marker.range.clipRows(config.firstRow, config.lastRow); - if (range.isEmpty()) continue; - - range = range.toScreenRange(this.session); - if (marker.renderer) { - var top = this.$getTop(range.start.row, config); - var left = this.$padding + range.start.column * config.characterWidth; - marker.renderer(html, range, left, top, config); - } else if (marker.type == "fullLine") { - this.drawFullLineMarker(html, range, marker.clazz, config); - } else if (marker.type == "screenLine") { - this.drawScreenLineMarker(html, range, marker.clazz, config); - } else if (range.isMultiLine()) { - if (marker.type == "text") - this.drawTextMarker(html, range, marker.clazz, config); - else - this.drawMultiLineMarker(html, range, marker.clazz, config); - } else { - this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config); - } - } - if (this.i !=-1) { - while (this.i < this.element.childElementCount) - this.element.removeChild(this.element.lastChild); - } - }; - - this.$getTop = function(row, layerConfig) { - return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight; - }; - - function getBorderClass(tl, tr, br, bl) { - return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0); - } - this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) { - var session = this.session; - var start = range.start.row; - var end = range.end.row; - var row = start; - var prev = 0; - var curr = 0; - var next = session.getScreenLastRowColumn(row); - var lineRange = new Range(row, range.start.column, row, curr); - for (; row <= end; row++) { - lineRange.start.row = lineRange.end.row = row; - lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row); - lineRange.end.column = next; - prev = curr; - curr = next; - next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column; - this.drawSingleLineMarker(stringBuilder, lineRange, - clazz + (row == start ? " ace_start" : "") + " ace_br" - + getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end), - layerConfig, row == end ? 0 : 1, extraStyle); - } - }; - this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var padding = this.$padding; - var height = config.lineHeight; - var top = this.$getTop(range.start.row, config); - var left = padding + range.start.column * config.characterWidth; - extraStyle = extraStyle || ""; - - if (this.session.$bidiHandler.isBidiRow(range.start.row)) { - var range1 = range.clone(); - range1.end.row = range1.start.row; - range1.end.column = this.session.getLine(range1.start.row).length; - this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br1 ace_start", config, null, extraStyle); - } else { - this.elt( - clazz + " ace_br1 ace_start", - "height:"+ height+ "px;"+ "right:0;"+ "top:"+top+ "px;left:"+ left+ "px;" + (extraStyle || "") - ); - } - if (this.session.$bidiHandler.isBidiRow(range.end.row)) { - var range1 = range.clone(); - range1.start.row = range1.end.row; - range1.start.column = 0; - this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br12", config, null, extraStyle); - } else { - top = this.$getTop(range.end.row, config); - var width = range.end.column * config.characterWidth; - - this.elt( - clazz + " ace_br12", - "height:"+ height+ "px;"+ - "width:"+ width+ "px;"+ - "top:"+ top+ "px;"+ - "left:"+ padding+ "px;"+ (extraStyle || "") - ); - } - height = (range.end.row - range.start.row - 1) * config.lineHeight; - if (height <= 0) - return; - top = this.$getTop(range.start.row + 1, config); - - var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8); - - this.elt( - clazz + (radiusClass ? " ace_br" + radiusClass : ""), - "height:"+ height+ "px;"+ - "right:0;"+ - "top:"+ top+ "px;"+ - "left:"+ padding+ "px;"+ (extraStyle || "") - ); - }; - this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { - if (this.session.$bidiHandler.isBidiRow(range.start.row)) - return this.drawBidiSingleLineMarker(stringBuilder, range, clazz, config, extraLength, extraStyle); - var height = config.lineHeight; - var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth; - - var top = this.$getTop(range.start.row, config); - var left = this.$padding + range.start.column * config.characterWidth; - - this.elt( - clazz, - "height:"+ height+ "px;"+ - "width:"+ width+ "px;"+ - "top:"+ top+ "px;"+ - "left:"+ left+ "px;"+ (extraStyle || "") - ); - }; - this.drawBidiSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { - var height = config.lineHeight, top = this.$getTop(range.start.row, config), padding = this.$padding; - var selections = this.session.$bidiHandler.getSelections(range.start.column, range.end.column); - - selections.forEach(function(selection) { - this.elt( - clazz, - "height:" + height + "px;" + - "width:" + selection.width + (extraLength || 0) + "px;" + - "top:" + top + "px;" + - "left:" + (padding + selection.left) + "px;" + (extraStyle || "") - ); - }, this); - }; - - this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var top = this.$getTop(range.start.row, config); - var height = config.lineHeight; - if (range.start.row != range.end.row) - height += this.$getTop(range.end.row, config) - top; - - this.elt( - clazz, - "height:"+ height+ "px;"+ - "top:"+ top+ "px;"+ - "left:0;right:0;"+ (extraStyle || "") - ); - }; - - this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var top = this.$getTop(range.start.row, config); - var height = config.lineHeight; - - this.elt( - clazz, - "height:"+ height+ "px;"+ - "top:"+ top+ "px;"+ - "left:0;right:0;"+ (extraStyle || "") - ); - }; - -}).call(Marker.prototype); - -exports.Marker = Marker; - -}); - -define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/layer/lines","ace/lib/event_emitter"], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var dom = require("../lib/dom"); -var lang = require("../lib/lang"); -var Lines = require("./lines").Lines; -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var Text = function(parentEl) { - this.dom = dom; - this.element = this.dom.createElement("div"); - this.element.className = "ace_layer ace_text-layer"; - parentEl.appendChild(this.element); - this.$updateEolChar = this.$updateEolChar.bind(this); - this.$lines = new Lines(this.element); -}; - -(function() { - - oop.implement(this, EventEmitter); - - this.EOF_CHAR = "\xB6"; - this.EOL_CHAR_LF = "\xAC"; - this.EOL_CHAR_CRLF = "\xa4"; - this.EOL_CHAR = this.EOL_CHAR_LF; - this.TAB_CHAR = "\u2014"; //"\u21E5"; - this.SPACE_CHAR = "\xB7"; - this.$padding = 0; - this.MAX_LINE_LENGTH = 10000; - - this.$updateEolChar = function() { - var doc = this.session.doc; - var unixMode = doc.getNewLineCharacter() == "\n" && doc.getNewLineMode() != "windows"; - var EOL_CHAR = unixMode ? this.EOL_CHAR_LF : this.EOL_CHAR_CRLF; - if (this.EOL_CHAR != EOL_CHAR) { - this.EOL_CHAR = EOL_CHAR; - return true; - } - }; - - this.setPadding = function(padding) { - this.$padding = padding; - this.element.style.margin = "0 " + padding + "px"; - }; - - this.getLineHeight = function() { - return this.$fontMetrics.$characterSize.height || 0; - }; - - this.getCharacterWidth = function() { - return this.$fontMetrics.$characterSize.width || 0; - }; - - this.$setFontMetrics = function(measure) { - this.$fontMetrics = measure; - this.$fontMetrics.on("changeCharacterSize", function(e) { - this._signal("changeCharacterSize", e); - }.bind(this)); - this.$pollSizeChanges(); - }; - - this.checkForSizeChanges = function() { - this.$fontMetrics.checkForSizeChanges(); - }; - this.$pollSizeChanges = function() { - return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges(); - }; - this.setSession = function(session) { - this.session = session; - if (session) - this.$computeTabString(); - }; - - this.showInvisibles = false; - this.showSpaces = false; - this.showTabs = false; - this.showEOL = false; - this.setShowInvisibles = function(showInvisibles) { - if (this.showInvisibles == showInvisibles) - return false; - - this.showInvisibles = showInvisibles; - if (typeof showInvisibles == "string") { - this.showSpaces = /tab/i.test(showInvisibles); - this.showTabs = /space/i.test(showInvisibles); - this.showEOL = /eol/i.test(showInvisibles); - } else { - this.showSpaces = this.showTabs = this.showEOL = showInvisibles; - } - this.$computeTabString(); - return true; - }; - - this.displayIndentGuides = true; - this.setDisplayIndentGuides = function(display) { - if (this.displayIndentGuides == display) - return false; - - this.displayIndentGuides = display; - this.$computeTabString(); - return true; - }; - - this.$tabStrings = []; - this.onChangeTabSize = - this.$computeTabString = function() { - var tabSize = this.session.getTabSize(); - this.tabSize = tabSize; - var tabStr = this.$tabStrings = [0]; - for (var i = 1; i < tabSize + 1; i++) { - if (this.showTabs) { - var span = this.dom.createElement("span"); - span.className = "ace_invisible ace_invisible_tab"; - span.textContent = lang.stringRepeat(this.TAB_CHAR, i); - tabStr.push(span); - } else { - tabStr.push(this.dom.createTextNode(lang.stringRepeat(" ", i), this.element)); - } - } - if (this.displayIndentGuides) { - this.$indentGuideRe = /\s\S| \t|\t |\s$/; - var className = "ace_indent-guide"; - var spaceClass = this.showSpaces ? " ace_invisible ace_invisible_space" : ""; - var spaceContent = this.showSpaces - ? lang.stringRepeat(this.SPACE_CHAR, this.tabSize) - : lang.stringRepeat(" ", this.tabSize); - - var tabClass = this.showTabs ? " ace_invisible ace_invisible_tab" : ""; - var tabContent = this.showTabs - ? lang.stringRepeat(this.TAB_CHAR, this.tabSize) - : spaceContent; - - var span = this.dom.createElement("span"); - span.className = className + spaceClass; - span.textContent = spaceContent; - this.$tabStrings[" "] = span; - - var span = this.dom.createElement("span"); - span.className = className + tabClass; - span.textContent = tabContent; - this.$tabStrings["\t"] = span; - } - }; - - this.updateLines = function(config, firstRow, lastRow) { - if (this.config.lastRow != config.lastRow || - this.config.firstRow != config.firstRow) { - return this.update(config); - } - - this.config = config; - - var first = Math.max(firstRow, config.firstRow); - var last = Math.min(lastRow, config.lastRow); - - var lineElements = this.element.childNodes; - var lineElementsIdx = 0; - - for (var row = config.firstRow; row < first; row++) { - var foldLine = this.session.getFoldLine(row); - if (foldLine) { - if (foldLine.containsRow(first)) { - first = foldLine.start.row; - break; - } else { - row = foldLine.end.row; - } - } - lineElementsIdx ++; - } - - var heightChanged = false; - var row = first; - var foldLine = this.session.getNextFoldLine(row); - var foldStart = foldLine ? foldLine.start.row : Infinity; - - while (true) { - if (row > foldStart) { - row = foldLine.end.row+1; - foldLine = this.session.getNextFoldLine(row, foldLine); - foldStart = foldLine ? foldLine.start.row :Infinity; - } - if (row > last) - break; - - var lineElement = lineElements[lineElementsIdx++]; - if (lineElement) { - this.dom.removeChildren(lineElement); - this.$renderLine( - lineElement, row, row == foldStart ? foldLine : false - ); - - if (heightChanged) - lineElement.style.top = this.$lines.computeLineTop(row, config, this.session) + "px"; - - var height = (config.lineHeight * this.session.getRowLength(row)) + "px"; - if (lineElement.style.height != height) { - heightChanged = true; - lineElement.style.height = height; - } - } - row++; - } - if (heightChanged) { - while (lineElementsIdx < this.$lines.cells.length) { - var cell = this.$lines.cells[lineElementsIdx++]; - cell.element.style.top = this.$lines.computeLineTop(cell.row, config, this.session) + "px"; - } - } - }; - - this.scrollLines = function(config) { - var oldConfig = this.config; - this.config = config; - - if (this.$lines.pageChanged(oldConfig, config)) - return this.update(config); - - this.$lines.moveContainer(config); - - var lastRow = config.lastRow; - var oldLastRow = oldConfig ? oldConfig.lastRow : -1; - - if (!oldConfig || oldLastRow < config.firstRow) - return this.update(config); - - if (lastRow < oldConfig.firstRow) - return this.update(config); - - if (!oldConfig || oldConfig.lastRow < config.firstRow) - return this.update(config); - - if (config.lastRow < oldConfig.firstRow) - return this.update(config); - - if (oldConfig.firstRow < config.firstRow) - for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--) - this.$lines.shift(); - - if (oldConfig.lastRow > config.lastRow) - for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--) - this.$lines.pop(); - - if (config.firstRow < oldConfig.firstRow) { - this.$lines.unshift(this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1)); - } - - if (config.lastRow > oldConfig.lastRow) { - this.$lines.push(this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow)); - } - }; - - this.$renderLinesFragment = function(config, firstRow, lastRow) { - var fragment = []; - var row = firstRow; - var foldLine = this.session.getNextFoldLine(row); - var foldStart = foldLine ? foldLine.start.row : Infinity; - - while (true) { - if (row > foldStart) { - row = foldLine.end.row+1; - foldLine = this.session.getNextFoldLine(row, foldLine); - foldStart = foldLine ? foldLine.start.row : Infinity; - } - if (row > lastRow) - break; - - var line = this.$lines.createCell(row, config, this.session); - - var lineEl = line.element; - this.dom.removeChildren(lineEl); - dom.setStyle(lineEl.style, "height", this.$lines.computeLineHeight(row, config, this.session) + "px"); - dom.setStyle(lineEl.style, "top", this.$lines.computeLineTop(row, config, this.session) + "px"); - this.$renderLine(lineEl, row, row == foldStart ? foldLine : false); - - if (this.$useLineGroups()) { - lineEl.className = "ace_line_group"; - } else { - lineEl.className = "ace_line"; - } - fragment.push(line); - - row++; - } - return fragment; - }; - - this.update = function(config) { - this.$lines.moveContainer(config); - - this.config = config; - - var firstRow = config.firstRow; - var lastRow = config.lastRow; - - var lines = this.$lines; - while (lines.getLength()) - lines.pop(); - - lines.push(this.$renderLinesFragment(config, firstRow, lastRow)); - }; - - this.$textToken = { - "text": true, - "rparen": true, - "lparen": true - }; - - this.$renderToken = function(parent, screenColumn, token, value) { - var self = this; - var re = /(\t)|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\uFEFF\uFFF9-\uFFFC]+)|(\u3000)|([\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]|[\uD800-\uDBFF][\uDC00-\uDFFF])/g; - - var valueFragment = this.dom.createFragment(this.element); - - var m; - var i = 0; - while (m = re.exec(value)) { - var tab = m[1]; - var simpleSpace = m[2]; - var controlCharacter = m[3]; - var cjkSpace = m[4]; - var cjk = m[5]; - - if (!self.showSpaces && simpleSpace) - continue; - - var before = i != m.index ? value.slice(i, m.index) : ""; - - i = m.index + m[0].length; - - if (before) { - valueFragment.appendChild(this.dom.createTextNode(before, this.element)); - } - - if (tab) { - var tabSize = self.session.getScreenTabSize(screenColumn + m.index); - valueFragment.appendChild(self.$tabStrings[tabSize].cloneNode(true)); - screenColumn += tabSize - 1; - } else if (simpleSpace) { - if (self.showSpaces) { - var span = this.dom.createElement("span"); - span.className = "ace_invisible ace_invisible_space"; - span.textContent = lang.stringRepeat(self.SPACE_CHAR, simpleSpace.length); - valueFragment.appendChild(span); - } else { - valueFragment.appendChild(this.com.createTextNode(simpleSpace, this.element)); - } - } else if (controlCharacter) { - var span = this.dom.createElement("span"); - span.className = "ace_invisible ace_invisible_space ace_invalid"; - span.textContent = lang.stringRepeat(self.SPACE_CHAR, controlCharacter.length); - valueFragment.appendChild(span); - } else if (cjkSpace) { - screenColumn += 1; - - var span = this.dom.createElement("span"); - span.style.width = (self.config.characterWidth * 2) + "px"; - span.className = self.showSpaces ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk"; - span.textContent = self.showSpaces ? self.SPACE_CHAR : cjkSpace; - valueFragment.appendChild(span); - } else if (cjk) { - screenColumn += 1; - var span = this.dom.createElement("span"); - span.style.width = (self.config.characterWidth * 2) + "px"; - span.className = "ace_cjk"; - span.textContent = cjk; - valueFragment.appendChild(span); - } - } - - valueFragment.appendChild(this.dom.createTextNode(i ? value.slice(i) : value, this.element)); - - if (!this.$textToken[token.type]) { - var classes = "ace_" + token.type.replace(/\./g, " ace_"); - var span = this.dom.createElement("span"); - if (token.type == "fold") - span.style.width = (token.value.length * this.config.characterWidth) + "px"; - - span.className = classes; - span.appendChild(valueFragment); - - parent.appendChild(span); - } - else { - parent.appendChild(valueFragment); - } - - return screenColumn + value.length; - }; - - this.renderIndentGuide = function(parent, value, max) { - var cols = value.search(this.$indentGuideRe); - if (cols <= 0 || cols >= max) - return value; - if (value[0] == " ") { - cols -= cols % this.tabSize; - var count = cols/this.tabSize; - for (var i=0; i= splitChars) { - screenColumn = this.$renderToken( - lineEl, screenColumn, - token, value.substring(0, splitChars - chars) - ); - value = value.substring(splitChars - chars); - chars = splitChars; - - lineEl = this.$createLineElement(); - parent.appendChild(lineEl); - - lineEl.appendChild(this.dom.createTextNode(lang.stringRepeat("\xa0", splits.indent), this.element)); - - split ++; - screenColumn = 0; - splitChars = splits[split] || Number.MAX_VALUE; - } - if (value.length != 0) { - chars += value.length; - screenColumn = this.$renderToken( - lineEl, screenColumn, token, value - ); - } - } - } - - if (splits[splits.length - 1] > this.MAX_LINE_LENGTH) - this.$renderOverflowMessage(lineEl, screenColumn, null, "", true); - }; - - this.$renderSimpleLine = function(parent, tokens) { - var screenColumn = 0; - var token = tokens[0]; - var value = token.value; - if (this.displayIndentGuides) - value = this.renderIndentGuide(parent, value); - if (value) - screenColumn = this.$renderToken(parent, screenColumn, token, value); - for (var i = 1; i < tokens.length; i++) { - token = tokens[i]; - value = token.value; - if (screenColumn + value.length > this.MAX_LINE_LENGTH) - return this.$renderOverflowMessage(parent, screenColumn, token, value); - screenColumn = this.$renderToken(parent, screenColumn, token, value); - } - }; - - this.$renderOverflowMessage = function(parent, screenColumn, token, value, hide) { - token && this.$renderToken(parent, screenColumn, token, - value.slice(0, this.MAX_LINE_LENGTH - screenColumn)); - - var overflowEl = this.dom.createElement("span"); - overflowEl.className = "ace_inline_button ace_keyword ace_toggle_wrap"; - overflowEl.textContent = hide ? "" : ""; - - parent.appendChild(overflowEl); - }; - this.$renderLine = function(parent, row, foldLine) { - if (!foldLine && foldLine != false) - foldLine = this.session.getFoldLine(row); - - if (foldLine) - var tokens = this.$getFoldLineTokens(row, foldLine); - else - var tokens = this.session.getTokens(row); - - var lastLineEl = parent; - if (tokens.length) { - var splits = this.session.getRowSplitData(row); - if (splits && splits.length) { - this.$renderWrappedLine(parent, tokens, splits); - var lastLineEl = parent.lastChild; - } else { - var lastLineEl = parent; - if (this.$useLineGroups()) { - lastLineEl = this.$createLineElement(); - parent.appendChild(lastLineEl); - } - this.$renderSimpleLine(lastLineEl, tokens); - } - } else if (this.$useLineGroups()) { - lastLineEl = this.$createLineElement(); - parent.appendChild(lastLineEl); - } - - if (this.showEOL && lastLineEl) { - if (foldLine) - row = foldLine.end.row; - - var invisibleEl = this.dom.createElement("span"); - invisibleEl.className = "ace_invisible ace_invisible_eol"; - invisibleEl.textContent = row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR; - - lastLineEl.appendChild(invisibleEl); - } - }; - - this.$getFoldLineTokens = function(row, foldLine) { - var session = this.session; - var renderTokens = []; - - function addTokens(tokens, from, to) { - var idx = 0, col = 0; - while ((col + tokens[idx].value.length) < from) { - col += tokens[idx].value.length; - idx++; - - if (idx == tokens.length) - return; - } - if (col != from) { - var value = tokens[idx].value.substring(from - col); - if (value.length > (to - from)) - value = value.substring(0, to - from); - - renderTokens.push({ - type: tokens[idx].type, - value: value - }); - - col = from + value.length; - idx += 1; - } - - while (col < to && idx < tokens.length) { - var value = tokens[idx].value; - if (value.length + col > to) { - renderTokens.push({ - type: tokens[idx].type, - value: value.substring(0, to - col) - }); - } else - renderTokens.push(tokens[idx]); - col += value.length; - idx += 1; - } - } - - var tokens = session.getTokens(row); - foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) { - if (placeholder != null) { - renderTokens.push({ - type: "fold", - value: placeholder - }); - } else { - if (isNewRow) - tokens = session.getTokens(row); - - if (tokens.length) - addTokens(tokens, lastColumn, column); - } - }, foldLine.end.row, this.session.getLine(foldLine.end.row).length); - - return renderTokens; - }; - - this.$useLineGroups = function() { - return this.session.getUseWrapMode(); - }; - - this.destroy = function() {}; -}).call(Text.prototype); - -exports.Text = Text; - -}); - -define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -var dom = require("../lib/dom"); - -var Cursor = function(parentEl) { - this.element = dom.createElement("div"); - this.element.className = "ace_layer ace_cursor-layer"; - parentEl.appendChild(this.element); - - this.isVisible = false; - this.isBlinking = true; - this.blinkInterval = 1000; - this.smoothBlinking = false; - - this.cursors = []; - this.cursor = this.addCursor(); - dom.addCssClass(this.element, "ace_hidden-cursors"); - this.$updateCursors = this.$updateOpacity.bind(this); -}; - -(function() { - - this.$updateOpacity = function(val) { - var cursors = this.cursors; - for (var i = cursors.length; i--; ) - dom.setStyle(cursors[i].style, "opacity", val ? "" : "0"); - }; - - this.$startCssAnimation = function() { - var cursors = this.cursors; - for (var i = cursors.length; i--; ) - cursors[i].style.animationDuration = this.blinkInterval + "ms"; - - this.$isAnimating = true; - setTimeout(function() { - if (this.$isAnimating) { - dom.addCssClass(this.element, "ace_animate-blinking"); - } - }.bind(this)); - }; - - this.$stopCssAnimation = function() { - this.$isAnimating = false; - dom.removeCssClass(this.element, "ace_animate-blinking"); - }; - - this.$padding = 0; - this.setPadding = function(padding) { - this.$padding = padding; - }; - - this.setSession = function(session) { - this.session = session; - }; - - this.setBlinking = function(blinking) { - if (blinking != this.isBlinking) { - this.isBlinking = blinking; - this.restartTimer(); - } - }; - - this.setBlinkInterval = function(blinkInterval) { - if (blinkInterval != this.blinkInterval) { - this.blinkInterval = blinkInterval; - this.restartTimer(); - } - }; - - this.setSmoothBlinking = function(smoothBlinking) { - if (smoothBlinking != this.smoothBlinking) { - this.smoothBlinking = smoothBlinking; - dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking); - this.$updateCursors(true); - this.restartTimer(); - } - }; - - this.addCursor = function() { - var el = dom.createElement("div"); - el.className = "ace_cursor"; - this.element.appendChild(el); - this.cursors.push(el); - return el; - }; - - this.removeCursor = function() { - if (this.cursors.length > 1) { - var el = this.cursors.pop(); - el.parentNode.removeChild(el); - return el; - } - }; - - this.hideCursor = function() { - this.isVisible = false; - dom.addCssClass(this.element, "ace_hidden-cursors"); - this.restartTimer(); - }; - - this.showCursor = function() { - this.isVisible = true; - dom.removeCssClass(this.element, "ace_hidden-cursors"); - this.restartTimer(); - }; - - this.restartTimer = function() { - var update = this.$updateCursors; - clearInterval(this.intervalId); - clearTimeout(this.timeoutId); - this.$stopCssAnimation(); - - if (this.smoothBlinking) { - this.$isSmoothBlinking = false; - dom.removeCssClass(this.element, "ace_smooth-blinking"); - } - - update(true); - - if (!this.isBlinking || !this.blinkInterval || !this.isVisible) { - this.$stopCssAnimation(); - return; - } - - if (this.smoothBlinking) { - this.$isSmoothBlinking = true; - setTimeout(function() { - if (this.$isSmoothBlinking) { - dom.addCssClass(this.element, "ace_smooth-blinking"); - } - }.bind(this)); - } - - if (dom.HAS_CSS_ANIMATION) { - this.$startCssAnimation(); - } else { - var blink = function(){ - this.timeoutId = setTimeout(function() { - update(false); - }, 0.6 * this.blinkInterval); - }.bind(this); - - this.intervalId = setInterval(function() { - update(true); - blink(); - }, this.blinkInterval); - blink(); - } - }; - - this.getPixelPosition = function(position, onScreen) { - if (!this.config || !this.session) - return {left : 0, top : 0}; - - if (!position) - position = this.session.selection.getCursor(); - var pos = this.session.documentToScreenPosition(position); - var cursorLeft = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, position.row) - ? this.session.$bidiHandler.getPosLeft(pos.column) - : pos.column * this.config.characterWidth); - - var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) * - this.config.lineHeight; - - return {left : cursorLeft, top : cursorTop}; - }; - - this.isCursorInView = function(pixelPos, config) { - return pixelPos.top >= 0 && pixelPos.top < config.maxHeight; - }; - - this.update = function(config) { - this.config = config; - - var selections = this.session.$selectionMarkers; - var i = 0, cursorIndex = 0; - - if (selections === undefined || selections.length === 0){ - selections = [{cursor: null}]; - } - - for (var i = 0, n = selections.length; i < n; i++) { - var pixelPos = this.getPixelPosition(selections[i].cursor, true); - if ((pixelPos.top > config.height + config.offset || - pixelPos.top < 0) && i > 1) { - continue; - } - - var element = this.cursors[cursorIndex++] || this.addCursor(); - var style = element.style; - - if (!this.drawCursor) { - if (!this.isCursorInView(pixelPos, config)) { - dom.setStyle(style, "display", "none"); - } else { - dom.setStyle(style, "display", "block"); - dom.translate(element, pixelPos.left, pixelPos.top); - dom.setStyle(style, "width", Math.round(config.characterWidth) + "px"); - dom.setStyle(style, "height", config.lineHeight + "px"); - } - } else { - this.drawCursor(element, pixelPos, config, selections[i], this.session); - } - } - while (this.cursors.length > cursorIndex) - this.removeCursor(); - - var overwrite = this.session.getOverwrite(); - this.$setOverwrite(overwrite); - this.$pixelPos = pixelPos; - this.restartTimer(); - }; - - this.drawCursor = null; - - this.$setOverwrite = function(overwrite) { - if (overwrite != this.overwrite) { - this.overwrite = overwrite; - if (overwrite) - dom.addCssClass(this.element, "ace_overwrite-cursors"); - else - dom.removeCssClass(this.element, "ace_overwrite-cursors"); - } - }; - - this.destroy = function() { - clearInterval(this.intervalId); - clearTimeout(this.timeoutId); - }; - -}).call(Cursor.prototype); - -exports.Cursor = Cursor; - -}); - -define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var dom = require("./lib/dom"); -var event = require("./lib/event"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var MAX_SCROLL_H = 0x8000; -var ScrollBar = function(parent) { - this.element = dom.createElement("div"); - this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix; - - this.inner = dom.createElement("div"); - this.inner.className = "ace_scrollbar-inner"; - this.inner.textContent = "\xa0"; - this.element.appendChild(this.inner); - - parent.appendChild(this.element); - - this.setVisible(false); - this.skipEvent = false; - - event.addListener(this.element, "scroll", this.onScroll.bind(this)); - event.addListener(this.element, "mousedown", event.preventDefault); -}; - -(function() { - oop.implement(this, EventEmitter); - - this.setVisible = function(isVisible) { - this.element.style.display = isVisible ? "" : "none"; - this.isVisible = isVisible; - this.coeff = 1; - }; -}).call(ScrollBar.prototype); -var VScrollBar = function(parent, renderer) { - ScrollBar.call(this, parent); - this.scrollTop = 0; - this.scrollHeight = 0; - renderer.$scrollbarWidth = - this.width = dom.scrollbarWidth(parent.ownerDocument); - this.inner.style.width = - this.element.style.width = (this.width || 15) + 5 + "px"; - this.$minWidth = 0; -}; - -oop.inherits(VScrollBar, ScrollBar); - -(function() { - - this.classSuffix = '-v'; - this.onScroll = function() { - if (!this.skipEvent) { - this.scrollTop = this.element.scrollTop; - if (this.coeff != 1) { - var h = this.element.clientHeight / this.scrollHeight; - this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h); - } - this._emit("scroll", {data: this.scrollTop}); - } - this.skipEvent = false; - }; - this.getWidth = function() { - return Math.max(this.isVisible ? this.width : 0, this.$minWidth || 0); - }; - this.setHeight = function(height) { - this.element.style.height = height + "px"; - }; - this.setInnerHeight = - this.setScrollHeight = function(height) { - this.scrollHeight = height; - if (height > MAX_SCROLL_H) { - this.coeff = MAX_SCROLL_H / height; - height = MAX_SCROLL_H; - } else if (this.coeff != 1) { - this.coeff = 1; - } - this.inner.style.height = height + "px"; - }; - this.setScrollTop = function(scrollTop) { - if (this.scrollTop != scrollTop) { - this.skipEvent = true; - this.scrollTop = scrollTop; - this.element.scrollTop = scrollTop * this.coeff; - } - }; - -}).call(VScrollBar.prototype); -var HScrollBar = function(parent, renderer) { - ScrollBar.call(this, parent); - this.scrollLeft = 0; - this.height = renderer.$scrollbarWidth; - this.inner.style.height = - this.element.style.height = (this.height || 15) + 5 + "px"; -}; - -oop.inherits(HScrollBar, ScrollBar); - -(function() { - - this.classSuffix = '-h'; - this.onScroll = function() { - if (!this.skipEvent) { - this.scrollLeft = this.element.scrollLeft; - this._emit("scroll", {data: this.scrollLeft}); - } - this.skipEvent = false; - }; - this.getHeight = function() { - return this.isVisible ? this.height : 0; - }; - this.setWidth = function(width) { - this.element.style.width = width + "px"; - }; - this.setInnerWidth = function(width) { - this.inner.style.width = width + "px"; - }; - this.setScrollWidth = function(width) { - this.inner.style.width = width + "px"; - }; - this.setScrollLeft = function(scrollLeft) { - if (this.scrollLeft != scrollLeft) { - this.skipEvent = true; - this.scrollLeft = this.element.scrollLeft = scrollLeft; - } - }; - -}).call(HScrollBar.prototype); - - -exports.ScrollBar = VScrollBar; // backward compatibility -exports.ScrollBarV = VScrollBar; // backward compatibility -exports.ScrollBarH = HScrollBar; // backward compatibility - -exports.VScrollBar = VScrollBar; -exports.HScrollBar = HScrollBar; -}); - -define("ace/renderloop",["require","exports","module","ace/lib/event"], function(require, exports, module) { -"use strict"; - -var event = require("./lib/event"); - - -var RenderLoop = function(onRender, win) { - this.onRender = onRender; - this.pending = false; - this.changes = 0; - this.$recursionLimit = 2; - this.window = win || window; - var _self = this; - this._flush = function(ts) { - _self.pending = false; - var changes = _self.changes; - - if (changes) { - event.blockIdle(100); - _self.changes = 0; - _self.onRender(changes); - } - - if (_self.changes) { - if (_self.$recursionLimit-- < 0) return; - _self.schedule(); - } else { - _self.$recursionLimit = 2; - } - }; -}; - -(function() { - - this.schedule = function(change) { - this.changes = this.changes | change; - if (this.changes && !this.pending) { - event.nextFrame(this._flush); - this.pending = true; - } - }; - - this.clear = function(change) { - var changes = this.changes; - this.changes = 0; - return changes; - }; - -}).call(RenderLoop.prototype); - -exports.RenderLoop = RenderLoop; -}); - -define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/event","ace/lib/useragent","ace/lib/event_emitter"], function(require, exports, module) { - -var oop = require("../lib/oop"); -var dom = require("../lib/dom"); -var lang = require("../lib/lang"); -var event = require("../lib/event"); -var useragent = require("../lib/useragent"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var CHAR_COUNT = 256; -var USE_OBSERVER = typeof ResizeObserver == "function"; -var L = 200; - -var FontMetrics = exports.FontMetrics = function(parentEl) { - this.el = dom.createElement("div"); - this.$setMeasureNodeStyles(this.el.style, true); - - this.$main = dom.createElement("div"); - this.$setMeasureNodeStyles(this.$main.style); - - this.$measureNode = dom.createElement("div"); - this.$setMeasureNodeStyles(this.$measureNode.style); - - - this.el.appendChild(this.$main); - this.el.appendChild(this.$measureNode); - parentEl.appendChild(this.el); - - this.$measureNode.textContent = lang.stringRepeat("X", CHAR_COUNT); - - this.$characterSize = {width: 0, height: 0}; - - - if (USE_OBSERVER) - this.$addObserver(); - else - this.checkForSizeChanges(); -}; - -(function() { - - oop.implement(this, EventEmitter); - - this.$characterSize = {width: 0, height: 0}; - - this.$setMeasureNodeStyles = function(style, isRoot) { - style.width = style.height = "auto"; - style.left = style.top = "0px"; - style.visibility = "hidden"; - style.position = "absolute"; - style.whiteSpace = "pre"; - - if (useragent.isIE < 8) { - style["font-family"] = "inherit"; - } else { - style.font = "inherit"; - } - style.overflow = isRoot ? "hidden" : "visible"; - }; - - this.checkForSizeChanges = function(size) { - if (size === undefined) - size = this.$measureSizes(); - if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { - this.$measureNode.style.fontWeight = "bold"; - var boldSize = this.$measureSizes(); - this.$measureNode.style.fontWeight = ""; - this.$characterSize = size; - this.charSizes = Object.create(null); - this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height; - this._emit("changeCharacterSize", {data: size}); - } - }; - - this.$addObserver = function() { - var self = this; - this.$observer = new window.ResizeObserver(function(e) { - self.checkForSizeChanges(); - }); - this.$observer.observe(this.$measureNode); - }; - - this.$pollSizeChanges = function() { - if (this.$pollSizeChangesTimer || this.$observer) - return this.$pollSizeChangesTimer; - var self = this; - - return this.$pollSizeChangesTimer = event.onIdle(function cb() { - self.checkForSizeChanges(); - event.onIdle(cb, 500); - }, 500); - }; - - this.setPolling = function(val) { - if (val) { - this.$pollSizeChanges(); - } else if (this.$pollSizeChangesTimer) { - clearInterval(this.$pollSizeChangesTimer); - this.$pollSizeChangesTimer = 0; - } - }; - - this.$measureSizes = function(node) { - var size = { - height: (node || this.$measureNode).clientHeight, - width: (node || this.$measureNode).clientWidth / CHAR_COUNT - }; - if (size.width === 0 || size.height === 0) - return null; - return size; - }; - - this.$measureCharWidth = function(ch) { - this.$main.textContent = lang.stringRepeat(ch, CHAR_COUNT); - var rect = this.$main.getBoundingClientRect(); - return rect.width / CHAR_COUNT; - }; - - this.getCharacterWidth = function(ch) { - var w = this.charSizes[ch]; - if (w === undefined) { - w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width; - } - return w; - }; - - this.destroy = function() { - clearInterval(this.$pollSizeChangesTimer); - if (this.$observer) - this.$observer.disconnect(); - if (this.el && this.el.parentNode) - this.el.parentNode.removeChild(this.el); - }; - - - this.$getZoom = function getZoom(element) { - if (!element || !element.parentElement) return 1; - return (window.getComputedStyle(element).zoom || 1) * getZoom(element.parentElement); - }; - this.$initTransformMeasureNodes = function() { - var t = function(t, l) { - return ["div", { - style: "position: absolute;top:" + t + "px;left:" + l + "px;" - }]; - }; - this.els = dom.buildDom([t(0, 0), t(L, 0), t(0, L), t(L, L)], this.el); - }; - this.transformCoordinates = function(clientPos, elPos) { - if (clientPos) { - var zoom = this.$getZoom(this.el); - clientPos = mul(1 / zoom, clientPos); - } - function solve(l1, l2, r) { - var det = l1[1] * l2[0] - l1[0] * l2[1]; - return [ - (-l2[1] * r[0] + l2[0] * r[1]) / det, - (+l1[1] * r[0] - l1[0] * r[1]) / det - ]; - } - function sub(a, b) { return [a[0] - b[0], a[1] - b[1]]; } - function add(a, b) { return [a[0] + b[0], a[1] + b[1]]; } - function mul(a, b) { return [a * b[0], a * b[1]]; } - - if (!this.els) - this.$initTransformMeasureNodes(); - - function p(el) { - var r = el.getBoundingClientRect(); - return [r.left, r.top]; - } - - var a = p(this.els[0]); - var b = p(this.els[1]); - var c = p(this.els[2]); - var d = p(this.els[3]); - - var h = solve(sub(d, b), sub(d, c), sub(add(b, c), add(d, a))); - - var m1 = mul(1 + h[0], sub(b, a)); - var m2 = mul(1 + h[1], sub(c, a)); - - if (elPos) { - var x = elPos; - var k = h[0] * x[0] / L + h[1] * x[1] / L + 1; - var ut = add(mul(x[0], m1), mul(x[1], m2)); - return add(mul(1 / k / L, ut), a); - } - var u = sub(clientPos, a); - var f = solve(sub(m1, mul(h[0], u)), sub(m2, mul(h[1], u)), u); - return mul(L, f); - }; - -}).call(FontMetrics.prototype); - -}); - -define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter","ace/lib/useragent"], function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var dom = require("./lib/dom"); -var config = require("./config"); -var GutterLayer = require("./layer/gutter").Gutter; -var MarkerLayer = require("./layer/marker").Marker; -var TextLayer = require("./layer/text").Text; -var CursorLayer = require("./layer/cursor").Cursor; -var HScrollBar = require("./scrollbar").HScrollBar; -var VScrollBar = require("./scrollbar").VScrollBar; -var RenderLoop = require("./renderloop").RenderLoop; -var FontMetrics = require("./layer/font_metrics").FontMetrics; -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var editorCss = "\ -.ace_br1 {border-top-left-radius : 3px;}\ -.ace_br2 {border-top-right-radius : 3px;}\ -.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\ -.ace_br4 {border-bottom-right-radius: 3px;}\ -.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\ -.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\ -.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\ -.ace_br8 {border-bottom-left-radius : 3px;}\ -.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\ -.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\ -.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_editor {\ -position: relative;\ -overflow: hidden;\ -padding: 0;\ -font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\ -direction: ltr;\ -text-align: left;\ --webkit-tap-highlight-color: rgba(0, 0, 0, 0);\ -}\ -.ace_scroller {\ -position: absolute;\ -overflow: hidden;\ -top: 0;\ -bottom: 0;\ -background-color: inherit;\ --ms-user-select: none;\ --moz-user-select: none;\ --webkit-user-select: none;\ -user-select: none;\ -cursor: text;\ -}\ -.ace_content {\ -position: absolute;\ -box-sizing: border-box;\ -min-width: 100%;\ -contain: style size layout;\ -font-variant-ligatures: no-common-ligatures;\ -}\ -.ace_dragging .ace_scroller:before{\ -position: absolute;\ -top: 0;\ -left: 0;\ -right: 0;\ -bottom: 0;\ -content: '';\ -background: rgba(250, 250, 250, 0.01);\ -z-index: 1000;\ -}\ -.ace_dragging.ace_dark .ace_scroller:before{\ -background: rgba(0, 0, 0, 0.01);\ -}\ -.ace_selecting, .ace_selecting * {\ -cursor: text !important;\ -}\ -.ace_gutter {\ -position: absolute;\ -overflow : hidden;\ -width: auto;\ -top: 0;\ -bottom: 0;\ -left: 0;\ -cursor: default;\ -z-index: 4;\ --ms-user-select: none;\ --moz-user-select: none;\ --webkit-user-select: none;\ -user-select: none;\ -contain: style size layout;\ -}\ -.ace_gutter-active-line {\ -position: absolute;\ -left: 0;\ -right: 0;\ -}\ -.ace_scroller.ace_scroll-left {\ -box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\ -}\ -.ace_gutter-cell {\ -position: absolute;\ -top: 0;\ -left: 0;\ -right: 0;\ -padding-left: 19px;\ -padding-right: 6px;\ -background-repeat: no-repeat;\ -}\ -.ace_gutter-cell.ace_error {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\ -background-repeat: no-repeat;\ -background-position: 2px center;\ -}\ -.ace_gutter-cell.ace_warning {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\ -background-position: 2px center;\ -}\ -.ace_gutter-cell.ace_info {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\ -background-position: 2px center;\ -}\ -.ace_dark .ace_gutter-cell.ace_info {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\ -}\ -.ace_scrollbar {\ -contain: strict;\ -position: absolute;\ -right: 0;\ -bottom: 0;\ -z-index: 6;\ -}\ -.ace_scrollbar-inner {\ -position: absolute;\ -cursor: text;\ -left: 0;\ -top: 0;\ -}\ -.ace_scrollbar-v{\ -overflow-x: hidden;\ -overflow-y: scroll;\ -top: 0;\ -}\ -.ace_scrollbar-h {\ -overflow-x: scroll;\ -overflow-y: hidden;\ -left: 0;\ -}\ -.ace_print-margin {\ -position: absolute;\ -height: 100%;\ -}\ -.ace_text-input {\ -position: absolute;\ -z-index: 0;\ -width: 0.5em;\ -height: 1em;\ -opacity: 0;\ -background: transparent;\ --moz-appearance: none;\ -appearance: none;\ -border: none;\ -resize: none;\ -outline: none;\ -overflow: hidden;\ -font: inherit;\ -padding: 0 1px;\ -margin: 0 -1px;\ -contain: strict;\ --ms-user-select: text;\ --moz-user-select: text;\ --webkit-user-select: text;\ -user-select: text;\ -white-space: pre!important;\ -}\ -.ace_text-input.ace_composition {\ -background: transparent;\ -color: inherit;\ -z-index: 1000;\ -opacity: 1;\ -}\ -.ace_composition_placeholder { color: transparent }\ -.ace_composition_marker { \ -border-bottom: 1px solid;\ -position: absolute;\ -border-radius: 0;\ -margin-top: 1px;\ -}\ -[ace_nocontext=true] {\ -transform: none!important;\ -filter: none!important;\ -clip-path: none!important;\ -mask : none!important;\ -contain: none!important;\ -perspective: none!important;\ -mix-blend-mode: initial!important;\ -z-index: auto;\ -}\ -.ace_layer {\ -z-index: 1;\ -position: absolute;\ -overflow: hidden;\ -word-wrap: normal;\ -white-space: pre;\ -height: 100%;\ -width: 100%;\ -box-sizing: border-box;\ -pointer-events: none;\ -}\ -.ace_gutter-layer {\ -position: relative;\ -width: auto;\ -text-align: right;\ -pointer-events: auto;\ -height: 1000000px;\ -contain: style size layout;\ -}\ -.ace_text-layer {\ -font: inherit !important;\ -position: absolute;\ -height: 1000000px;\ -width: 1000000px;\ -contain: style size layout;\ -}\ -.ace_text-layer > .ace_line, .ace_text-layer > .ace_line_group {\ -contain: style size layout;\ -position: absolute;\ -top: 0;\ -left: 0;\ -right: 0;\ -}\ -.ace_hidpi .ace_text-layer,\ -.ace_hidpi .ace_gutter-layer,\ -.ace_hidpi .ace_content,\ -.ace_hidpi .ace_gutter {\ -contain: strict;\ -will-change: transform;\ -}\ -.ace_hidpi .ace_text-layer > .ace_line, \ -.ace_hidpi .ace_text-layer > .ace_line_group {\ -contain: strict;\ -}\ -.ace_cjk {\ -display: inline-block;\ -text-align: center;\ -}\ -.ace_cursor-layer {\ -z-index: 4;\ -}\ -.ace_cursor {\ -z-index: 4;\ -position: absolute;\ -box-sizing: border-box;\ -border-left: 2px solid;\ -transform: translatez(0);\ -}\ -.ace_multiselect .ace_cursor {\ -border-left-width: 1px;\ -}\ -.ace_slim-cursors .ace_cursor {\ -border-left-width: 1px;\ -}\ -.ace_overwrite-cursors .ace_cursor {\ -border-left-width: 0;\ -border-bottom: 1px solid;\ -}\ -.ace_hidden-cursors .ace_cursor {\ -opacity: 0.2;\ -}\ -.ace_hasPlaceholder .ace_hidden-cursors .ace_cursor {\ -opacity: 0;\ -}\ -.ace_smooth-blinking .ace_cursor {\ -transition: opacity 0.18s;\ -}\ -.ace_animate-blinking .ace_cursor {\ -animation-duration: 1000ms;\ -animation-timing-function: step-end;\ -animation-name: blink-ace-animate;\ -animation-iteration-count: infinite;\ -}\ -.ace_animate-blinking.ace_smooth-blinking .ace_cursor {\ -animation-duration: 1000ms;\ -animation-timing-function: ease-in-out;\ -animation-name: blink-ace-animate-smooth;\ -}\ -@keyframes blink-ace-animate {\ -from, to { opacity: 1; }\ -60% { opacity: 0; }\ -}\ -@keyframes blink-ace-animate-smooth {\ -from, to { opacity: 1; }\ -45% { opacity: 1; }\ -60% { opacity: 0; }\ -85% { opacity: 0; }\ -}\ -.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\ -position: absolute;\ -z-index: 3;\ -}\ -.ace_marker-layer .ace_selection {\ -position: absolute;\ -z-index: 5;\ -}\ -.ace_marker-layer .ace_bracket {\ -position: absolute;\ -z-index: 6;\ -}\ -.ace_marker-layer .ace_error_bracket {\ -position: absolute;\ -border-bottom: 1px solid #DE5555;\ -border-radius: 0;\ -}\ -.ace_marker-layer .ace_active-line {\ -position: absolute;\ -z-index: 2;\ -}\ -.ace_marker-layer .ace_selected-word {\ -position: absolute;\ -z-index: 4;\ -box-sizing: border-box;\ -}\ -.ace_line .ace_fold {\ -box-sizing: border-box;\ -display: inline-block;\ -height: 11px;\ -margin-top: -2px;\ -vertical-align: middle;\ -background-image:\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\ -background-repeat: no-repeat, repeat-x;\ -background-position: center center, top left;\ -color: transparent;\ -border: 1px solid black;\ -border-radius: 2px;\ -cursor: pointer;\ -pointer-events: auto;\ -}\ -.ace_dark .ace_fold {\ -}\ -.ace_fold:hover{\ -background-image:\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\ -}\ -.ace_tooltip {\ -background-color: #FFF;\ -background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\ -border: 1px solid gray;\ -border-radius: 1px;\ -box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\ -color: black;\ -max-width: 100%;\ -padding: 3px 4px;\ -position: fixed;\ -z-index: 999999;\ -box-sizing: border-box;\ -cursor: default;\ -white-space: pre;\ -word-wrap: break-word;\ -line-height: normal;\ -font-style: normal;\ -font-weight: normal;\ -letter-spacing: normal;\ -pointer-events: none;\ -}\ -.ace_folding-enabled > .ace_gutter-cell {\ -padding-right: 13px;\ -}\ -.ace_fold-widget {\ -box-sizing: border-box;\ -margin: 0 -12px 0 1px;\ -display: none;\ -width: 11px;\ -vertical-align: top;\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\ -background-repeat: no-repeat;\ -background-position: center;\ -border-radius: 3px;\ -border: 1px solid transparent;\ -cursor: pointer;\ -}\ -.ace_folding-enabled .ace_fold-widget {\ -display: inline-block; \ -}\ -.ace_fold-widget.ace_end {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\ -}\ -.ace_fold-widget.ace_closed {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\ -}\ -.ace_fold-widget:hover {\ -border: 1px solid rgba(0, 0, 0, 0.3);\ -background-color: rgba(255, 255, 255, 0.2);\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\ -}\ -.ace_fold-widget:active {\ -border: 1px solid rgba(0, 0, 0, 0.4);\ -background-color: rgba(0, 0, 0, 0.05);\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\ -}\ -.ace_dark .ace_fold-widget {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\ -}\ -.ace_dark .ace_fold-widget.ace_end {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\ -}\ -.ace_dark .ace_fold-widget.ace_closed {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\ -}\ -.ace_dark .ace_fold-widget:hover {\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ -background-color: rgba(255, 255, 255, 0.1);\ -}\ -.ace_dark .ace_fold-widget:active {\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ -}\ -.ace_inline_button {\ -border: 1px solid lightgray;\ -display: inline-block;\ -margin: -1px 8px;\ -padding: 0 5px;\ -pointer-events: auto;\ -cursor: pointer;\ -}\ -.ace_inline_button:hover {\ -border-color: gray;\ -background: rgba(200,200,200,0.2);\ -display: inline-block;\ -pointer-events: auto;\ -}\ -.ace_fold-widget.ace_invalid {\ -background-color: #FFB4B4;\ -border-color: #DE5555;\ -}\ -.ace_fade-fold-widgets .ace_fold-widget {\ -transition: opacity 0.4s ease 0.05s;\ -opacity: 0;\ -}\ -.ace_fade-fold-widgets:hover .ace_fold-widget {\ -transition: opacity 0.05s ease 0.05s;\ -opacity:1;\ -}\ -.ace_underline {\ -text-decoration: underline;\ -}\ -.ace_bold {\ -font-weight: bold;\ -}\ -.ace_nobold .ace_bold {\ -font-weight: normal;\ -}\ -.ace_italic {\ -font-style: italic;\ -}\ -.ace_error-marker {\ -background-color: rgba(255, 0, 0,0.2);\ -position: absolute;\ -z-index: 9;\ -}\ -.ace_highlight-marker {\ -background-color: rgba(255, 255, 0,0.2);\ -position: absolute;\ -z-index: 8;\ -}\ -.ace_mobile-menu {\ -position: absolute;\ -line-height: 1.5;\ -border-radius: 4px;\ --ms-user-select: none;\ --moz-user-select: none;\ --webkit-user-select: none;\ -user-select: none;\ -background: white;\ -box-shadow: 1px 3px 2px grey;\ -border: 1px solid #dcdcdc;\ -color: black;\ -}\ -.ace_dark > .ace_mobile-menu {\ -background: #333;\ -color: #ccc;\ -box-shadow: 1px 3px 2px grey;\ -border: 1px solid #444;\ -}\ -.ace_mobile-button {\ -padding: 2px;\ -cursor: pointer;\ -overflow: hidden;\ -}\ -.ace_mobile-button:hover {\ -background-color: #eee;\ -opacity:1;\ -}\ -.ace_mobile-button:active {\ -background-color: #ddd;\ -}\ -.ace_placeholder {\ -font-family: arial;\ -transform: scale(0.9);\ -transform-origin: left;\ -white-space: pre;\ -opacity: 0.7;\ -margin: 0 10px;\ -}"; - -var useragent = require("./lib/useragent"); -var HIDE_TEXTAREA = useragent.isIE; - -dom.importCssString(editorCss, "ace_editor.css", false); - -var VirtualRenderer = function(container, theme) { - var _self = this; - - this.container = container || dom.createElement("div"); - - dom.addCssClass(this.container, "ace_editor"); - if (dom.HI_DPI) dom.addCssClass(this.container, "ace_hidpi"); - - this.setTheme(theme); - if (config.get("useStrictCSP") == null) - config.set("useStrictCSP", false); - - this.$gutter = dom.createElement("div"); - this.$gutter.className = "ace_gutter"; - this.container.appendChild(this.$gutter); - this.$gutter.setAttribute("aria-hidden", true); - - this.scroller = dom.createElement("div"); - this.scroller.className = "ace_scroller"; - - this.container.appendChild(this.scroller); - - this.content = dom.createElement("div"); - this.content.className = "ace_content"; - this.scroller.appendChild(this.content); - - this.$gutterLayer = new GutterLayer(this.$gutter); - this.$gutterLayer.on("changeGutterWidth", this.onGutterResize.bind(this)); - - this.$markerBack = new MarkerLayer(this.content); - - var textLayer = this.$textLayer = new TextLayer(this.content); - this.canvas = textLayer.element; - - this.$markerFront = new MarkerLayer(this.content); - - this.$cursorLayer = new CursorLayer(this.content); - this.$horizScroll = false; - this.$vScroll = false; - - this.scrollBar = - this.scrollBarV = new VScrollBar(this.container, this); - this.scrollBarH = new HScrollBar(this.container, this); - this.scrollBarV.on("scroll", function(e) { - if (!_self.$scrollAnimation) - _self.session.setScrollTop(e.data - _self.scrollMargin.top); - }); - this.scrollBarH.on("scroll", function(e) { - if (!_self.$scrollAnimation) - _self.session.setScrollLeft(e.data - _self.scrollMargin.left); - }); - - this.scrollTop = 0; - this.scrollLeft = 0; - - this.cursorPos = { - row : 0, - column : 0 - }; - - this.$fontMetrics = new FontMetrics(this.container); - this.$textLayer.$setFontMetrics(this.$fontMetrics); - this.$textLayer.on("changeCharacterSize", function(e) { - _self.updateCharacterSize(); - _self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height); - _self._signal("changeCharacterSize", e); - }); - - this.$size = { - width: 0, - height: 0, - scrollerHeight: 0, - scrollerWidth: 0, - $dirty: true - }; - - this.layerConfig = { - width : 1, - padding : 0, - firstRow : 0, - firstRowScreen: 0, - lastRow : 0, - lineHeight : 0, - characterWidth : 0, - minHeight : 1, - maxHeight : 1, - offset : 0, - height : 1, - gutterOffset: 1 - }; - - this.scrollMargin = { - left: 0, - right: 0, - top: 0, - bottom: 0, - v: 0, - h: 0 - }; - - this.margin = { - left: 0, - right: 0, - top: 0, - bottom: 0, - v: 0, - h: 0 - }; - - this.$keepTextAreaAtCursor = !useragent.isIOS; - - this.$loop = new RenderLoop( - this.$renderChanges.bind(this), - this.container.ownerDocument.defaultView - ); - this.$loop.schedule(this.CHANGE_FULL); - - this.updateCharacterSize(); - this.setPadding(4); - config.resetOptions(this); - config._signal("renderer", this); -}; - -(function() { - - this.CHANGE_CURSOR = 1; - this.CHANGE_MARKER = 2; - this.CHANGE_GUTTER = 4; - this.CHANGE_SCROLL = 8; - this.CHANGE_LINES = 16; - this.CHANGE_TEXT = 32; - this.CHANGE_SIZE = 64; - this.CHANGE_MARKER_BACK = 128; - this.CHANGE_MARKER_FRONT = 256; - this.CHANGE_FULL = 512; - this.CHANGE_H_SCROLL = 1024; - - oop.implement(this, EventEmitter); - - this.updateCharacterSize = function() { - if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) { - this.$allowBoldFonts = this.$textLayer.allowBoldFonts; - this.setStyle("ace_nobold", !this.$allowBoldFonts); - } - - this.layerConfig.characterWidth = - this.characterWidth = this.$textLayer.getCharacterWidth(); - this.layerConfig.lineHeight = - this.lineHeight = this.$textLayer.getLineHeight(); - this.$updatePrintMargin(); - dom.setStyle(this.scroller.style, "line-height", this.lineHeight + "px"); - }; - this.setSession = function(session) { - if (this.session) - this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode); - - this.session = session; - if (session && this.scrollMargin.top && session.getScrollTop() <= 0) - session.setScrollTop(-this.scrollMargin.top); - - this.$cursorLayer.setSession(session); - this.$markerBack.setSession(session); - this.$markerFront.setSession(session); - this.$gutterLayer.setSession(session); - this.$textLayer.setSession(session); - if (!session) - return; - - this.$loop.schedule(this.CHANGE_FULL); - this.session.$setFontMetrics(this.$fontMetrics); - this.scrollBarH.scrollLeft = this.scrollBarV.scrollTop = null; - - this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this); - this.onChangeNewLineMode(); - this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode); - }; - this.updateLines = function(firstRow, lastRow, force) { - if (lastRow === undefined) - lastRow = Infinity; - - if (!this.$changedLines) { - this.$changedLines = { - firstRow: firstRow, - lastRow: lastRow - }; - } - else { - if (this.$changedLines.firstRow > firstRow) - this.$changedLines.firstRow = firstRow; - - if (this.$changedLines.lastRow < lastRow) - this.$changedLines.lastRow = lastRow; - } - if (this.$changedLines.lastRow < this.layerConfig.firstRow) { - if (force) - this.$changedLines.lastRow = this.layerConfig.lastRow; - else - return; - } - if (this.$changedLines.firstRow > this.layerConfig.lastRow) - return; - this.$loop.schedule(this.CHANGE_LINES); - }; - - this.onChangeNewLineMode = function() { - this.$loop.schedule(this.CHANGE_TEXT); - this.$textLayer.$updateEolChar(); - this.session.$bidiHandler.setEolChar(this.$textLayer.EOL_CHAR); - }; - - this.onChangeTabSize = function() { - this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER); - this.$textLayer.onChangeTabSize(); - }; - this.updateText = function() { - this.$loop.schedule(this.CHANGE_TEXT); - }; - this.updateFull = function(force) { - if (force) - this.$renderChanges(this.CHANGE_FULL, true); - else - this.$loop.schedule(this.CHANGE_FULL); - }; - this.updateFontSize = function() { - this.$textLayer.checkForSizeChanges(); - }; - - this.$changes = 0; - this.$updateSizeAsync = function() { - if (this.$loop.pending) - this.$size.$dirty = true; - else - this.onResize(); - }; - this.onResize = function(force, gutterWidth, width, height) { - if (this.resizing > 2) - return; - else if (this.resizing > 0) - this.resizing++; - else - this.resizing = force ? 1 : 0; - var el = this.container; - if (!height) - height = el.clientHeight || el.scrollHeight; - if (!width) - width = el.clientWidth || el.scrollWidth; - var changes = this.$updateCachedSize(force, gutterWidth, width, height); - - - if (!this.$size.scrollerHeight || (!width && !height)) - return this.resizing = 0; - - if (force) - this.$gutterLayer.$padding = null; - - if (force) - this.$renderChanges(changes | this.$changes, true); - else - this.$loop.schedule(changes | this.$changes); - - if (this.resizing) - this.resizing = 0; - this.scrollBarH.scrollLeft = this.scrollBarV.scrollTop = null; - }; - - this.$updateCachedSize = function(force, gutterWidth, width, height) { - height -= (this.$extraHeight || 0); - var changes = 0; - var size = this.$size; - var oldSize = { - width: size.width, - height: size.height, - scrollerHeight: size.scrollerHeight, - scrollerWidth: size.scrollerWidth - }; - if (height && (force || size.height != height)) { - size.height = height; - changes |= this.CHANGE_SIZE; - - size.scrollerHeight = size.height; - if (this.$horizScroll) - size.scrollerHeight -= this.scrollBarH.getHeight(); - this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px"; - - changes = changes | this.CHANGE_SCROLL; - } - - if (width && (force || size.width != width)) { - changes |= this.CHANGE_SIZE; - size.width = width; - - if (gutterWidth == null) - gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; - - this.gutterWidth = gutterWidth; - - dom.setStyle(this.scrollBarH.element.style, "left", gutterWidth + "px"); - dom.setStyle(this.scroller.style, "left", gutterWidth + this.margin.left + "px"); - size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth() - this.margin.h); - dom.setStyle(this.$gutter.style, "left", this.margin.left + "px"); - - var right = this.scrollBarV.getWidth() + "px"; - dom.setStyle(this.scrollBarH.element.style, "right", right); - dom.setStyle(this.scroller.style, "right", right); - dom.setStyle(this.scroller.style, "bottom", this.scrollBarH.getHeight()); - - if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force) { - changes |= this.CHANGE_FULL; - } - } - - size.$dirty = !width || !height; - - if (changes) - this._signal("resize", oldSize); - - return changes; - }; - - this.onGutterResize = function(width) { - var gutterWidth = this.$showGutter ? width : 0; - if (gutterWidth != this.gutterWidth) - this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height); - - if (this.session.getUseWrapMode() && this.adjustWrapLimit()) { - this.$loop.schedule(this.CHANGE_FULL); - } else if (this.$size.$dirty) { - this.$loop.schedule(this.CHANGE_FULL); - } else { - this.$computeLayerConfig(); - } - }; - this.adjustWrapLimit = function() { - var availableWidth = this.$size.scrollerWidth - this.$padding * 2; - var limit = Math.floor(availableWidth / this.characterWidth); - return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn); - }; - this.setAnimatedScroll = function(shouldAnimate){ - this.setOption("animatedScroll", shouldAnimate); - }; - this.getAnimatedScroll = function() { - return this.$animatedScroll; - }; - this.setShowInvisibles = function(showInvisibles) { - this.setOption("showInvisibles", showInvisibles); - this.session.$bidiHandler.setShowInvisibles(showInvisibles); - }; - this.getShowInvisibles = function() { - return this.getOption("showInvisibles"); - }; - this.getDisplayIndentGuides = function() { - return this.getOption("displayIndentGuides"); - }; - - this.setDisplayIndentGuides = function(display) { - this.setOption("displayIndentGuides", display); - }; - this.setShowPrintMargin = function(showPrintMargin) { - this.setOption("showPrintMargin", showPrintMargin); - }; - this.getShowPrintMargin = function() { - return this.getOption("showPrintMargin"); - }; - this.setPrintMarginColumn = function(showPrintMargin) { - this.setOption("printMarginColumn", showPrintMargin); - }; - this.getPrintMarginColumn = function() { - return this.getOption("printMarginColumn"); - }; - this.getShowGutter = function(){ - return this.getOption("showGutter"); - }; - this.setShowGutter = function(show){ - return this.setOption("showGutter", show); - }; - - this.getFadeFoldWidgets = function(){ - return this.getOption("fadeFoldWidgets"); - }; - - this.setFadeFoldWidgets = function(show) { - this.setOption("fadeFoldWidgets", show); - }; - - this.setHighlightGutterLine = function(shouldHighlight) { - this.setOption("highlightGutterLine", shouldHighlight); - }; - - this.getHighlightGutterLine = function() { - return this.getOption("highlightGutterLine"); - }; - - this.$updatePrintMargin = function() { - if (!this.$showPrintMargin && !this.$printMarginEl) - return; - - if (!this.$printMarginEl) { - var containerEl = dom.createElement("div"); - containerEl.className = "ace_layer ace_print-margin-layer"; - this.$printMarginEl = dom.createElement("div"); - this.$printMarginEl.className = "ace_print-margin"; - containerEl.appendChild(this.$printMarginEl); - this.content.insertBefore(containerEl, this.content.firstChild); - } - - var style = this.$printMarginEl.style; - style.left = Math.round(this.characterWidth * this.$printMarginColumn + this.$padding) + "px"; - style.visibility = this.$showPrintMargin ? "visible" : "hidden"; - - if (this.session && this.session.$wrap == -1) - this.adjustWrapLimit(); - }; - this.getContainerElement = function() { - return this.container; - }; - this.getMouseEventTarget = function() { - return this.scroller; - }; - this.getTextAreaContainer = function() { - return this.container; - }; - this.$moveTextAreaToCursor = function() { - if (this.$isMousePressed) return; - var style = this.textarea.style; - var composition = this.$composition; - if (!this.$keepTextAreaAtCursor && !composition) { - dom.translate(this.textarea, -100, 0); - return; - } - var pixelPos = this.$cursorLayer.$pixelPos; - if (!pixelPos) - return; - if (composition && composition.markerRange) - pixelPos = this.$cursorLayer.getPixelPosition(composition.markerRange.start, true); - - var config = this.layerConfig; - var posTop = pixelPos.top; - var posLeft = pixelPos.left; - posTop -= config.offset; - - var h = composition && composition.useTextareaForIME ? this.lineHeight : HIDE_TEXTAREA ? 0 : 1; - if (posTop < 0 || posTop > config.height - h) { - dom.translate(this.textarea, 0, 0); - return; - } - - var w = 1; - var maxTop = this.$size.height - h; - if (!composition) { - posTop += this.lineHeight; - } - else { - if (composition.useTextareaForIME) { - var val = this.textarea.value; - w = this.characterWidth * (this.session.$getStringScreenWidth(val)[0]); - } - else { - posTop += this.lineHeight + 2; - } - } - - posLeft -= this.scrollLeft; - if (posLeft > this.$size.scrollerWidth - w) - posLeft = this.$size.scrollerWidth - w; - - posLeft += this.gutterWidth + this.margin.left; - - dom.setStyle(style, "height", h + "px"); - dom.setStyle(style, "width", w + "px"); - dom.translate(this.textarea, Math.min(posLeft, this.$size.scrollerWidth - w), Math.min(posTop, maxTop)); - }; - this.getFirstVisibleRow = function() { - return this.layerConfig.firstRow; - }; - this.getFirstFullyVisibleRow = function() { - return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1); - }; - this.getLastFullyVisibleRow = function() { - var config = this.layerConfig; - var lastRow = config.lastRow; - var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight; - if (top - this.session.getScrollTop() > config.height - config.lineHeight) - return lastRow - 1; - return lastRow; - }; - this.getLastVisibleRow = function() { - return this.layerConfig.lastRow; - }; - - this.$padding = null; - this.setPadding = function(padding) { - this.$padding = padding; - this.$textLayer.setPadding(padding); - this.$cursorLayer.setPadding(padding); - this.$markerFront.setPadding(padding); - this.$markerBack.setPadding(padding); - this.$loop.schedule(this.CHANGE_FULL); - this.$updatePrintMargin(); - }; - - this.setScrollMargin = function(top, bottom, left, right) { - var sm = this.scrollMargin; - sm.top = top|0; - sm.bottom = bottom|0; - sm.right = right|0; - sm.left = left|0; - sm.v = sm.top + sm.bottom; - sm.h = sm.left + sm.right; - if (sm.top && this.scrollTop <= 0 && this.session) - this.session.setScrollTop(-sm.top); - this.updateFull(); - }; - - this.setMargin = function(top, bottom, left, right) { - var sm = this.margin; - sm.top = top|0; - sm.bottom = bottom|0; - sm.right = right|0; - sm.left = left|0; - sm.v = sm.top + sm.bottom; - sm.h = sm.left + sm.right; - this.$updateCachedSize(true, this.gutterWidth, this.$size.width, this.$size.height); - this.updateFull(); - }; - this.getHScrollBarAlwaysVisible = function() { - return this.$hScrollBarAlwaysVisible; - }; - this.setHScrollBarAlwaysVisible = function(alwaysVisible) { - this.setOption("hScrollBarAlwaysVisible", alwaysVisible); - }; - this.getVScrollBarAlwaysVisible = function() { - return this.$vScrollBarAlwaysVisible; - }; - this.setVScrollBarAlwaysVisible = function(alwaysVisible) { - this.setOption("vScrollBarAlwaysVisible", alwaysVisible); - }; - - this.$updateScrollBarV = function() { - var scrollHeight = this.layerConfig.maxHeight; - var scrollerHeight = this.$size.scrollerHeight; - if (!this.$maxLines && this.$scrollPastEnd) { - scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd; - if (this.scrollTop > scrollHeight - scrollerHeight) { - scrollHeight = this.scrollTop + scrollerHeight; - this.scrollBarV.scrollTop = null; - } - } - this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v); - this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top); - }; - this.$updateScrollBarH = function() { - this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h); - this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left); - }; - - this.$frozen = false; - this.freeze = function() { - this.$frozen = true; - }; - - this.unfreeze = function() { - this.$frozen = false; - }; - - this.$renderChanges = function(changes, force) { - if (this.$changes) { - changes |= this.$changes; - this.$changes = 0; - } - if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) { - this.$changes |= changes; - return; - } - if (this.$size.$dirty) { - this.$changes |= changes; - return this.onResize(true); - } - if (!this.lineHeight) { - this.$textLayer.checkForSizeChanges(); - } - - this._signal("beforeRender", changes); - - if (this.session && this.session.$bidiHandler) - this.session.$bidiHandler.updateCharacterWidths(this.$fontMetrics); - - var config = this.layerConfig; - if (changes & this.CHANGE_FULL || - changes & this.CHANGE_SIZE || - changes & this.CHANGE_TEXT || - changes & this.CHANGE_LINES || - changes & this.CHANGE_SCROLL || - changes & this.CHANGE_H_SCROLL - ) { - changes |= this.$computeLayerConfig() | this.$loop.clear(); - if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) { - var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight; - if (st > 0) { - this.scrollTop = st; - changes = changes | this.CHANGE_SCROLL; - changes |= this.$computeLayerConfig() | this.$loop.clear(); - } - } - config = this.layerConfig; - this.$updateScrollBarV(); - if (changes & this.CHANGE_H_SCROLL) - this.$updateScrollBarH(); - - dom.translate(this.content, -this.scrollLeft, -config.offset); - - var width = config.width + 2 * this.$padding + "px"; - var height = config.minHeight + "px"; - - dom.setStyle(this.content.style, "width", width); - dom.setStyle(this.content.style, "height", height); - } - if (changes & this.CHANGE_H_SCROLL) { - dom.translate(this.content, -this.scrollLeft, -config.offset); - this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left"; - } - if (changes & this.CHANGE_FULL) { - this.$changedLines = null; - this.$textLayer.update(config); - if (this.$showGutter) - this.$gutterLayer.update(config); - this.$markerBack.update(config); - this.$markerFront.update(config); - this.$cursorLayer.update(config); - this.$moveTextAreaToCursor(); - this._signal("afterRender", changes); - return; - } - if (changes & this.CHANGE_SCROLL) { - this.$changedLines = null; - if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) - this.$textLayer.update(config); - else - this.$textLayer.scrollLines(config); - - if (this.$showGutter) { - if (changes & this.CHANGE_GUTTER || changes & this.CHANGE_LINES) - this.$gutterLayer.update(config); - else - this.$gutterLayer.scrollLines(config); - } - this.$markerBack.update(config); - this.$markerFront.update(config); - this.$cursorLayer.update(config); - this.$moveTextAreaToCursor(); - this._signal("afterRender", changes); - return; - } - - if (changes & this.CHANGE_TEXT) { - this.$changedLines = null; - this.$textLayer.update(config); - if (this.$showGutter) - this.$gutterLayer.update(config); - } - else if (changes & this.CHANGE_LINES) { - if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter) - this.$gutterLayer.update(config); - } - else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) { - if (this.$showGutter) - this.$gutterLayer.update(config); - } - else if (changes & this.CHANGE_CURSOR) { - if (this.$highlightGutterLine) - this.$gutterLayer.updateLineHighlight(config); - } - - if (changes & this.CHANGE_CURSOR) { - this.$cursorLayer.update(config); - this.$moveTextAreaToCursor(); - } - - if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) { - this.$markerFront.update(config); - } - - if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) { - this.$markerBack.update(config); - } - - this._signal("afterRender", changes); - }; - - - this.$autosize = function() { - var height = this.session.getScreenLength() * this.lineHeight; - var maxHeight = this.$maxLines * this.lineHeight; - var desiredHeight = Math.min(maxHeight, - Math.max((this.$minLines || 1) * this.lineHeight, height) - ) + this.scrollMargin.v + (this.$extraHeight || 0); - if (this.$horizScroll) - desiredHeight += this.scrollBarH.getHeight(); - if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight) - desiredHeight = this.$maxPixelHeight; - - var hideScrollbars = desiredHeight <= 2 * this.lineHeight; - var vScroll = !hideScrollbars && height > maxHeight; - - if (desiredHeight != this.desiredHeight || - this.$size.height != this.desiredHeight || vScroll != this.$vScroll) { - if (vScroll != this.$vScroll) { - this.$vScroll = vScroll; - this.scrollBarV.setVisible(vScroll); - } - - var w = this.container.clientWidth; - this.container.style.height = desiredHeight + "px"; - this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight); - this.desiredHeight = desiredHeight; - - this._signal("autosize"); - } - }; - - this.$computeLayerConfig = function() { - var session = this.session; - var size = this.$size; - - var hideScrollbars = size.height <= 2 * this.lineHeight; - var screenLines = this.session.getScreenLength(); - var maxHeight = screenLines * this.lineHeight; - - var longestLine = this.$getLongestLine(); - - var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible || - size.scrollerWidth - longestLine - 2 * this.$padding < 0); - - var hScrollChanged = this.$horizScroll !== horizScroll; - if (hScrollChanged) { - this.$horizScroll = horizScroll; - this.scrollBarH.setVisible(horizScroll); - } - var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine - if (this.$maxLines && this.lineHeight > 1) - this.$autosize(); - - var minHeight = size.scrollerHeight + this.lineHeight; - - var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd - ? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd - : 0; - maxHeight += scrollPastEnd; - - var sm = this.scrollMargin; - this.session.setScrollTop(Math.max(-sm.top, - Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom))); - - this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft, - longestLine + 2 * this.$padding - size.scrollerWidth + sm.right))); - - var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible || - size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top); - var vScrollChanged = vScrollBefore !== vScroll; - if (vScrollChanged) { - this.$vScroll = vScroll; - this.scrollBarV.setVisible(vScroll); - } - - var offset = this.scrollTop % this.lineHeight; - var lineCount = Math.ceil(minHeight / this.lineHeight) - 1; - var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight)); - var lastRow = firstRow + lineCount; - var firstRowScreen, firstRowHeight; - var lineHeight = this.lineHeight; - firstRow = session.screenToDocumentRow(firstRow, 0); - var foldLine = session.getFoldLine(firstRow); - if (foldLine) { - firstRow = foldLine.start.row; - } - - firstRowScreen = session.documentToScreenRow(firstRow, 0); - firstRowHeight = session.getRowLength(firstRow) * lineHeight; - - lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1); - minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight + - firstRowHeight; - - offset = this.scrollTop - firstRowScreen * lineHeight; - - var changes = 0; - if (this.layerConfig.width != longestLine || hScrollChanged) - changes = this.CHANGE_H_SCROLL; - if (hScrollChanged || vScrollChanged) { - changes |= this.$updateCachedSize(true, this.gutterWidth, size.width, size.height); - this._signal("scrollbarVisibilityChanged"); - if (vScrollChanged) - longestLine = this.$getLongestLine(); - } - - this.layerConfig = { - width : longestLine, - padding : this.$padding, - firstRow : firstRow, - firstRowScreen: firstRowScreen, - lastRow : lastRow, - lineHeight : lineHeight, - characterWidth : this.characterWidth, - minHeight : minHeight, - maxHeight : maxHeight, - offset : offset, - gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0, - height : this.$size.scrollerHeight - }; - - if (this.session.$bidiHandler) - this.session.$bidiHandler.setContentWidth(longestLine - this.$padding); - - return changes; - }; - - this.$updateLines = function() { - if (!this.$changedLines) return; - var firstRow = this.$changedLines.firstRow; - var lastRow = this.$changedLines.lastRow; - this.$changedLines = null; - - var layerConfig = this.layerConfig; - - if (firstRow > layerConfig.lastRow + 1) { return; } - if (lastRow < layerConfig.firstRow) { return; } - if (lastRow === Infinity) { - if (this.$showGutter) - this.$gutterLayer.update(layerConfig); - this.$textLayer.update(layerConfig); - return; - } - this.$textLayer.updateLines(layerConfig, firstRow, lastRow); - return true; - }; - - this.$getLongestLine = function() { - var charCount = this.session.getScreenWidth(); - if (this.showInvisibles && !this.session.$useWrapMode) - charCount += 1; - - if (this.$textLayer && charCount > this.$textLayer.MAX_LINE_LENGTH) - charCount = this.$textLayer.MAX_LINE_LENGTH + 30; - - return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth)); - }; - this.updateFrontMarkers = function() { - this.$markerFront.setMarkers(this.session.getMarkers(true)); - this.$loop.schedule(this.CHANGE_MARKER_FRONT); - }; - this.updateBackMarkers = function() { - this.$markerBack.setMarkers(this.session.getMarkers()); - this.$loop.schedule(this.CHANGE_MARKER_BACK); - }; - this.addGutterDecoration = function(row, className){ - this.$gutterLayer.addGutterDecoration(row, className); - }; - this.removeGutterDecoration = function(row, className){ - this.$gutterLayer.removeGutterDecoration(row, className); - }; - this.updateBreakpoints = function(rows) { - this.$loop.schedule(this.CHANGE_GUTTER); - }; - this.setAnnotations = function(annotations) { - this.$gutterLayer.setAnnotations(annotations); - this.$loop.schedule(this.CHANGE_GUTTER); - }; - this.updateCursor = function() { - this.$loop.schedule(this.CHANGE_CURSOR); - }; - this.hideCursor = function() { - this.$cursorLayer.hideCursor(); - }; - this.showCursor = function() { - this.$cursorLayer.showCursor(); - }; - - this.scrollSelectionIntoView = function(anchor, lead, offset) { - this.scrollCursorIntoView(anchor, offset); - this.scrollCursorIntoView(lead, offset); - }; - this.scrollCursorIntoView = function(cursor, offset, $viewMargin) { - if (this.$size.scrollerHeight === 0) - return; - - var pos = this.$cursorLayer.getPixelPosition(cursor); - - var left = pos.left; - var top = pos.top; - - var topMargin = $viewMargin && $viewMargin.top || 0; - var bottomMargin = $viewMargin && $viewMargin.bottom || 0; - - var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop; - - if (scrollTop + topMargin > top) { - if (offset && scrollTop + topMargin > top + this.lineHeight) - top -= offset * this.$size.scrollerHeight; - if (top === 0) - top = -this.scrollMargin.top; - this.session.setScrollTop(top); - } else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) { - if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight) - top += offset * this.$size.scrollerHeight; - this.session.setScrollTop(top + this.lineHeight + bottomMargin - this.$size.scrollerHeight); - } - - var scrollLeft = this.scrollLeft; - - if (scrollLeft > left) { - if (left < this.$padding + 2 * this.layerConfig.characterWidth) - left = -this.scrollMargin.left; - this.session.setScrollLeft(left); - } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { - this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); - } else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) { - this.session.setScrollLeft(0); - } - }; - this.getScrollTop = function() { - return this.session.getScrollTop(); - }; - this.getScrollLeft = function() { - return this.session.getScrollLeft(); - }; - this.getScrollTopRow = function() { - return this.scrollTop / this.lineHeight; - }; - this.getScrollBottomRow = function() { - return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1); - }; - this.scrollToRow = function(row) { - this.session.setScrollTop(row * this.lineHeight); - }; - - this.alignCursor = function(cursor, alignment) { - if (typeof cursor == "number") - cursor = {row: cursor, column: 0}; - - var pos = this.$cursorLayer.getPixelPosition(cursor); - var h = this.$size.scrollerHeight - this.lineHeight; - var offset = pos.top - h * (alignment || 0); - - this.session.setScrollTop(offset); - return offset; - }; - - this.STEPS = 8; - this.$calcSteps = function(fromValue, toValue){ - var i = 0; - var l = this.STEPS; - var steps = []; - - var func = function(t, x_min, dx) { - return dx * (Math.pow(t - 1, 3) + 1) + x_min; - }; - - for (i = 0; i < l; ++i) - steps.push(func(i / this.STEPS, fromValue, toValue - fromValue)); - - return steps; - }; - this.scrollToLine = function(line, center, animate, callback) { - var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0}); - var offset = pos.top; - if (center) - offset -= this.$size.scrollerHeight / 2; - - var initialScroll = this.scrollTop; - this.session.setScrollTop(offset); - if (animate !== false) - this.animateScrolling(initialScroll, callback); - }; - - this.animateScrolling = function(fromValue, callback) { - var toValue = this.scrollTop; - if (!this.$animatedScroll) - return; - var _self = this; - - if (fromValue == toValue) - return; - - if (this.$scrollAnimation) { - var oldSteps = this.$scrollAnimation.steps; - if (oldSteps.length) { - fromValue = oldSteps[0]; - if (fromValue == toValue) - return; - } - } - - var steps = _self.$calcSteps(fromValue, toValue); - this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps}; - - clearInterval(this.$timer); - - _self.session.setScrollTop(steps.shift()); - _self.session.$scrollTop = toValue; - this.$timer = setInterval(function() { - if (!_self.session) - return clearInterval(_self.$timer); - if (steps.length) { - _self.session.setScrollTop(steps.shift()); - _self.session.$scrollTop = toValue; - } else if (toValue != null) { - _self.session.$scrollTop = -1; - _self.session.setScrollTop(toValue); - toValue = null; - } else { - _self.$timer = clearInterval(_self.$timer); - _self.$scrollAnimation = null; - callback && callback(); - } - }, 10); - }; - this.scrollToY = function(scrollTop) { - if (this.scrollTop !== scrollTop) { - this.$loop.schedule(this.CHANGE_SCROLL); - this.scrollTop = scrollTop; - } - }; - this.scrollToX = function(scrollLeft) { - if (this.scrollLeft !== scrollLeft) - this.scrollLeft = scrollLeft; - this.$loop.schedule(this.CHANGE_H_SCROLL); - }; - this.scrollTo = function(x, y) { - this.session.setScrollTop(y); - this.session.setScrollLeft(x); - }; - this.scrollBy = function(deltaX, deltaY) { - deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY); - deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX); - }; - this.isScrollableBy = function(deltaX, deltaY) { - if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top) - return true; - if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight - - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom) - return true; - if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left) - return true; - if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth - - this.layerConfig.width < -1 + this.scrollMargin.right) - return true; - }; - - this.pixelToScreenCoordinates = function(x, y) { - var canvasPos; - if (this.$hasCssTransforms) { - canvasPos = {top:0, left: 0}; - var p = this.$fontMetrics.transformCoordinates([x, y]); - x = p[1] - this.gutterWidth - this.margin.left; - y = p[0]; - } else { - canvasPos = this.scroller.getBoundingClientRect(); - } - - var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding; - var offset = offsetX / this.characterWidth; - var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight); - var col = this.$blockCursor ? Math.floor(offset) : Math.round(offset); - - return {row: row, column: col, side: offset - col > 0 ? 1 : -1, offsetX: offsetX}; - }; - - this.screenToTextCoordinates = function(x, y) { - var canvasPos; - if (this.$hasCssTransforms) { - canvasPos = {top:0, left: 0}; - var p = this.$fontMetrics.transformCoordinates([x, y]); - x = p[1] - this.gutterWidth - this.margin.left; - y = p[0]; - } else { - canvasPos = this.scroller.getBoundingClientRect(); - } - - var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding; - var offset = offsetX / this.characterWidth; - var col = this.$blockCursor ? Math.floor(offset) : Math.round(offset); - - var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight); - - return this.session.screenToDocumentPosition(row, Math.max(col, 0), offsetX); - }; - this.textToScreenCoordinates = function(row, column) { - var canvasPos = this.scroller.getBoundingClientRect(); - var pos = this.session.documentToScreenPosition(row, column); - - var x = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, row) - ? this.session.$bidiHandler.getPosLeft(pos.column) - : Math.round(pos.column * this.characterWidth)); - - var y = pos.row * this.lineHeight; - - return { - pageX: canvasPos.left + x - this.scrollLeft, - pageY: canvasPos.top + y - this.scrollTop - }; - }; - this.visualizeFocus = function() { - dom.addCssClass(this.container, "ace_focus"); - }; - this.visualizeBlur = function() { - dom.removeCssClass(this.container, "ace_focus"); - }; - this.showComposition = function(composition) { - this.$composition = composition; - if (!composition.cssText) { - composition.cssText = this.textarea.style.cssText; - } - if (composition.useTextareaForIME == undefined) - composition.useTextareaForIME = this.$useTextareaForIME; - - if (this.$useTextareaForIME) { - dom.addCssClass(this.textarea, "ace_composition"); - this.textarea.style.cssText = ""; - this.$moveTextAreaToCursor(); - this.$cursorLayer.element.style.display = "none"; - } - else { - composition.markerId = this.session.addMarker(composition.markerRange, "ace_composition_marker", "text"); - } - }; - this.setCompositionText = function(text) { - var cursor = this.session.selection.cursor; - this.addToken(text, "composition_placeholder", cursor.row, cursor.column); - this.$moveTextAreaToCursor(); - }; - this.hideComposition = function() { - if (!this.$composition) - return; - - if (this.$composition.markerId) - this.session.removeMarker(this.$composition.markerId); - - dom.removeCssClass(this.textarea, "ace_composition"); - this.textarea.style.cssText = this.$composition.cssText; - var cursor = this.session.selection.cursor; - this.removeExtraToken(cursor.row, cursor.column); - this.$composition = null; - this.$cursorLayer.element.style.display = ""; - }; - - this.addToken = function(text, type, row, column) { - var session = this.session; - session.bgTokenizer.lines[row] = null; - var newToken = {type: type, value: text}; - var tokens = session.getTokens(row); - if (column == null) { - tokens.push(newToken); - } else { - var l = 0; - for (var i =0; i < tokens.length; i++) { - var token = tokens[i]; - l += token.value.length; - if (column <= l) { - var diff = token.value.length - (l - column); - var before = token.value.slice(0, diff); - var after = token.value.slice(diff); - - tokens.splice(i, 1, {type: token.type, value: before}, newToken, {type: token.type, value: after}); - break; - } - } - } - this.updateLines(row, row); - }; - - this.removeExtraToken = function(row, column) { - this.updateLines(row, row); - }; - this.setTheme = function(theme, cb) { - var _self = this; - this.$themeId = theme; - _self._dispatchEvent('themeChange',{theme:theme}); - - if (!theme || typeof theme == "string") { - var moduleName = theme || this.$options.theme.initialValue; - config.loadModule(["theme", moduleName], afterLoad); - } else { - afterLoad(theme); - } - - function afterLoad(module) { - if (_self.$themeId != theme) - return cb && cb(); - if (!module || !module.cssClass) - throw new Error("couldn't load module " + theme + " or it didn't call define"); - if (module.$id) - _self.$themeId = module.$id; - dom.importCssString( - module.cssText, - module.cssClass, - _self.container - ); - - if (_self.theme) - dom.removeCssClass(_self.container, _self.theme.cssClass); - - var padding = "padding" in module ? module.padding - : "padding" in (_self.theme || {}) ? 4 : _self.$padding; - if (_self.$padding && padding != _self.$padding) - _self.setPadding(padding); - _self.$theme = module.cssClass; - - _self.theme = module; - dom.addCssClass(_self.container, module.cssClass); - dom.setCssClass(_self.container, "ace_dark", module.isDark); - if (_self.$size) { - _self.$size.width = 0; - _self.$updateSizeAsync(); - } - - _self._dispatchEvent('themeLoaded', {theme:module}); - cb && cb(); - } - }; - this.getTheme = function() { - return this.$themeId; - }; - this.setStyle = function(style, include) { - dom.setCssClass(this.container, style, include !== false); - }; - this.unsetStyle = function(style) { - dom.removeCssClass(this.container, style); - }; - - this.setCursorStyle = function(style) { - dom.setStyle(this.scroller.style, "cursor", style); - }; - this.setMouseCursor = function(cursorStyle) { - dom.setStyle(this.scroller.style, "cursor", cursorStyle); - }; - - this.attachToShadowRoot = function() { - dom.importCssString(editorCss, "ace_editor.css", this.container); - }; - this.destroy = function() { - this.freeze(); - this.$fontMetrics.destroy(); - this.$cursorLayer.destroy(); - this.removeAllListeners(); - this.container.textContent = ""; - }; - -}).call(VirtualRenderer.prototype); - - -config.defineOptions(VirtualRenderer.prototype, "renderer", { - animatedScroll: {initialValue: false}, - showInvisibles: { - set: function(value) { - if (this.$textLayer.setShowInvisibles(value)) - this.$loop.schedule(this.CHANGE_TEXT); - }, - initialValue: false - }, - showPrintMargin: { - set: function() { this.$updatePrintMargin(); }, - initialValue: true - }, - printMarginColumn: { - set: function() { this.$updatePrintMargin(); }, - initialValue: 80 - }, - printMargin: { - set: function(val) { - if (typeof val == "number") - this.$printMarginColumn = val; - this.$showPrintMargin = !!val; - this.$updatePrintMargin(); - }, - get: function() { - return this.$showPrintMargin && this.$printMarginColumn; - } - }, - showGutter: { - set: function(show){ - this.$gutter.style.display = show ? "block" : "none"; - this.$loop.schedule(this.CHANGE_FULL); - this.onGutterResize(); - }, - initialValue: true - }, - fadeFoldWidgets: { - set: function(show) { - dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show); - }, - initialValue: false - }, - showFoldWidgets: { - set: function(show) { - this.$gutterLayer.setShowFoldWidgets(show); - this.$loop.schedule(this.CHANGE_GUTTER); - }, - initialValue: true - }, - displayIndentGuides: { - set: function(show) { - if (this.$textLayer.setDisplayIndentGuides(show)) - this.$loop.schedule(this.CHANGE_TEXT); - }, - initialValue: true - }, - highlightGutterLine: { - set: function(shouldHighlight) { - this.$gutterLayer.setHighlightGutterLine(shouldHighlight); - this.$loop.schedule(this.CHANGE_GUTTER); - }, - initialValue: true - }, - hScrollBarAlwaysVisible: { - set: function(val) { - if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll) - this.$loop.schedule(this.CHANGE_SCROLL); - }, - initialValue: false - }, - vScrollBarAlwaysVisible: { - set: function(val) { - if (!this.$vScrollBarAlwaysVisible || !this.$vScroll) - this.$loop.schedule(this.CHANGE_SCROLL); - }, - initialValue: false - }, - fontSize: { - set: function(size) { - if (typeof size == "number") - size = size + "px"; - this.container.style.fontSize = size; - this.updateFontSize(); - }, - initialValue: 12 - }, - fontFamily: { - set: function(name) { - this.container.style.fontFamily = name; - this.updateFontSize(); - } - }, - maxLines: { - set: function(val) { - this.updateFull(); - } - }, - minLines: { - set: function(val) { - if (!(this.$minLines < 0x1ffffffffffff)) - this.$minLines = 0; - this.updateFull(); - } - }, - maxPixelHeight: { - set: function(val) { - this.updateFull(); - }, - initialValue: 0 - }, - scrollPastEnd: { - set: function(val) { - val = +val || 0; - if (this.$scrollPastEnd == val) - return; - this.$scrollPastEnd = val; - this.$loop.schedule(this.CHANGE_SCROLL); - }, - initialValue: 0, - handlesSet: true - }, - fixedWidthGutter: { - set: function(val) { - this.$gutterLayer.$fixedWidth = !!val; - this.$loop.schedule(this.CHANGE_GUTTER); - } - }, - theme: { - set: function(val) { this.setTheme(val); }, - get: function() { return this.$themeId || this.theme; }, - initialValue: "./theme/textmate", - handlesSet: true - }, - hasCssTransforms: { - }, - useTextareaForIME: { - initialValue: !useragent.isMobile && !useragent.isIE - } -}); - -exports.VirtualRenderer = VirtualRenderer; -}); - -define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var net = require("../lib/net"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; -var config = require("../config"); - -function $workerBlob(workerUrl) { - var script = "importScripts('" + net.qualifyURL(workerUrl) + "');"; - try { - return new Blob([script], {"type": "application/javascript"}); - } catch (e) { // Backwards-compatibility - var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; - var blobBuilder = new BlobBuilder(); - blobBuilder.append(script); - return blobBuilder.getBlob("application/javascript"); - } -} - -function createWorker(workerUrl) { - if (typeof Worker == "undefined") - return { postMessage: function() {}, terminate: function() {} }; - if (config.get("loadWorkerFromBlob")) { - var blob = $workerBlob(workerUrl); - var URL = window.URL || window.webkitURL; - var blobURL = URL.createObjectURL(blob); - return new Worker(blobURL); - } - return new Worker(workerUrl); -} - -var WorkerClient = function(worker) { - if (!worker.postMessage) - worker = this.$createWorkerFromOldConfig.apply(this, arguments); - - this.$worker = worker; - this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); - this.changeListener = this.changeListener.bind(this); - this.onMessage = this.onMessage.bind(this); - - this.callbackId = 1; - this.callbacks = {}; - - this.$worker.onmessage = this.onMessage; -}; - -(function(){ - - oop.implement(this, EventEmitter); - - this.$createWorkerFromOldConfig = function(topLevelNamespaces, mod, classname, workerUrl, importScripts) { - if (require.nameToUrl && !require.toUrl) - require.toUrl = require.nameToUrl; - - if (config.get("packaged") || !require.toUrl) { - workerUrl = workerUrl || config.moduleUrl(mod, "worker"); - } else { - var normalizePath = this.$normalizePath; - workerUrl = workerUrl || normalizePath(require.toUrl("ace/worker/worker.js", null, "_")); - - var tlns = {}; - topLevelNamespaces.forEach(function(ns) { - tlns[ns] = normalizePath(require.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, "")); - }); - } - - this.$worker = createWorker(workerUrl); - if (importScripts) { - this.send("importScripts", importScripts); - } - this.$worker.postMessage({ - init : true, - tlns : tlns, - module : mod, - classname : classname - }); - return this.$worker; - }; - - this.onMessage = function(e) { - var msg = e.data; - switch (msg.type) { - case "event": - this._signal(msg.name, {data: msg.data}); - break; - case "call": - var callback = this.callbacks[msg.id]; - if (callback) { - callback(msg.data); - delete this.callbacks[msg.id]; - } - break; - case "error": - this.reportError(msg.data); - break; - case "log": - window.console && console.log && console.log.apply(console, msg.data); - break; - } - }; - - this.reportError = function(err) { - window.console && console.error && console.error(err); - }; - - this.$normalizePath = function(path) { - return net.qualifyURL(path); - }; - - this.terminate = function() { - this._signal("terminate", {}); - this.deltaQueue = null; - this.$worker.terminate(); - this.$worker = null; - if (this.$doc) - this.$doc.off("change", this.changeListener); - this.$doc = null; - }; - - this.send = function(cmd, args) { - this.$worker.postMessage({command: cmd, args: args}); - }; - - this.call = function(cmd, args, callback) { - if (callback) { - var id = this.callbackId++; - this.callbacks[id] = callback; - args.push(id); - } - this.send(cmd, args); - }; - - this.emit = function(event, data) { - try { - if (data.data && data.data.err) - data.data.err = {message: data.data.err.message, stack: data.data.err.stack, code: data.data.err.code}; - this.$worker.postMessage({event: event, data: {data: data.data}}); - } - catch(ex) { - console.error(ex.stack); - } - }; - - this.attachToDocument = function(doc) { - if (this.$doc) - this.terminate(); - - this.$doc = doc; - this.call("setValue", [doc.getValue()]); - doc.on("change", this.changeListener); - }; - - this.changeListener = function(delta) { - if (!this.deltaQueue) { - this.deltaQueue = []; - setTimeout(this.$sendDeltaQueue, 0); - } - if (delta.action == "insert") - this.deltaQueue.push(delta.start, delta.lines); - else - this.deltaQueue.push(delta.start, delta.end); - }; - - this.$sendDeltaQueue = function() { - var q = this.deltaQueue; - if (!q) return; - this.deltaQueue = null; - if (q.length > 50 && q.length > this.$doc.getLength() >> 1) { - this.call("setValue", [this.$doc.getValue()]); - } else - this.emit("change", {data: q}); - }; - -}).call(WorkerClient.prototype); - - -var UIWorkerClient = function(topLevelNamespaces, mod, classname) { - var main = null; - var emitSync = false; - var sender = Object.create(EventEmitter); - - var messageBuffer = []; - var workerClient = new WorkerClient({ - messageBuffer: messageBuffer, - terminate: function() {}, - postMessage: function(e) { - messageBuffer.push(e); - if (!main) return; - if (emitSync) - setTimeout(processNext); - else - processNext(); - } - }); - - workerClient.setEmitSync = function(val) { emitSync = val; }; - - var processNext = function() { - var msg = messageBuffer.shift(); - if (msg.command) - main[msg.command].apply(main, msg.args); - else if (msg.event) - sender._signal(msg.event, msg.data); - }; - - sender.postMessage = function(msg) { - workerClient.onMessage({data: msg}); - }; - sender.callback = function(data, callbackId) { - this.postMessage({type: "call", id: callbackId, data: data}); - }; - sender.emit = function(name, data) { - this.postMessage({type: "event", name: name, data: data}); - }; - - config.loadModule(["worker", mod], function(Main) { - main = new Main[classname](sender); - while (messageBuffer.length) - processNext(); - }); - - return workerClient; -}; - -exports.UIWorkerClient = UIWorkerClient; -exports.WorkerClient = WorkerClient; -exports.createWorker = createWorker; - - -}); - -define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(require, exports, module) { -"use strict"; - -var Range = require("./range").Range; -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var oop = require("./lib/oop"); - -var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) { - var _self = this; - this.length = length; - this.session = session; - this.doc = session.getDocument(); - this.mainClass = mainClass; - this.othersClass = othersClass; - this.$onUpdate = this.onUpdate.bind(this); - this.doc.on("change", this.$onUpdate); - this.$others = others; - - this.$onCursorChange = function() { - setTimeout(function() { - _self.onCursorChange(); - }); - }; - - this.$pos = pos; - var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1}; - this.$undoStackDepth = undoStack.length; - this.setup(); - - session.selection.on("changeCursor", this.$onCursorChange); -}; - -(function() { - - oop.implement(this, EventEmitter); - this.setup = function() { - var _self = this; - var doc = this.doc; - var session = this.session; - - this.selectionBefore = session.selection.toJSON(); - if (session.selection.inMultiSelectMode) - session.selection.toSingleRange(); - - this.pos = doc.createAnchor(this.$pos.row, this.$pos.column); - var pos = this.pos; - pos.$insertRight = true; - pos.detach(); - pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false); - this.others = []; - this.$others.forEach(function(other) { - var anchor = doc.createAnchor(other.row, other.column); - anchor.$insertRight = true; - anchor.detach(); - _self.others.push(anchor); - }); - session.setUndoSelect(false); - }; - this.showOtherMarkers = function() { - if (this.othersActive) return; - var session = this.session; - var _self = this; - this.othersActive = true; - this.others.forEach(function(anchor) { - anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false); - }); - }; - this.hideOtherMarkers = function() { - if (!this.othersActive) return; - this.othersActive = false; - for (var i = 0; i < this.others.length; i++) { - this.session.removeMarker(this.others[i].markerId); - } - }; - this.onUpdate = function(delta) { - if (this.$updating) - return this.updateAnchors(delta); - - var range = delta; - if (range.start.row !== range.end.row) return; - if (range.start.row !== this.pos.row) return; - this.$updating = true; - var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column; - var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1; - var distanceFromStart = range.start.column - this.pos.column; - - this.updateAnchors(delta); - - if (inMainRange) - this.length += lengthDiff; - - if (inMainRange && !this.session.$fromUndo) { - if (delta.action === 'insert') { - for (var i = this.others.length - 1; i >= 0; i--) { - var otherPos = this.others[i]; - var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; - this.doc.insertMergedLines(newPos, delta.lines); - } - } else if (delta.action === 'remove') { - for (var i = this.others.length - 1; i >= 0; i--) { - var otherPos = this.others[i]; - var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; - this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff)); - } - } - } - - this.$updating = false; - this.updateMarkers(); - }; - - this.updateAnchors = function(delta) { - this.pos.onChange(delta); - for (var i = this.others.length; i--;) - this.others[i].onChange(delta); - this.updateMarkers(); - }; - - this.updateMarkers = function() { - if (this.$updating) - return; - var _self = this; - var session = this.session; - var updateMarker = function(pos, className) { - session.removeMarker(pos.markerId); - pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false); - }; - updateMarker(this.pos, this.mainClass); - for (var i = this.others.length; i--;) - updateMarker(this.others[i], this.othersClass); - }; - - this.onCursorChange = function(event) { - if (this.$updating || !this.session) return; - var pos = this.session.selection.getCursor(); - if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) { - this.showOtherMarkers(); - this._emit("cursorEnter", event); - } else { - this.hideOtherMarkers(); - this._emit("cursorLeave", event); - } - }; - this.detach = function() { - this.session.removeMarker(this.pos && this.pos.markerId); - this.hideOtherMarkers(); - this.doc.off("change", this.$onUpdate); - this.session.selection.off("changeCursor", this.$onCursorChange); - this.session.setUndoSelect(true); - this.session = null; - }; - this.cancel = function() { - if (this.$undoStackDepth === -1) - return; - var undoManager = this.session.getUndoManager(); - var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth; - for (var i = 0; i < undosRequired; i++) { - undoManager.undo(this.session, true); - } - if (this.selectionBefore) - this.session.selection.fromJSON(this.selectionBefore); - }; -}).call(PlaceHolder.prototype); - - -exports.PlaceHolder = PlaceHolder; -}); - -define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(require, exports, module) { - -var event = require("../lib/event"); -var useragent = require("../lib/useragent"); -function isSamePoint(p1, p2) { - return p1.row == p2.row && p1.column == p2.column; -} - -function onMouseDown(e) { - var ev = e.domEvent; - var alt = ev.altKey; - var shift = ev.shiftKey; - var ctrl = ev.ctrlKey; - var accel = e.getAccelKey(); - var button = e.getButton(); - - if (ctrl && useragent.isMac) - button = ev.button; - - if (e.editor.inMultiSelectMode && button == 2) { - e.editor.textInput.onContextMenu(e.domEvent); - return; - } - - if (!ctrl && !alt && !accel) { - if (button === 0 && e.editor.inMultiSelectMode) - e.editor.exitMultiSelectMode(); - return; - } - - if (button !== 0) - return; - - var editor = e.editor; - var selection = editor.selection; - var isMultiSelect = editor.inMultiSelectMode; - var pos = e.getDocumentPosition(); - var cursor = selection.getCursor(); - var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor)); - - var mouseX = e.x, mouseY = e.y; - var onMouseSelection = function(e) { - mouseX = e.clientX; - mouseY = e.clientY; - }; - - var session = editor.session; - var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); - var screenCursor = screenAnchor; - - var selectionMode; - if (editor.$mouseHandler.$enableJumpToDef) { - if (ctrl && alt || accel && alt) - selectionMode = shift ? "block" : "add"; - else if (alt && editor.$blockSelectEnabled) - selectionMode = "block"; - } else { - if (accel && !alt) { - selectionMode = "add"; - if (!isMultiSelect && shift) - return; - } else if (alt && editor.$blockSelectEnabled) { - selectionMode = "block"; - } - } - - if (selectionMode && useragent.isMac && ev.ctrlKey) { - editor.$mouseHandler.cancelContextMenu(); - } - - if (selectionMode == "add") { - if (!isMultiSelect && inSelection) - return; // dragging - - if (!isMultiSelect) { - var range = selection.toOrientedRange(); - editor.addSelectionMarker(range); - } - - var oldRange = selection.rangeList.rangeAtPoint(pos); - - editor.inVirtualSelectionMode = true; - - if (shift) { - oldRange = null; - range = selection.ranges[0] || range; - editor.removeSelectionMarker(range); - } - editor.once("mouseup", function() { - var tmpSel = selection.toOrientedRange(); - - if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) - selection.substractPoint(tmpSel.cursor); - else { - if (shift) { - selection.substractPoint(range.cursor); - } else if (range) { - editor.removeSelectionMarker(range); - selection.addRange(range); - } - selection.addRange(tmpSel); - } - editor.inVirtualSelectionMode = false; - }); - - } else if (selectionMode == "block") { - e.stop(); - editor.inVirtualSelectionMode = true; - var initialRange; - var rectSel = []; - var blockSelect = function() { - var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); - var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column, newCursor.offsetX); - - if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.lead)) - return; - screenCursor = newCursor; - - editor.selection.moveToPosition(cursor); - editor.renderer.scrollCursorIntoView(); - - editor.removeSelectionMarkers(rectSel); - rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); - if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty()) - rectSel[0] = editor.$mouseHandler.$clickSelection.clone(); - rectSel.forEach(editor.addSelectionMarker, editor); - editor.updateSelectionMarkers(); - }; - if (isMultiSelect && !accel) { - selection.toSingleRange(); - } else if (!isMultiSelect && accel) { - initialRange = selection.toOrientedRange(); - editor.addSelectionMarker(initialRange); - } - - if (shift) - screenAnchor = session.documentToScreenPosition(selection.lead); - else - selection.moveToPosition(pos); - - screenCursor = {row: -1, column: -1}; - - var onMouseSelectionEnd = function(e) { - blockSelect(); - clearInterval(timerId); - editor.removeSelectionMarkers(rectSel); - if (!rectSel.length) - rectSel = [selection.toOrientedRange()]; - if (initialRange) { - editor.removeSelectionMarker(initialRange); - selection.toSingleRange(initialRange); - } - for (var i = 0; i < rectSel.length; i++) - selection.addRange(rectSel[i]); - editor.inVirtualSelectionMode = false; - editor.$mouseHandler.$clickSelection = null; - }; - - var onSelectionInterval = blockSelect; - - event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); - var timerId = setInterval(function() {onSelectionInterval();}, 20); - - return e.preventDefault(); - } -} - - -exports.onMouseDown = onMouseDown; - -}); - -define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(require, exports, module) { -exports.defaultCommands = [{ - name: "addCursorAbove", - description: "Add cursor above", - exec: function(editor) { editor.selectMoreLines(-1); }, - bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "addCursorBelow", - description: "Add cursor below", - exec: function(editor) { editor.selectMoreLines(1); }, - bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "addCursorAboveSkipCurrent", - description: "Add cursor above (skip current)", - exec: function(editor) { editor.selectMoreLines(-1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "addCursorBelowSkipCurrent", - description: "Add cursor below (skip current)", - exec: function(editor) { editor.selectMoreLines(1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectMoreBefore", - description: "Select more before", - exec: function(editor) { editor.selectMore(-1); }, - bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectMoreAfter", - description: "Select more after", - exec: function(editor) { editor.selectMore(1); }, - bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectNextBefore", - description: "Select next before", - exec: function(editor) { editor.selectMore(-1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectNextAfter", - description: "Select next after", - exec: function(editor) { editor.selectMore(1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "toggleSplitSelectionIntoLines", - description: "Split into lines", - exec: function(editor) { - if (editor.multiSelect.rangeCount > 1) - editor.multiSelect.joinSelections(); - else - editor.multiSelect.splitIntoLines(); - }, - bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"}, - readOnly: true -}, { - name: "splitSelectionIntoLines", - description: "Split into lines", - exec: function(editor) { editor.multiSelect.splitIntoLines(); }, - readOnly: true -}, { - name: "alignCursors", - description: "Align cursors", - exec: function(editor) { editor.alignCursors(); }, - bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"}, - scrollIntoView: "cursor" -}, { - name: "findAll", - description: "Find all", - exec: function(editor) { editor.findAll(); }, - bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"}, - scrollIntoView: "cursor", - readOnly: true -}]; -exports.multiSelectCommands = [{ - name: "singleSelection", - description: "Single selection", - bindKey: "esc", - exec: function(editor) { editor.exitMultiSelectMode(); }, - scrollIntoView: "cursor", - readOnly: true, - isAvailable: function(editor) {return editor && editor.inMultiSelectMode;} -}]; - -var HashHandler = require("../keyboard/hash_handler").HashHandler; -exports.keyboardHandler = new HashHandler(exports.multiSelectCommands); - -}); - -define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(require, exports, module) { - -var RangeList = require("./range_list").RangeList; -var Range = require("./range").Range; -var Selection = require("./selection").Selection; -var onMouseDown = require("./mouse/multi_select_handler").onMouseDown; -var event = require("./lib/event"); -var lang = require("./lib/lang"); -var commands = require("./commands/multi_select_commands"); -exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands); -var Search = require("./search").Search; -var search = new Search(); - -function find(session, needle, dir) { - search.$options.wrap = true; - search.$options.needle = needle; - search.$options.backwards = dir == -1; - return search.find(session); -} -var EditSession = require("./edit_session").EditSession; -(function() { - this.getSelectionMarkers = function() { - return this.$selectionMarkers; - }; -}).call(EditSession.prototype); -(function() { - this.ranges = null; - this.rangeList = null; - this.addRange = function(range, $blockChangeEvents) { - if (!range) - return; - - if (!this.inMultiSelectMode && this.rangeCount === 0) { - var oldRange = this.toOrientedRange(); - this.rangeList.add(oldRange); - this.rangeList.add(range); - if (this.rangeList.ranges.length != 2) { - this.rangeList.removeAll(); - return $blockChangeEvents || this.fromOrientedRange(range); - } - this.rangeList.removeAll(); - this.rangeList.add(oldRange); - this.$onAddRange(oldRange); - } - - if (!range.cursor) - range.cursor = range.end; - - var removed = this.rangeList.add(range); - - this.$onAddRange(range); - - if (removed.length) - this.$onRemoveRange(removed); - - if (this.rangeCount > 1 && !this.inMultiSelectMode) { - this._signal("multiSelect"); - this.inMultiSelectMode = true; - this.session.$undoSelect = false; - this.rangeList.attach(this.session); - } - - return $blockChangeEvents || this.fromOrientedRange(range); - }; - this.toSingleRange = function(range) { - range = range || this.ranges[0]; - var removed = this.rangeList.removeAll(); - if (removed.length) - this.$onRemoveRange(removed); - - range && this.fromOrientedRange(range); - }; - this.substractPoint = function(pos) { - var removed = this.rangeList.substractPoint(pos); - if (removed) { - this.$onRemoveRange(removed); - return removed[0]; - } - }; - this.mergeOverlappingRanges = function() { - var removed = this.rangeList.merge(); - if (removed.length) - this.$onRemoveRange(removed); - }; - - this.$onAddRange = function(range) { - this.rangeCount = this.rangeList.ranges.length; - this.ranges.unshift(range); - this._signal("addRange", {range: range}); - }; - - this.$onRemoveRange = function(removed) { - this.rangeCount = this.rangeList.ranges.length; - if (this.rangeCount == 1 && this.inMultiSelectMode) { - var lastRange = this.rangeList.ranges.pop(); - removed.push(lastRange); - this.rangeCount = 0; - } - - for (var i = removed.length; i--; ) { - var index = this.ranges.indexOf(removed[i]); - this.ranges.splice(index, 1); - } - - this._signal("removeRange", {ranges: removed}); - - if (this.rangeCount === 0 && this.inMultiSelectMode) { - this.inMultiSelectMode = false; - this._signal("singleSelect"); - this.session.$undoSelect = true; - this.rangeList.detach(this.session); - } - - lastRange = lastRange || this.ranges[0]; - if (lastRange && !lastRange.isEqual(this.getRange())) - this.fromOrientedRange(lastRange); - }; - this.$initRangeList = function() { - if (this.rangeList) - return; - - this.rangeList = new RangeList(); - this.ranges = []; - this.rangeCount = 0; - }; - this.getAllRanges = function() { - return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()]; - }; - this.splitIntoLines = function () { - var ranges = this.ranges.length ? this.ranges : [this.getRange()]; - var newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var row = range.start.row; - var endRow = range.end.row; - if (row === endRow) { - newRanges.push(range.clone()); - } else { - newRanges.push(new Range(row, range.start.column, row, this.session.getLine(row).length)); - while (++row < endRow) - newRanges.push(this.getLineRange(row, true)); - newRanges.push(new Range(endRow, 0, endRow, range.end.column)); - } - if (i == 0 && !this.isBackwards()) - newRanges = newRanges.reverse(); - } - this.toSingleRange(); - for (var i = newRanges.length; i--;) - this.addRange(newRanges[i]); - }; - - this.joinSelections = function () { - var ranges = this.rangeList.ranges; - var lastRange = ranges[ranges.length - 1]; - var range = Range.fromPoints(ranges[0].start, lastRange.end); - - this.toSingleRange(); - this.setSelectionRange(range, lastRange.cursor == lastRange.start); - }; - this.toggleBlockSelection = function () { - if (this.rangeCount > 1) { - var ranges = this.rangeList.ranges; - var lastRange = ranges[ranges.length - 1]; - var range = Range.fromPoints(ranges[0].start, lastRange.end); - - this.toSingleRange(); - this.setSelectionRange(range, lastRange.cursor == lastRange.start); - } else { - var cursor = this.session.documentToScreenPosition(this.cursor); - var anchor = this.session.documentToScreenPosition(this.anchor); - - var rectSel = this.rectangularRangeBlock(cursor, anchor); - rectSel.forEach(this.addRange, this); - } - }; - this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) { - var rectSel = []; - - var xBackwards = screenCursor.column < screenAnchor.column; - if (xBackwards) { - var startColumn = screenCursor.column; - var endColumn = screenAnchor.column; - var startOffsetX = screenCursor.offsetX; - var endOffsetX = screenAnchor.offsetX; - } else { - var startColumn = screenAnchor.column; - var endColumn = screenCursor.column; - var startOffsetX = screenAnchor.offsetX; - var endOffsetX = screenCursor.offsetX; - } - - var yBackwards = screenCursor.row < screenAnchor.row; - if (yBackwards) { - var startRow = screenCursor.row; - var endRow = screenAnchor.row; - } else { - var startRow = screenAnchor.row; - var endRow = screenCursor.row; - } - - if (startColumn < 0) - startColumn = 0; - if (startRow < 0) - startRow = 0; - - if (startRow == endRow) - includeEmptyLines = true; - - var docEnd; - for (var row = startRow; row <= endRow; row++) { - var range = Range.fromPoints( - this.session.screenToDocumentPosition(row, startColumn, startOffsetX), - this.session.screenToDocumentPosition(row, endColumn, endOffsetX) - ); - if (range.isEmpty()) { - if (docEnd && isSamePoint(range.end, docEnd)) - break; - docEnd = range.end; - } - range.cursor = xBackwards ? range.start : range.end; - rectSel.push(range); - } - - if (yBackwards) - rectSel.reverse(); - - if (!includeEmptyLines) { - var end = rectSel.length - 1; - while (rectSel[end].isEmpty() && end > 0) - end--; - if (end > 0) { - var start = 0; - while (rectSel[start].isEmpty()) - start++; - } - for (var i = end; i >= start; i--) { - if (rectSel[i].isEmpty()) - rectSel.splice(i, 1); - } - } - - return rectSel; - }; -}).call(Selection.prototype); -var Editor = require("./editor").Editor; -(function() { - this.updateSelectionMarkers = function() { - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - }; - this.addSelectionMarker = function(orientedRange) { - if (!orientedRange.cursor) - orientedRange.cursor = orientedRange.end; - - var style = this.getSelectionStyle(); - orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style); - - this.session.$selectionMarkers.push(orientedRange); - this.session.selectionMarkerCount = this.session.$selectionMarkers.length; - return orientedRange; - }; - this.removeSelectionMarker = function(range) { - if (!range.marker) - return; - this.session.removeMarker(range.marker); - var index = this.session.$selectionMarkers.indexOf(range); - if (index != -1) - this.session.$selectionMarkers.splice(index, 1); - this.session.selectionMarkerCount = this.session.$selectionMarkers.length; - }; - - this.removeSelectionMarkers = function(ranges) { - var markerList = this.session.$selectionMarkers; - for (var i = ranges.length; i--; ) { - var range = ranges[i]; - if (!range.marker) - continue; - this.session.removeMarker(range.marker); - var index = markerList.indexOf(range); - if (index != -1) - markerList.splice(index, 1); - } - this.session.selectionMarkerCount = markerList.length; - }; - - this.$onAddRange = function(e) { - this.addSelectionMarker(e.range); - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - }; - - this.$onRemoveRange = function(e) { - this.removeSelectionMarkers(e.ranges); - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - }; - - this.$onMultiSelect = function(e) { - if (this.inMultiSelectMode) - return; - this.inMultiSelectMode = true; - - this.setStyle("ace_multiselect"); - this.keyBinding.addKeyboardHandler(commands.keyboardHandler); - this.commands.setDefaultHandler("exec", this.$onMultiSelectExec); - - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - }; - - this.$onSingleSelect = function(e) { - if (this.session.multiSelect.inVirtualMode) - return; - this.inMultiSelectMode = false; - - this.unsetStyle("ace_multiselect"); - this.keyBinding.removeKeyboardHandler(commands.keyboardHandler); - - this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec); - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - this._emit("changeSelection"); - }; - - this.$onMultiSelectExec = function(e) { - var command = e.command; - var editor = e.editor; - if (!editor.multiSelect) - return; - if (!command.multiSelectAction) { - var result = command.exec(editor, e.args || {}); - editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); - editor.multiSelect.mergeOverlappingRanges(); - } else if (command.multiSelectAction == "forEach") { - result = editor.forEachSelection(command, e.args); - } else if (command.multiSelectAction == "forEachLine") { - result = editor.forEachSelection(command, e.args, true); - } else if (command.multiSelectAction == "single") { - editor.exitMultiSelectMode(); - result = command.exec(editor, e.args || {}); - } else { - result = command.multiSelectAction(editor, e.args || {}); - } - return result; - }; - this.forEachSelection = function(cmd, args, options) { - if (this.inVirtualSelectionMode) - return; - var keepOrder = options && options.keepOrder; - var $byLines = options == true || options && options.$byLines; - var session = this.session; - var selection = this.selection; - var rangeList = selection.rangeList; - var ranges = (keepOrder ? selection : rangeList).ranges; - var result; - - if (!ranges.length) - return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); - - var reg = selection._eventRegistry; - selection._eventRegistry = {}; - - var tmpSel = new Selection(session); - this.inVirtualSelectionMode = true; - for (var i = ranges.length; i--;) { - if ($byLines) { - while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row) - i--; - } - tmpSel.fromOrientedRange(ranges[i]); - tmpSel.index = i; - this.selection = session.selection = tmpSel; - var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); - if (!result && cmdResult !== undefined) - result = cmdResult; - tmpSel.toOrientedRange(ranges[i]); - } - tmpSel.detach(); - - this.selection = session.selection = selection; - this.inVirtualSelectionMode = false; - selection._eventRegistry = reg; - selection.mergeOverlappingRanges(); - if (selection.ranges[0]) - selection.fromOrientedRange(selection.ranges[0]); - - var anim = this.renderer.$scrollAnimation; - this.onCursorChange(); - this.onSelectionChange(); - if (anim && anim.from == anim.to) - this.renderer.animateScrolling(anim.from); - - return result; - }; - this.exitMultiSelectMode = function() { - if (!this.inMultiSelectMode || this.inVirtualSelectionMode) - return; - this.multiSelect.toSingleRange(); - }; - - this.getSelectedText = function() { - var text = ""; - if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { - var ranges = this.multiSelect.rangeList.ranges; - var buf = []; - for (var i = 0; i < ranges.length; i++) { - buf.push(this.session.getTextRange(ranges[i])); - } - var nl = this.session.getDocument().getNewLineCharacter(); - text = buf.join(nl); - if (text.length == (buf.length - 1) * nl.length) - text = ""; - } else if (!this.selection.isEmpty()) { - text = this.session.getTextRange(this.getSelectionRange()); - } - return text; - }; - - this.$checkMultiselectChange = function(e, anchor) { - if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { - var range = this.multiSelect.ranges[0]; - if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor) - return; - var pos = anchor == this.multiSelect.anchor - ? range.cursor == range.start ? range.end : range.start - : range.cursor; - if (pos.row != anchor.row - || this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column) - this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange()); - else - this.multiSelect.mergeOverlappingRanges(); - } - }; - this.findAll = function(needle, options, additive) { - options = options || {}; - options.needle = needle || options.needle; - if (options.needle == undefined) { - var range = this.selection.isEmpty() - ? this.selection.getWordRange() - : this.selection.getRange(); - options.needle = this.session.getTextRange(range); - } - this.$search.set(options); - - var ranges = this.$search.findAll(this.session); - if (!ranges.length) - return 0; - - var selection = this.multiSelect; - - if (!additive) - selection.toSingleRange(ranges[0]); - - for (var i = ranges.length; i--; ) - selection.addRange(ranges[i], true); - if (range && selection.rangeList.rangeAtPoint(range.start)) - selection.addRange(range, true); - - return ranges.length; - }; - this.selectMoreLines = function(dir, skip) { - var range = this.selection.toOrientedRange(); - var isBackwards = range.cursor == range.end; - - var screenLead = this.session.documentToScreenPosition(range.cursor); - if (this.selection.$desiredColumn) - screenLead.column = this.selection.$desiredColumn; - - var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column); - - if (!range.isEmpty()) { - var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start); - var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column); - } else { - var anchor = lead; - } - - if (isBackwards) { - var newRange = Range.fromPoints(lead, anchor); - newRange.cursor = newRange.start; - } else { - var newRange = Range.fromPoints(anchor, lead); - newRange.cursor = newRange.end; - } - - newRange.desiredColumn = screenLead.column; - if (!this.selection.inMultiSelectMode) { - this.selection.addRange(range); - } else { - if (skip) - var toRemove = range.cursor; - } - - this.selection.addRange(newRange); - if (toRemove) - this.selection.substractPoint(toRemove); - }; - this.transposeSelections = function(dir) { - var session = this.session; - var sel = session.multiSelect; - var all = sel.ranges; - - for (var i = all.length; i--; ) { - var range = all[i]; - if (range.isEmpty()) { - var tmp = session.getWordRange(range.start.row, range.start.column); - range.start.row = tmp.start.row; - range.start.column = tmp.start.column; - range.end.row = tmp.end.row; - range.end.column = tmp.end.column; - } - } - sel.mergeOverlappingRanges(); - - var words = []; - for (var i = all.length; i--; ) { - var range = all[i]; - words.unshift(session.getTextRange(range)); - } - - if (dir < 0) - words.unshift(words.pop()); - else - words.push(words.shift()); - - for (var i = all.length; i--; ) { - var range = all[i]; - var tmp = range.clone(); - session.replace(range, words[i]); - range.start.row = tmp.start.row; - range.start.column = tmp.start.column; - } - sel.fromOrientedRange(sel.ranges[0]); - }; - this.selectMore = function(dir, skip, stopAtFirst) { - var session = this.session; - var sel = session.multiSelect; - - var range = sel.toOrientedRange(); - if (range.isEmpty()) { - range = session.getWordRange(range.start.row, range.start.column); - range.cursor = dir == -1 ? range.start : range.end; - this.multiSelect.addRange(range); - if (stopAtFirst) - return; - } - var needle = session.getTextRange(range); - - var newRange = find(session, needle, dir); - if (newRange) { - newRange.cursor = dir == -1 ? newRange.start : newRange.end; - this.session.unfold(newRange); - this.multiSelect.addRange(newRange); - this.renderer.scrollCursorIntoView(null, 0.5); - } - if (skip) - this.multiSelect.substractPoint(range.cursor); - }; - this.alignCursors = function() { - var session = this.session; - var sel = session.multiSelect; - var ranges = sel.ranges; - var row = -1; - var sameRowRanges = ranges.filter(function(r) { - if (r.cursor.row == row) - return true; - row = r.cursor.row; - }); - - if (!ranges.length || sameRowRanges.length == ranges.length - 1) { - var range = this.selection.getRange(); - var fr = range.start.row, lr = range.end.row; - var guessRange = fr == lr; - if (guessRange) { - var max = this.session.getLength(); - var line; - do { - line = this.session.getLine(lr); - } while (/[=:]/.test(line) && ++lr < max); - do { - line = this.session.getLine(fr); - } while (/[=:]/.test(line) && --fr > 0); - - if (fr < 0) fr = 0; - if (lr >= max) lr = max - 1; - } - var lines = this.session.removeFullLines(fr, lr); - lines = this.$reAlignText(lines, guessRange); - this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n"); - if (!guessRange) { - range.start.column = 0; - range.end.column = lines[lines.length - 1].length; - } - this.selection.setRange(range); - } else { - sameRowRanges.forEach(function(r) { - sel.substractPoint(r.cursor); - }); - - var maxCol = 0; - var minSpace = Infinity; - var spaceOffsets = ranges.map(function(r) { - var p = r.cursor; - var line = session.getLine(p.row); - var spaceOffset = line.substr(p.column).search(/\S/g); - if (spaceOffset == -1) - spaceOffset = 0; - - if (p.column > maxCol) - maxCol = p.column; - if (spaceOffset < minSpace) - minSpace = spaceOffset; - return spaceOffset; - }); - ranges.forEach(function(r, i) { - var p = r.cursor; - var l = maxCol - p.column; - var d = spaceOffsets[i] - minSpace; - if (l > d) - session.insert(p, lang.stringRepeat(" ", l - d)); - else - session.remove(new Range(p.row, p.column, p.row, p.column - l + d)); - - r.start.column = r.end.column = maxCol; - r.start.row = r.end.row = p.row; - r.cursor = r.end; - }); - sel.fromOrientedRange(ranges[0]); - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - } - }; - - this.$reAlignText = function(lines, forceLeft) { - var isLeftAligned = true, isRightAligned = true; - var startW, textW, endW; - - return lines.map(function(line) { - var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/); - if (!m) - return [line]; - - if (startW == null) { - startW = m[1].length; - textW = m[2].length; - endW = m[3].length; - return m; - } - - if (startW + textW + endW != m[1].length + m[2].length + m[3].length) - isRightAligned = false; - if (startW != m[1].length) - isLeftAligned = false; - - if (startW > m[1].length) - startW = m[1].length; - if (textW < m[2].length) - textW = m[2].length; - if (endW > m[3].length) - endW = m[3].length; - - return m; - }).map(forceLeft ? alignLeft : - isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign); - - function spaces(n) { - return lang.stringRepeat(" ", n); - } - - function alignLeft(m) { - return !m[2] ? m[0] : spaces(startW) + m[2] - + spaces(textW - m[2].length + endW) - + m[4].replace(/^([=:])\s+/, "$1 "); - } - function alignRight(m) { - return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2] - + spaces(endW) - + m[4].replace(/^([=:])\s+/, "$1 "); - } - function unAlign(m) { - return !m[2] ? m[0] : spaces(startW) + m[2] - + spaces(endW) - + m[4].replace(/^([=:])\s+/, "$1 "); - } - }; -}).call(Editor.prototype); - - -function isSamePoint(p1, p2) { - return p1.row == p2.row && p1.column == p2.column; -} -exports.onSessionChange = function(e) { - var session = e.session; - if (session && !session.multiSelect) { - session.$selectionMarkers = []; - session.selection.$initRangeList(); - session.multiSelect = session.selection; - } - this.multiSelect = session && session.multiSelect; - - var oldSession = e.oldSession; - if (oldSession) { - oldSession.multiSelect.off("addRange", this.$onAddRange); - oldSession.multiSelect.off("removeRange", this.$onRemoveRange); - oldSession.multiSelect.off("multiSelect", this.$onMultiSelect); - oldSession.multiSelect.off("singleSelect", this.$onSingleSelect); - oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange); - oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange); - } - - if (session) { - session.multiSelect.on("addRange", this.$onAddRange); - session.multiSelect.on("removeRange", this.$onRemoveRange); - session.multiSelect.on("multiSelect", this.$onMultiSelect); - session.multiSelect.on("singleSelect", this.$onSingleSelect); - session.multiSelect.lead.on("change", this.$checkMultiselectChange); - session.multiSelect.anchor.on("change", this.$checkMultiselectChange); - } - - if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) { - if (session.selection.inMultiSelectMode) - this.$onMultiSelect(); - else - this.$onSingleSelect(); - } -}; -function MultiSelect(editor) { - if (editor.$multiselectOnSessionChange) - return; - editor.$onAddRange = editor.$onAddRange.bind(editor); - editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); - editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); - editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); - editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor); - editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor); - - editor.$multiselectOnSessionChange(editor); - editor.on("changeSession", editor.$multiselectOnSessionChange); - - editor.on("mousedown", onMouseDown); - editor.commands.addCommands(commands.defaultCommands); - - addAltCursorListeners(editor); -} - -function addAltCursorListeners(editor){ - if (!editor.textInput) return; - var el = editor.textInput.getElement(); - var altCursor = false; - event.addListener(el, "keydown", function(e) { - var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey); - if (editor.$blockSelectEnabled && altDown) { - if (!altCursor) { - editor.renderer.setMouseCursor("crosshair"); - altCursor = true; - } - } else if (altCursor) { - reset(); - } - }, editor); - - event.addListener(el, "keyup", reset, editor); - event.addListener(el, "blur", reset, editor); - function reset(e) { - if (altCursor) { - editor.renderer.setMouseCursor(""); - altCursor = false; - } - } -} - -exports.MultiSelect = MultiSelect; - - -require("./config").defineOptions(Editor.prototype, "editor", { - enableMultiselect: { - set: function(val) { - MultiSelect(this); - if (val) { - this.on("changeSession", this.$multiselectOnSessionChange); - this.on("mousedown", onMouseDown); - } else { - this.off("changeSession", this.$multiselectOnSessionChange); - this.off("mousedown", onMouseDown); - } - }, - value: true - }, - enableBlockSelect: { - set: function(val) { - this.$blockSelectEnabled = val; - }, - value: true - } -}); - - - -}); - -define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(require, exports, module) { -"use strict"; - -var Range = require("../../range").Range; - -var FoldMode = exports.FoldMode = function() {}; - -(function() { - - this.foldingStartMarker = null; - this.foldingStopMarker = null; - this.getFoldWidget = function(session, foldStyle, row) { - var line = session.getLine(row); - if (this.foldingStartMarker.test(line)) - return "start"; - if (foldStyle == "markbeginend" - && this.foldingStopMarker - && this.foldingStopMarker.test(line)) - return "end"; - return ""; - }; - - this.getFoldWidgetRange = function(session, foldStyle, row) { - return null; - }; - - this.indentationBlock = function(session, row, column) { - var re = /\S/; - var line = session.getLine(row); - var startLevel = line.search(re); - if (startLevel == -1) - return; - - var startColumn = column || line.length; - var maxRow = session.getLength(); - var startRow = row; - var endRow = row; - - while (++row < maxRow) { - var level = session.getLine(row).search(re); - - if (level == -1) - continue; - - if (level <= startLevel) { - var token = session.getTokenAt(row, 0); - if (!token || token.type !== "string") - break; - } - - endRow = row; - } - - if (endRow > startRow) { - var endColumn = session.getLine(endRow).length; - return new Range(startRow, startColumn, endRow, endColumn); - } - }; - - this.openingBracketBlock = function(session, bracket, row, column, typeRe) { - var start = {row: row, column: column + 1}; - var end = session.$findClosingBracket(bracket, start, typeRe); - if (!end) - return; - - var fw = session.foldWidgets[end.row]; - if (fw == null) - fw = session.getFoldWidget(end.row); - - if (fw == "start" && end.row > start.row) { - end.row --; - end.column = session.getLine(end.row).length; - } - return Range.fromPoints(start, end); - }; - - this.closingBracketBlock = function(session, bracket, row, column, typeRe) { - var end = {row: row, column: column}; - var start = session.$findOpeningBracket(bracket, end); - - if (!start) - return; - - start.column++; - end.column--; - - return Range.fromPoints(start, end); - }; -}).call(FoldMode.prototype); - -}); - -define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -exports.isDark = false; -exports.cssClass = "ace-tm"; -exports.cssText = ".ace-tm .ace_gutter {\ -background: #f0f0f0;\ -color: #333;\ -}\ -.ace-tm .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8;\ -}\ -.ace-tm .ace_fold {\ -background-color: #6B72E6;\ -}\ -.ace-tm {\ -background-color: #FFFFFF;\ -color: black;\ -}\ -.ace-tm .ace_cursor {\ -color: black;\ -}\ -.ace-tm .ace_invisible {\ -color: rgb(191, 191, 191);\ -}\ -.ace-tm .ace_storage,\ -.ace-tm .ace_keyword {\ -color: blue;\ -}\ -.ace-tm .ace_constant {\ -color: rgb(197, 6, 11);\ -}\ -.ace-tm .ace_constant.ace_buildin {\ -color: rgb(88, 72, 246);\ -}\ -.ace-tm .ace_constant.ace_language {\ -color: rgb(88, 92, 246);\ -}\ -.ace-tm .ace_constant.ace_library {\ -color: rgb(6, 150, 14);\ -}\ -.ace-tm .ace_invalid {\ -background-color: rgba(255, 0, 0, 0.1);\ -color: red;\ -}\ -.ace-tm .ace_support.ace_function {\ -color: rgb(60, 76, 114);\ -}\ -.ace-tm .ace_support.ace_constant {\ -color: rgb(6, 150, 14);\ -}\ -.ace-tm .ace_support.ace_type,\ -.ace-tm .ace_support.ace_class {\ -color: rgb(109, 121, 222);\ -}\ -.ace-tm .ace_keyword.ace_operator {\ -color: rgb(104, 118, 135);\ -}\ -.ace-tm .ace_string {\ -color: rgb(3, 106, 7);\ -}\ -.ace-tm .ace_comment {\ -color: rgb(76, 136, 107);\ -}\ -.ace-tm .ace_comment.ace_doc {\ -color: rgb(0, 102, 255);\ -}\ -.ace-tm .ace_comment.ace_doc.ace_tag {\ -color: rgb(128, 159, 191);\ -}\ -.ace-tm .ace_constant.ace_numeric {\ -color: rgb(0, 0, 205);\ -}\ -.ace-tm .ace_variable {\ -color: rgb(49, 132, 149);\ -}\ -.ace-tm .ace_xml-pe {\ -color: rgb(104, 104, 91);\ -}\ -.ace-tm .ace_entity.ace_name.ace_function {\ -color: #0000A2;\ -}\ -.ace-tm .ace_heading {\ -color: rgb(12, 7, 255);\ -}\ -.ace-tm .ace_list {\ -color:rgb(185, 6, 144);\ -}\ -.ace-tm .ace_meta.ace_tag {\ -color:rgb(0, 22, 142);\ -}\ -.ace-tm .ace_string.ace_regex {\ -color: rgb(255, 0, 0)\ -}\ -.ace-tm .ace_marker-layer .ace_selection {\ -background: rgb(181, 213, 255);\ -}\ -.ace-tm.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px white;\ -}\ -.ace-tm .ace_marker-layer .ace_step {\ -background: rgb(252, 255, 0);\ -}\ -.ace-tm .ace_marker-layer .ace_stack {\ -background: rgb(164, 229, 101);\ -}\ -.ace-tm .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgb(192, 192, 192);\ -}\ -.ace-tm .ace_marker-layer .ace_active-line {\ -background: rgba(0, 0, 0, 0.07);\ -}\ -.ace-tm .ace_gutter-active-line {\ -background-color : #dcdcdc;\ -}\ -.ace-tm .ace_marker-layer .ace_selected-word {\ -background: rgb(250, 250, 255);\ -border: 1px solid rgb(200, 200, 250);\ -}\ -.ace-tm .ace_indent-guide {\ -background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ -}\ -"; -exports.$id = "ace/theme/textmate"; - -var dom = require("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass, false); -}); - -define("ace/line_widgets",["require","exports","module","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -var dom = require("./lib/dom"); - -function LineWidgets(session) { - this.session = session; - this.session.widgetManager = this; - this.session.getRowLength = this.getRowLength; - this.session.$getWidgetScreenLength = this.$getWidgetScreenLength; - this.updateOnChange = this.updateOnChange.bind(this); - this.renderWidgets = this.renderWidgets.bind(this); - this.measureWidgets = this.measureWidgets.bind(this); - this.session._changedWidgets = []; - this.$onChangeEditor = this.$onChangeEditor.bind(this); - - this.session.on("change", this.updateOnChange); - this.session.on("changeFold", this.updateOnFold); - this.session.on("changeEditor", this.$onChangeEditor); -} - -(function() { - this.getRowLength = function(row) { - var h; - if (this.lineWidgets) - h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; - else - h = 0; - if (!this.$useWrapMode || !this.$wrapData[row]) { - return 1 + h; - } else { - return this.$wrapData[row].length + 1 + h; - } - }; - - this.$getWidgetScreenLength = function() { - var screenRows = 0; - this.lineWidgets.forEach(function(w){ - if (w && w.rowCount && !w.hidden) - screenRows += w.rowCount; - }); - return screenRows; - }; - - this.$onChangeEditor = function(e) { - this.attach(e.editor); - }; - - this.attach = function(editor) { - if (editor && editor.widgetManager && editor.widgetManager != this) - editor.widgetManager.detach(); - - if (this.editor == editor) - return; - - this.detach(); - this.editor = editor; - - if (editor) { - editor.widgetManager = this; - editor.renderer.on("beforeRender", this.measureWidgets); - editor.renderer.on("afterRender", this.renderWidgets); - } - }; - this.detach = function(e) { - var editor = this.editor; - if (!editor) - return; - - this.editor = null; - editor.widgetManager = null; - - editor.renderer.off("beforeRender", this.measureWidgets); - editor.renderer.off("afterRender", this.renderWidgets); - var lineWidgets = this.session.lineWidgets; - lineWidgets && lineWidgets.forEach(function(w) { - if (w && w.el && w.el.parentNode) { - w._inDocument = false; - w.el.parentNode.removeChild(w.el); - } - }); - }; - - this.updateOnFold = function(e, session) { - var lineWidgets = session.lineWidgets; - if (!lineWidgets || !e.action) - return; - var fold = e.data; - var start = fold.start.row; - var end = fold.end.row; - var hide = e.action == "add"; - for (var i = start + 1; i < end; i++) { - if (lineWidgets[i]) - lineWidgets[i].hidden = hide; - } - if (lineWidgets[end]) { - if (hide) { - if (!lineWidgets[start]) - lineWidgets[start] = lineWidgets[end]; - else - lineWidgets[end].hidden = hide; - } else { - if (lineWidgets[start] == lineWidgets[end]) - lineWidgets[start] = undefined; - lineWidgets[end].hidden = hide; - } - } - }; - - this.updateOnChange = function(delta) { - var lineWidgets = this.session.lineWidgets; - if (!lineWidgets) return; - - var startRow = delta.start.row; - var len = delta.end.row - startRow; - - if (len === 0) { - } else if (delta.action == "remove") { - var removed = lineWidgets.splice(startRow + 1, len); - if (!lineWidgets[startRow] && removed[removed.length - 1]) { - lineWidgets[startRow] = removed.pop(); - } - removed.forEach(function(w) { - w && this.removeLineWidget(w); - }, this); - this.$updateRows(); - } else { - var args = new Array(len); - if (lineWidgets[startRow] && lineWidgets[startRow].column != null) { - if (delta.start.column > lineWidgets[startRow].column) - startRow++; - } - args.unshift(startRow, 0); - lineWidgets.splice.apply(lineWidgets, args); - this.$updateRows(); - } - }; - - this.$updateRows = function() { - var lineWidgets = this.session.lineWidgets; - if (!lineWidgets) return; - var noWidgets = true; - lineWidgets.forEach(function(w, i) { - if (w) { - noWidgets = false; - w.row = i; - while (w.$oldWidget) { - w.$oldWidget.row = i; - w = w.$oldWidget; - } - } - }); - if (noWidgets) - this.session.lineWidgets = null; - }; - - this.$registerLineWidget = function(w) { - if (!this.session.lineWidgets) - this.session.lineWidgets = new Array(this.session.getLength()); - - var old = this.session.lineWidgets[w.row]; - if (old) { - w.$oldWidget = old; - if (old.el && old.el.parentNode) { - old.el.parentNode.removeChild(old.el); - old._inDocument = false; - } - } - - this.session.lineWidgets[w.row] = w; - return w; - }; - - this.addLineWidget = function(w) { - this.$registerLineWidget(w); - w.session = this.session; - - if (!this.editor) return w; - - var renderer = this.editor.renderer; - if (w.html && !w.el) { - w.el = dom.createElement("div"); - w.el.innerHTML = w.html; - } - if (w.el) { - dom.addCssClass(w.el, "ace_lineWidgetContainer"); - w.el.style.position = "absolute"; - w.el.style.zIndex = 5; - renderer.container.appendChild(w.el); - w._inDocument = true; - - if (!w.coverGutter) { - w.el.style.zIndex = 3; - } - if (w.pixelHeight == null) { - w.pixelHeight = w.el.offsetHeight; - } - } - if (w.rowCount == null) { - w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight; - } - - var fold = this.session.getFoldAt(w.row, 0); - w.$fold = fold; - if (fold) { - var lineWidgets = this.session.lineWidgets; - if (w.row == fold.end.row && !lineWidgets[fold.start.row]) - lineWidgets[fold.start.row] = w; - else - w.hidden = true; - } - - this.session._emit("changeFold", {data:{start:{row: w.row}}}); - - this.$updateRows(); - this.renderWidgets(null, renderer); - this.onWidgetChanged(w); - return w; - }; - - this.removeLineWidget = function(w) { - w._inDocument = false; - w.session = null; - if (w.el && w.el.parentNode) - w.el.parentNode.removeChild(w.el); - if (w.editor && w.editor.destroy) try { - w.editor.destroy(); - } catch(e){} - if (this.session.lineWidgets) { - var w1 = this.session.lineWidgets[w.row]; - if (w1 == w) { - this.session.lineWidgets[w.row] = w.$oldWidget; - if (w.$oldWidget) - this.onWidgetChanged(w.$oldWidget); - } else { - while (w1) { - if (w1.$oldWidget == w) { - w1.$oldWidget = w.$oldWidget; - break; - } - w1 = w1.$oldWidget; - } - } - } - this.session._emit("changeFold", {data:{start:{row: w.row}}}); - this.$updateRows(); - }; - - this.getWidgetsAtRow = function(row) { - var lineWidgets = this.session.lineWidgets; - var w = lineWidgets && lineWidgets[row]; - var list = []; - while (w) { - list.push(w); - w = w.$oldWidget; - } - return list; - }; - - this.onWidgetChanged = function(w) { - this.session._changedWidgets.push(w); - this.editor && this.editor.renderer.updateFull(); - }; - - this.measureWidgets = function(e, renderer) { - var changedWidgets = this.session._changedWidgets; - var config = renderer.layerConfig; - - if (!changedWidgets || !changedWidgets.length) return; - var min = Infinity; - for (var i = 0; i < changedWidgets.length; i++) { - var w = changedWidgets[i]; - if (!w || !w.el) continue; - if (w.session != this.session) continue; - if (!w._inDocument) { - if (this.session.lineWidgets[w.row] != w) - continue; - w._inDocument = true; - renderer.container.appendChild(w.el); - } - - w.h = w.el.offsetHeight; - - if (!w.fixedWidth) { - w.w = w.el.offsetWidth; - w.screenWidth = Math.ceil(w.w / config.characterWidth); - } - - var rowCount = w.h / config.lineHeight; - if (w.coverLine) { - rowCount -= this.session.getRowLineCount(w.row); - if (rowCount < 0) - rowCount = 0; - } - if (w.rowCount != rowCount) { - w.rowCount = rowCount; - if (w.row < min) - min = w.row; - } - } - if (min != Infinity) { - this.session._emit("changeFold", {data:{start:{row: min}}}); - this.session.lineWidgetWidth = null; - } - this.session._changedWidgets = []; - }; - - this.renderWidgets = function(e, renderer) { - var config = renderer.layerConfig; - var lineWidgets = this.session.lineWidgets; - if (!lineWidgets) - return; - var first = Math.min(this.firstRow, config.firstRow); - var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length); - - while (first > 0 && !lineWidgets[first]) - first--; - - this.firstRow = config.firstRow; - this.lastRow = config.lastRow; - - renderer.$cursorLayer.config = config; - for (var i = first; i <= last; i++) { - var w = lineWidgets[i]; - if (!w || !w.el) continue; - if (w.hidden) { - w.el.style.top = -100 - (w.pixelHeight || 0) + "px"; - continue; - } - if (!w._inDocument) { - w._inDocument = true; - renderer.container.appendChild(w.el); - } - var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top; - if (!w.coverLine) - top += config.lineHeight * this.session.getRowLineCount(w.row); - w.el.style.top = top - config.offset + "px"; - - var left = w.coverGutter ? 0 : renderer.gutterWidth; - if (!w.fixedWidth) - left -= renderer.scrollLeft; - w.el.style.left = left + "px"; - - if (w.fullWidth && w.screenWidth) { - w.el.style.minWidth = config.width + 2 * config.padding + "px"; - } - - if (w.fixedWidth) { - w.el.style.right = renderer.scrollBar.getWidth() + "px"; - } else { - w.el.style.right = ""; - } - } - }; - -}).call(LineWidgets.prototype); - - -exports.LineWidgets = LineWidgets; - -}); - -define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(require, exports, module) { -"use strict"; -var LineWidgets = require("../line_widgets").LineWidgets; -var dom = require("../lib/dom"); -var Range = require("../range").Range; - -function binarySearch(array, needle, comparator) { - var first = 0; - var last = array.length - 1; - - while (first <= last) { - var mid = (first + last) >> 1; - var c = comparator(needle, array[mid]); - if (c > 0) - first = mid + 1; - else if (c < 0) - last = mid - 1; - else - return mid; - } - return -(first + 1); -} - -function findAnnotations(session, row, dir) { - var annotations = session.getAnnotations().sort(Range.comparePoints); - if (!annotations.length) - return; - - var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints); - if (i < 0) - i = -i - 1; - - if (i >= annotations.length) - i = dir > 0 ? 0 : annotations.length - 1; - else if (i === 0 && dir < 0) - i = annotations.length - 1; - - var annotation = annotations[i]; - if (!annotation || !dir) - return; - - if (annotation.row === row) { - do { - annotation = annotations[i += dir]; - } while (annotation && annotation.row === row); - if (!annotation) - return annotations.slice(); - } - - - var matched = []; - row = annotation.row; - do { - matched[dir < 0 ? "unshift" : "push"](annotation); - annotation = annotations[i += dir]; - } while (annotation && annotation.row == row); - return matched.length && matched; -} - -exports.showErrorMarker = function(editor, dir) { - var session = editor.session; - if (!session.widgetManager) { - session.widgetManager = new LineWidgets(session); - session.widgetManager.attach(editor); - } - - var pos = editor.getCursorPosition(); - var row = pos.row; - var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) { - return w.type == "errorMarker"; - })[0]; - if (oldWidget) { - oldWidget.destroy(); - } else { - row -= dir; - } - var annotations = findAnnotations(session, row, dir); - var gutterAnno; - if (annotations) { - var annotation = annotations[0]; - pos.column = (annotation.pos && typeof annotation.column != "number" - ? annotation.pos.sc - : annotation.column) || 0; - pos.row = annotation.row; - gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row]; - } else if (oldWidget) { - return; - } else { - gutterAnno = { - text: ["Looks good!"], - className: "ace_ok" - }; - } - editor.session.unfold(pos.row); - editor.selection.moveToPosition(pos); - - var w = { - row: pos.row, - fixedWidth: true, - coverGutter: true, - el: dom.createElement("div"), - type: "errorMarker" - }; - var el = w.el.appendChild(dom.createElement("div")); - var arrow = w.el.appendChild(dom.createElement("div")); - arrow.className = "error_widget_arrow " + gutterAnno.className; - - var left = editor.renderer.$cursorLayer - .getPixelPosition(pos).left; - arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px"; - - w.el.className = "error_widget_wrapper"; - el.className = "error_widget " + gutterAnno.className; - el.innerHTML = gutterAnno.text.join("
"); - - el.appendChild(dom.createElement("div")); - - var kb = function(_, hashId, keyString) { - if (hashId === 0 && (keyString === "esc" || keyString === "return")) { - w.destroy(); - return {command: "null"}; - } - }; - - w.destroy = function() { - if (editor.$mouseHandler.isMousePressed) - return; - editor.keyBinding.removeKeyboardHandler(kb); - session.widgetManager.removeLineWidget(w); - editor.off("changeSelection", w.destroy); - editor.off("changeSession", w.destroy); - editor.off("mouseup", w.destroy); - editor.off("change", w.destroy); - }; - - editor.keyBinding.addKeyboardHandler(kb); - editor.on("changeSelection", w.destroy); - editor.on("changeSession", w.destroy); - editor.on("mouseup", w.destroy); - editor.on("change", w.destroy); - - editor.session.widgetManager.addLineWidget(w); - - w.el.onmousedown = editor.focus.bind(editor); - - editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight}); -}; - - -dom.importCssString("\ - .error_widget_wrapper {\ - background: inherit;\ - color: inherit;\ - border:none\ - }\ - .error_widget {\ - border-top: solid 2px;\ - border-bottom: solid 2px;\ - margin: 5px 0;\ - padding: 10px 40px;\ - white-space: pre-wrap;\ - }\ - .error_widget.ace_error, .error_widget_arrow.ace_error{\ - border-color: #ff5a5a\ - }\ - .error_widget.ace_warning, .error_widget_arrow.ace_warning{\ - border-color: #F1D817\ - }\ - .error_widget.ace_info, .error_widget_arrow.ace_info{\ - border-color: #5a5a5a\ - }\ - .error_widget.ace_ok, .error_widget_arrow.ace_ok{\ - border-color: #5aaa5a\ - }\ - .error_widget_arrow {\ - position: absolute;\ - border: solid 5px;\ - border-top-color: transparent!important;\ - border-right-color: transparent!important;\ - border-left-color: transparent!important;\ - top: -5px;\ - }\ -", "error_marker.css", false); - -}); - -define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/range","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(require, exports, module) { -"use strict"; - -require("./lib/fixoldbrowsers"); - -var dom = require("./lib/dom"); -var event = require("./lib/event"); - -var Range = require("./range").Range; -var Editor = require("./editor").Editor; -var EditSession = require("./edit_session").EditSession; -var UndoManager = require("./undomanager").UndoManager; -var Renderer = require("./virtual_renderer").VirtualRenderer; -require("./worker/worker_client"); -require("./keyboard/hash_handler"); -require("./placeholder"); -require("./multi_select"); -require("./mode/folding/fold_mode"); -require("./theme/textmate"); -require("./ext/error_marker"); - -exports.config = require("./config"); -exports.require = require; - -if (typeof define === "function") - exports.define = define; -exports.edit = function(el, options) { - if (typeof el == "string") { - var _id = el; - el = document.getElementById(_id); - if (!el) - throw new Error("ace.edit can't find div #" + _id); - } - - if (el && el.env && el.env.editor instanceof Editor) - return el.env.editor; - - var value = ""; - if (el && /input|textarea/i.test(el.tagName)) { - var oldNode = el; - value = oldNode.value; - el = dom.createElement("pre"); - oldNode.parentNode.replaceChild(el, oldNode); - } else if (el) { - value = el.textContent; - el.innerHTML = ""; - } - - var doc = exports.createEditSession(value); - - var editor = new Editor(new Renderer(el), doc, options); - - var env = { - document: doc, - editor: editor, - onResize: editor.resize.bind(editor, null) - }; - if (oldNode) env.textarea = oldNode; - event.addListener(window, "resize", env.onResize); - editor.on("destroy", function() { - event.removeListener(window, "resize", env.onResize); - env.editor.container.env = null; // prevent memory leak on old ie - }); - editor.container.env = editor.env = env; - return editor; -}; -exports.createEditSession = function(text, mode) { - var doc = new EditSession(text, mode); - doc.setUndoManager(new UndoManager()); - return doc; -}; -exports.Range = Range; -exports.Editor = Editor; -exports.EditSession = EditSession; -exports.UndoManager = UndoManager; -exports.VirtualRenderer = Renderer; -exports.version = exports.config.version; -}); (function() { - window.require(["ace/ace"], function(a) { - if (a) { - a.config.init(true); - a.define = window.define; - } - if (!window.ace) - window.ace = a; - for (var key in a) if (a.hasOwnProperty(key)) - window.ace[key] = a[key]; - window.ace["default"] = window.ace; - if (typeof module == "object" && typeof exports == "object" && module) { - module.exports = window.ace; - } - }); - })(); - \ No newline at end of file diff --git a/GameDev/bin/Release/editor/ace/ext-prompt.js b/GameDev/bin/Release/editor/ace/ext-prompt.js deleted file mode 100644 index 34d7e36d..00000000 --- a/GameDev/bin/Release/editor/ace/ext-prompt.js +++ /dev/null @@ -1,2806 +0,0 @@ -define("ace/ext/menu_tools/get_editor_keyboard_shortcuts",["require","exports","module","ace/lib/keys"], function(require, exports, module) { -"use strict"; -var keys = require("../../lib/keys"); -module.exports.getEditorKeybordShortcuts = function(editor) { - var KEY_MODS = keys.KEY_MODS; - var keybindings = []; - var commandMap = {}; - editor.keyBinding.$handlers.forEach(function(handler) { - var ckb = handler.commandKeyBinding; - for (var i in ckb) { - var key = i.replace(/(^|-)\w/g, function(x) { return x.toUpperCase(); }); - var commands = ckb[i]; - if (!Array.isArray(commands)) - commands = [commands]; - commands.forEach(function(command) { - if (typeof command != "string") - command = command.name; - if (commandMap[command]) { - commandMap[command].key += "|" + key; - } else { - commandMap[command] = {key: key, command: command}; - keybindings.push(commandMap[command]); - } - }); - } - }); - return keybindings; -}; - -}); - -define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(require, exports, module) { -"use strict"; - -var Renderer = require("../virtual_renderer").VirtualRenderer; -var Editor = require("../editor").Editor; -var Range = require("../range").Range; -var event = require("../lib/event"); -var lang = require("../lib/lang"); -var dom = require("../lib/dom"); - -var $singleLineEditor = function(el) { - var renderer = new Renderer(el); - - renderer.$maxLines = 4; - - var editor = new Editor(renderer); - - editor.setHighlightActiveLine(false); - editor.setShowPrintMargin(false); - editor.renderer.setShowGutter(false); - editor.renderer.setHighlightGutterLine(false); - - editor.$mouseHandler.$focusTimeout = 0; - editor.$highlightTagPending = true; - - return editor; -}; - -var AcePopup = function(parentNode) { - var el = dom.createElement("div"); - var popup = new $singleLineEditor(el); - - if (parentNode) - parentNode.appendChild(el); - el.style.display = "none"; - popup.renderer.content.style.cursor = "default"; - popup.renderer.setStyle("ace_autocomplete"); - - popup.setOption("displayIndentGuides", false); - popup.setOption("dragDelay", 150); - - var noop = function(){}; - - popup.focus = noop; - popup.$isFocused = true; - - popup.renderer.$cursorLayer.restartTimer = noop; - popup.renderer.$cursorLayer.element.style.opacity = 0; - - popup.renderer.$maxLines = 8; - popup.renderer.$keepTextAreaAtCursor = false; - - popup.setHighlightActiveLine(false); - popup.session.highlight(""); - popup.session.$searchHighlight.clazz = "ace_highlight-marker"; - - popup.on("mousedown", function(e) { - var pos = e.getDocumentPosition(); - popup.selection.moveToPosition(pos); - selectionMarker.start.row = selectionMarker.end.row = pos.row; - e.stop(); - }); - - var lastMouseEvent; - var hoverMarker = new Range(-1,0,-1,Infinity); - var selectionMarker = new Range(-1,0,-1,Infinity); - selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine"); - popup.setSelectOnHover = function(val) { - if (!val) { - hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine"); - } else if (hoverMarker.id) { - popup.session.removeMarker(hoverMarker.id); - hoverMarker.id = null; - } - }; - popup.setSelectOnHover(false); - popup.on("mousemove", function(e) { - if (!lastMouseEvent) { - lastMouseEvent = e; - return; - } - if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) { - return; - } - lastMouseEvent = e; - lastMouseEvent.scrollTop = popup.renderer.scrollTop; - var row = lastMouseEvent.getDocumentPosition().row; - if (hoverMarker.start.row != row) { - if (!hoverMarker.id) - popup.setRow(row); - setHoverMarker(row); - } - }); - popup.renderer.on("beforeRender", function() { - if (lastMouseEvent && hoverMarker.start.row != -1) { - lastMouseEvent.$pos = null; - var row = lastMouseEvent.getDocumentPosition().row; - if (!hoverMarker.id) - popup.setRow(row); - setHoverMarker(row, true); - } - }); - popup.renderer.on("afterRender", function() { - var row = popup.getRow(); - var t = popup.renderer.$textLayer; - var selected = t.element.childNodes[row - t.config.firstRow]; - if (selected !== t.selectedNode && t.selectedNode) - dom.removeCssClass(t.selectedNode, "ace_selected"); - t.selectedNode = selected; - if (selected) - dom.addCssClass(selected, "ace_selected"); - }); - var hideHoverMarker = function() { setHoverMarker(-1); }; - var setHoverMarker = function(row, suppressRedraw) { - if (row !== hoverMarker.start.row) { - hoverMarker.start.row = hoverMarker.end.row = row; - if (!suppressRedraw) - popup.session._emit("changeBackMarker"); - popup._emit("changeHoverMarker"); - } - }; - popup.getHoveredRow = function() { - return hoverMarker.start.row; - }; - - event.addListener(popup.container, "mouseout", hideHoverMarker); - popup.on("hide", hideHoverMarker); - popup.on("changeSelection", hideHoverMarker); - - popup.session.doc.getLength = function() { - return popup.data.length; - }; - popup.session.doc.getLine = function(i) { - var data = popup.data[i]; - if (typeof data == "string") - return data; - return (data && data.value) || ""; - }; - - var bgTokenizer = popup.session.bgTokenizer; - bgTokenizer.$tokenizeRow = function(row) { - var data = popup.data[row]; - var tokens = []; - if (!data) - return tokens; - if (typeof data == "string") - data = {value: data}; - var caption = data.caption || data.value || data.name; - - function addToken(value, className) { - value && tokens.push({ - type: (data.className || "") + (className || ""), - value: value - }); - } - - var lower = caption.toLowerCase(); - var filterText = (popup.filterText || "").toLowerCase(); - var lastIndex = 0; - var lastI = 0; - for (var i = 0; i <= filterText.length; i++) { - if (i != lastI && (data.matchMask & (1 << i) || i == filterText.length)) { - var sub = filterText.slice(lastI, i); - lastI = i; - var index = lower.indexOf(sub, lastIndex); - if (index == -1) continue; - addToken(caption.slice(lastIndex, index), ""); - lastIndex = index + sub.length; - addToken(caption.slice(index, lastIndex), "completion-highlight"); - } - } - addToken(caption.slice(lastIndex, caption.length), ""); - - if (data.meta) - tokens.push({type: "completion-meta", value: data.meta}); - if (data.message) - tokens.push({type: "completion-message", value: data.message}); - - return tokens; - }; - bgTokenizer.$updateOnChange = noop; - bgTokenizer.start = noop; - - popup.session.$computeWidth = function() { - return this.screenWidth = 0; - }; - popup.isOpen = false; - popup.isTopdown = false; - popup.autoSelect = true; - popup.filterText = ""; - - popup.data = []; - popup.setData = function(list, filterText) { - popup.filterText = filterText || ""; - popup.setValue(lang.stringRepeat("\n", list.length), -1); - popup.data = list || []; - popup.setRow(0); - }; - popup.getData = function(row) { - return popup.data[row]; - }; - - popup.getRow = function() { - return selectionMarker.start.row; - }; - popup.setRow = function(line) { - line = Math.max(this.autoSelect ? 0 : -1, Math.min(this.data.length, line)); - if (selectionMarker.start.row != line) { - popup.selection.clearSelection(); - selectionMarker.start.row = selectionMarker.end.row = line || 0; - popup.session._emit("changeBackMarker"); - popup.moveCursorTo(line || 0, 0); - if (popup.isOpen) - popup._signal("select"); - } - }; - - popup.on("changeSelection", function() { - if (popup.isOpen) - popup.setRow(popup.selection.lead.row); - popup.renderer.scrollCursorIntoView(); - }); - - popup.hide = function() { - this.container.style.display = "none"; - this._signal("hide"); - popup.isOpen = false; - }; - popup.show = function(pos, lineHeight, topdownOnly) { - var el = this.container; - var screenHeight = window.innerHeight; - var screenWidth = window.innerWidth; - var renderer = this.renderer; - var maxH = renderer.$maxLines * lineHeight * 1.4; - var top = pos.top + this.$borderSize; - var allowTopdown = top > screenHeight / 2 && !topdownOnly; - if (allowTopdown && top + lineHeight + maxH > screenHeight) { - renderer.$maxPixelHeight = top - 2 * this.$borderSize; - el.style.top = ""; - el.style.bottom = screenHeight - top + "px"; - popup.isTopdown = false; - } else { - top += lineHeight; - renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight; - el.style.top = top + "px"; - el.style.bottom = ""; - popup.isTopdown = true; - } - - el.style.display = ""; - - var left = pos.left; - if (left + el.offsetWidth > screenWidth) - left = screenWidth - el.offsetWidth; - - el.style.left = left + "px"; - - this._signal("show"); - lastMouseEvent = null; - popup.isOpen = true; - }; - - popup.goTo = function(where) { - var row = this.getRow(); - var max = this.session.getLength() - 1; - - switch(where) { - case "up": row = row <= 0 ? max : row - 1; break; - case "down": row = row >= max ? -1 : row + 1; break; - case "start": row = 0; break; - case "end": row = max; break; - } - - this.setRow(row); - }; - - - popup.getTextLeftOffset = function() { - return this.$borderSize + this.renderer.$padding + this.$imageSize; - }; - - popup.$imageSize = 0; - popup.$borderSize = 1; - - return popup; -}; - -dom.importCssString("\ -.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\ - background-color: #CAD6FA;\ - z-index: 1;\ -}\ -.ace_dark.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\ - background-color: #3a674e;\ -}\ -.ace_editor.ace_autocomplete .ace_line-hover {\ - border: 1px solid #abbffe;\ - margin-top: -1px;\ - background: rgba(233,233,253,0.4);\ - position: absolute;\ - z-index: 2;\ -}\ -.ace_dark.ace_editor.ace_autocomplete .ace_line-hover {\ - border: 1px solid rgba(109, 150, 13, 0.8);\ - background: rgba(58, 103, 78, 0.62);\ -}\ -.ace_completion-meta {\ - opacity: 0.5;\ - margin: 0.9em;\ -}\ -.ace_completion-message {\ - color: blue;\ -}\ -.ace_editor.ace_autocomplete .ace_completion-highlight{\ - color: #2d69c7;\ -}\ -.ace_dark.ace_editor.ace_autocomplete .ace_completion-highlight{\ - color: #93ca12;\ -}\ -.ace_editor.ace_autocomplete {\ - width: 300px;\ - z-index: 200000;\ - border: 1px lightgray solid;\ - position: fixed;\ - box-shadow: 2px 3px 5px rgba(0,0,0,.2);\ - line-height: 1.4;\ - background: #fefefe;\ - color: #111;\ -}\ -.ace_dark.ace_editor.ace_autocomplete {\ - border: 1px #484747 solid;\ - box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.51);\ - line-height: 1.4;\ - background: #25282c;\ - color: #c1c1c1;\ -}", "autocompletion.css", false); - -exports.AcePopup = AcePopup; -exports.$singleLineEditor = $singleLineEditor; -}); - -define("ace/autocomplete/util",["require","exports","module"], function(require, exports, module) { -"use strict"; - -exports.parForEach = function(array, fn, callback) { - var completed = 0; - var arLength = array.length; - if (arLength === 0) - callback(); - for (var i = 0; i < arLength; i++) { - fn(array[i], function(result, err) { - completed++; - if (completed === arLength) - callback(result, err); - }); - } -}; - -var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\u2000\u2070-\uFFFF]/; - -exports.retrievePrecedingIdentifier = function(text, pos, regex) { - regex = regex || ID_REGEX; - var buf = []; - for (var i = pos-1; i >= 0; i--) { - if (regex.test(text[i])) - buf.push(text[i]); - else - break; - } - return buf.reverse().join(""); -}; - -exports.retrieveFollowingIdentifier = function(text, pos, regex) { - regex = regex || ID_REGEX; - var buf = []; - for (var i = pos; i < text.length; i++) { - if (regex.test(text[i])) - buf.push(text[i]); - else - break; - } - return buf; -}; - -exports.getCompletionPrefix = function (editor) { - var pos = editor.getCursorPosition(); - var line = editor.session.getLine(pos.row); - var prefix; - editor.completers.forEach(function(completer) { - if (completer.identifierRegexps) { - completer.identifierRegexps.forEach(function(identifierRegex) { - if (!prefix && identifierRegex) - prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex); - }.bind(this)); - } - }.bind(this)); - return prefix || this.retrievePrecedingIdentifier(line, pos.column); -}; - -}); - -define("ace/snippets",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/range_list","ace/keyboard/hash_handler","ace/tokenizer","ace/clipboard","ace/editor"], function(require, exports, module) { -"use strict"; -var dom = require("./lib/dom"); -var oop = require("./lib/oop"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var lang = require("./lib/lang"); -var Range = require("./range").Range; -var RangeList = require("./range_list").RangeList; -var HashHandler = require("./keyboard/hash_handler").HashHandler; -var Tokenizer = require("./tokenizer").Tokenizer; -var clipboard = require("./clipboard"); - -var VARIABLES = { - CURRENT_WORD: function(editor) { - return editor.session.getTextRange(editor.session.getWordRange()); - }, - SELECTION: function(editor, name, indentation) { - var text = editor.session.getTextRange(); - if (indentation) - return text.replace(/\n\r?([ \t]*\S)/g, "\n" + indentation + "$1"); - return text; - }, - CURRENT_LINE: function(editor) { - return editor.session.getLine(editor.getCursorPosition().row); - }, - PREV_LINE: function(editor) { - return editor.session.getLine(editor.getCursorPosition().row - 1); - }, - LINE_INDEX: function(editor) { - return editor.getCursorPosition().row; - }, - LINE_NUMBER: function(editor) { - return editor.getCursorPosition().row + 1; - }, - SOFT_TABS: function(editor) { - return editor.session.getUseSoftTabs() ? "YES" : "NO"; - }, - TAB_SIZE: function(editor) { - return editor.session.getTabSize(); - }, - CLIPBOARD: function(editor) { - return clipboard.getText && clipboard.getText(); - }, - FILENAME: function(editor) { - return /[^/\\]*$/.exec(this.FILEPATH(editor))[0]; - }, - FILENAME_BASE: function(editor) { - return /[^/\\]*$/.exec(this.FILEPATH(editor))[0].replace(/\.[^.]*$/, ""); - }, - DIRECTORY: function(editor) { - return this.FILEPATH(editor).replace(/[^/\\]*$/, ""); - }, - FILEPATH: function(editor) { return "/not implemented.txt"; }, - WORKSPACE_NAME: function() { return "Unknown"; }, - FULLNAME: function() { return "Unknown"; }, - BLOCK_COMMENT_START: function(editor) { - var mode = editor.session.$mode || {}; - return mode.blockComment && mode.blockComment.start || ""; - }, - BLOCK_COMMENT_END: function(editor) { - var mode = editor.session.$mode || {}; - return mode.blockComment && mode.blockComment.end || ""; - }, - LINE_COMMENT: function(editor) { - var mode = editor.session.$mode || {}; - return mode.lineCommentStart || ""; - }, - CURRENT_YEAR: date.bind(null, {year: "numeric"}), - CURRENT_YEAR_SHORT: date.bind(null, {year: "2-digit"}), - CURRENT_MONTH: date.bind(null, {month: "numeric"}), - CURRENT_MONTH_NAME: date.bind(null, {month: "long"}), - CURRENT_MONTH_NAME_SHORT: date.bind(null, {month: "short"}), - CURRENT_DATE: date.bind(null, {day: "2-digit"}), - CURRENT_DAY_NAME: date.bind(null, {weekday: "long"}), - CURRENT_DAY_NAME_SHORT: date.bind(null, {weekday: "short"}), - CURRENT_HOUR: date.bind(null, {hour: "2-digit", hour12: false}), - CURRENT_MINUTE: date.bind(null, {minute: "2-digit"}), - CURRENT_SECOND: date.bind(null, {second: "2-digit"}) -}; - -VARIABLES.SELECTED_TEXT = VARIABLES.SELECTION; - -function date(dateFormat) { - var str = new Date().toLocaleString("en-us", dateFormat); - return str.length == 1 ? "0" + str : str; -} - -var SnippetManager = function() { - this.snippetMap = {}; - this.snippetNameMap = {}; -}; - -(function() { - oop.implement(this, EventEmitter); - - this.getTokenizer = function() { - return SnippetManager.$tokenizer || this.createTokenizer(); - }; - - this.createTokenizer = function() { - function TabstopToken(str) { - str = str.substr(1); - if (/^\d+$/.test(str)) - return [{tabstopId: parseInt(str, 10)}]; - return [{text: str}]; - } - function escape(ch) { - return "(?:[^\\\\" + ch + "]|\\\\.)"; - } - var formatMatcher = { - regex: "/(" + escape("/") + "+)/", - onMatch: function(val, state, stack) { - var ts = stack[0]; - ts.fmtString = true; - ts.guard = val.slice(1, -1); - ts.flag = ""; - return ""; - }, - next: "formatString" - }; - - SnippetManager.$tokenizer = new Tokenizer({ - start: [ - {regex: /\\./, onMatch: function(val, state, stack) { - var ch = val[1]; - if (ch == "}" && stack.length) { - val = ch; - } else if ("`$\\".indexOf(ch) != -1) { - val = ch; - } - return [val]; - }}, - {regex: /}/, onMatch: function(val, state, stack) { - return [stack.length ? stack.shift() : val]; - }}, - {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken}, - {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) { - var t = TabstopToken(str.substr(1)); - stack.unshift(t[0]); - return t; - }, next: "snippetVar"}, - {regex: /\n/, token: "newline", merge: false} - ], - snippetVar: [ - {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) { - var choices = val.slice(1, -1).replace(/\\[,|\\]|,/g, function(operator) { - return operator.length == 2 ? operator[1] : "\x00"; - }).split("\x00").map(function(value){ - return {value: value}; - }); - stack[0].choices = choices; - return [choices[0]]; - }, next: "start"}, - formatMatcher, - {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"} - ], - formatString: [ - {regex: /:/, onMatch: function(val, state, stack) { - if (stack.length && stack[0].expectElse) { - stack[0].expectElse = false; - stack[0].ifEnd = {elseEnd: stack[0]}; - return [stack[0].ifEnd]; - } - return ":"; - }}, - {regex: /\\./, onMatch: function(val, state, stack) { - var ch = val[1]; - if (ch == "}" && stack.length) - val = ch; - else if ("`$\\".indexOf(ch) != -1) - val = ch; - else if (ch == "n") - val = "\n"; - else if (ch == "t") - val = "\t"; - else if ("ulULE".indexOf(ch) != -1) - val = {changeCase: ch, local: ch > "a"}; - return [val]; - }}, - {regex: "/\\w*}", onMatch: function(val, state, stack) { - var next = stack.shift(); - if (next) - next.flag = val.slice(1, -1); - this.next = next && next.tabstopId ? "start" : ""; - return [next || val]; - }, next: "start"}, - {regex: /\$(?:\d+|\w+)/, onMatch: function(val, state, stack) { - return [{text: val.slice(1)}]; - }}, - {regex: /\${\w+/, onMatch: function(val, state, stack) { - var token = {text: val.slice(2)}; - stack.unshift(token); - return [token]; - }, next: "formatStringVar"}, - {regex: /\n/, token: "newline", merge: false}, - {regex: /}/, onMatch: function(val, state, stack) { - var next = stack.shift(); - this.next = next && next.tabstopId ? "start" : ""; - return [next || val]; - }, next: "start"} - ], - formatStringVar: [ - {regex: /:\/\w+}/, onMatch: function(val, state, stack) { - var ts = stack[0]; - ts.formatFunction = val.slice(2, -1); - return [stack.shift()]; - }, next: "formatString"}, - formatMatcher, - {regex: /:[\?\-+]?/, onMatch: function(val, state, stack) { - if (val[1] == "+") - stack[0].ifEnd = stack[0]; - if (val[1] == "?") - stack[0].expectElse = true; - }, next: "formatString"}, - {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "formatString"} - ] - }); - return SnippetManager.$tokenizer; - }; - - this.tokenizeTmSnippet = function(str, startState) { - return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) { - return x.value || x; - }); - }; - - this.getVariableValue = function(editor, name, indentation) { - if (/^\d+$/.test(name)) - return (this.variables.__ || {})[name] || ""; - if (/^[A-Z]\d+$/.test(name)) - return (this.variables[name[0] + "__"] || {})[name.substr(1)] || ""; - - name = name.replace(/^TM_/, ""); - if (!this.variables.hasOwnProperty(name)) - return ""; - var value = this.variables[name]; - if (typeof value == "function") - value = this.variables[name](editor, name, indentation); - return value == null ? "" : value; - }; - - this.variables = VARIABLES; - this.tmStrFormat = function(str, ch, editor) { - if (!ch.fmt) return str; - var flag = ch.flag || ""; - var re = ch.guard; - re = new RegExp(re, flag.replace(/[^gim]/g, "")); - var fmtTokens = typeof ch.fmt == "string" ? this.tokenizeTmSnippet(ch.fmt, "formatString") : ch.fmt; - var _self = this; - var formatted = str.replace(re, function() { - var oldArgs = _self.variables.__; - _self.variables.__ = [].slice.call(arguments); - var fmtParts = _self.resolveVariables(fmtTokens, editor); - var gChangeCase = "E"; - for (var i = 0; i < fmtParts.length; i++) { - var ch = fmtParts[i]; - if (typeof ch == "object") { - fmtParts[i] = ""; - if (ch.changeCase && ch.local) { - var next = fmtParts[i + 1]; - if (next && typeof next == "string") { - if (ch.changeCase == "u") - fmtParts[i] = next[0].toUpperCase(); - else - fmtParts[i] = next[0].toLowerCase(); - fmtParts[i + 1] = next.substr(1); - } - } else if (ch.changeCase) { - gChangeCase = ch.changeCase; - } - } else if (gChangeCase == "U") { - fmtParts[i] = ch.toUpperCase(); - } else if (gChangeCase == "L") { - fmtParts[i] = ch.toLowerCase(); - } - } - _self.variables.__ = oldArgs; - return fmtParts.join(""); - }); - return formatted; - }; - - this.tmFormatFunction = function(str, ch, editor) { - if (ch.formatFunction == "upcase") - return str.toUpperCase(); - if (ch.formatFunction == "downcase") - return str.toLowerCase(); - return str; - }; - - this.resolveVariables = function(snippet, editor) { - var result = []; - var indentation = ""; - var afterNewLine = true; - for (var i = 0; i < snippet.length; i++) { - var ch = snippet[i]; - if (typeof ch == "string") { - result.push(ch); - if (ch == "\n") { - afterNewLine = true; - indentation = ""; - } - else if (afterNewLine) { - indentation = /^\t*/.exec(ch)[0]; - afterNewLine = /\S/.test(ch); - } - continue; - } - if (!ch) continue; - afterNewLine = false; - - if (ch.fmtString) { - var j = snippet.indexOf(ch, i + 1); - if (j == -1) j = snippet.length; - ch.fmt = snippet.slice(i + 1, j); - i = j; - } - - if (ch.text) { - var value = this.getVariableValue(editor, ch.text, indentation) + ""; - if (ch.fmtString) - value = this.tmStrFormat(value, ch, editor); - if (ch.formatFunction) - value = this.tmFormatFunction(value, ch, editor); - - if (value && !ch.ifEnd) { - result.push(value); - gotoNext(ch); - } else if (!value && ch.ifEnd) { - gotoNext(ch.ifEnd); - } - } else if (ch.elseEnd) { - gotoNext(ch.elseEnd); - } else if (ch.tabstopId != null) { - result.push(ch); - } else if (ch.changeCase != null) { - result.push(ch); - } - } - function gotoNext(ch) { - var i1 = snippet.indexOf(ch, i + 1); - if (i1 != -1) - i = i1; - } - return result; - }; - - this.insertSnippetForSelection = function(editor, snippetText) { - var cursor = editor.getCursorPosition(); - var line = editor.session.getLine(cursor.row); - var tabString = editor.session.getTabString(); - var indentString = line.match(/^\s*/)[0]; - - if (cursor.column < indentString.length) - indentString = indentString.slice(0, cursor.column); - - snippetText = snippetText.replace(/\r/g, ""); - var tokens = this.tokenizeTmSnippet(snippetText); - tokens = this.resolveVariables(tokens, editor); - tokens = tokens.map(function(x) { - if (x == "\n") - return x + indentString; - if (typeof x == "string") - return x.replace(/\t/g, tabString); - return x; - }); - var tabstops = []; - tokens.forEach(function(p, i) { - if (typeof p != "object") - return; - var id = p.tabstopId; - var ts = tabstops[id]; - if (!ts) { - ts = tabstops[id] = []; - ts.index = id; - ts.value = ""; - ts.parents = {}; - } - if (ts.indexOf(p) !== -1) - return; - if (p.choices && !ts.choices) - ts.choices = p.choices; - ts.push(p); - var i1 = tokens.indexOf(p, i + 1); - if (i1 === -1) - return; - - var value = tokens.slice(i + 1, i1); - var isNested = value.some(function(t) {return typeof t === "object";}); - if (isNested && !ts.value) { - ts.value = value; - } else if (value.length && (!ts.value || typeof ts.value !== "string")) { - ts.value = value.join(""); - } - }); - tabstops.forEach(function(ts) {ts.length = 0;}); - var expanding = {}; - function copyValue(val) { - var copy = []; - for (var i = 0; i < val.length; i++) { - var p = val[i]; - if (typeof p == "object") { - if (expanding[p.tabstopId]) - continue; - var j = val.lastIndexOf(p, i - 1); - p = copy[j] || {tabstopId: p.tabstopId}; - } - copy[i] = p; - } - return copy; - } - for (var i = 0; i < tokens.length; i++) { - var p = tokens[i]; - if (typeof p != "object") - continue; - var id = p.tabstopId; - var ts = tabstops[id]; - var i1 = tokens.indexOf(p, i + 1); - if (expanding[id]) { - if (expanding[id] === p) { - delete expanding[id]; - Object.keys(expanding).forEach(function(parentId) { - ts.parents[parentId] = true; - }); - } - continue; - } - expanding[id] = p; - var value = ts.value; - if (typeof value !== "string") - value = copyValue(value); - else if (p.fmt) - value = this.tmStrFormat(value, p, editor); - tokens.splice.apply(tokens, [i + 1, Math.max(0, i1 - i)].concat(value, p)); - - if (ts.indexOf(p) === -1) - ts.push(p); - } - var row = 0, column = 0; - var text = ""; - tokens.forEach(function(t) { - if (typeof t === "string") { - var lines = t.split("\n"); - if (lines.length > 1){ - column = lines[lines.length - 1].length; - row += lines.length - 1; - } else - column += t.length; - text += t; - } else if (t) { - if (!t.start) - t.start = {row: row, column: column}; - else - t.end = {row: row, column: column}; - } - }); - var range = editor.getSelectionRange(); - var end = editor.session.replace(range, text); - - var tabstopManager = new TabstopManager(editor); - var selectionId = editor.inVirtualSelectionMode && editor.selection.index; - tabstopManager.addTabstops(tabstops, range.start, end, selectionId); - }; - - this.insertSnippet = function(editor, snippetText) { - var self = this; - if (editor.inVirtualSelectionMode) - return self.insertSnippetForSelection(editor, snippetText); - - editor.forEachSelection(function() { - self.insertSnippetForSelection(editor, snippetText); - }, null, {keepOrder: true}); - - if (editor.tabstopManager) - editor.tabstopManager.tabNext(); - }; - - this.$getScope = function(editor) { - var scope = editor.session.$mode.$id || ""; - scope = scope.split("/").pop(); - if (scope === "html" || scope === "php") { - if (scope === "php" && !editor.session.$mode.inlinePhp) - scope = "html"; - var c = editor.getCursorPosition(); - var state = editor.session.getState(c.row); - if (typeof state === "object") { - state = state[0]; - } - if (state.substring) { - if (state.substring(0, 3) == "js-") - scope = "javascript"; - else if (state.substring(0, 4) == "css-") - scope = "css"; - else if (state.substring(0, 4) == "php-") - scope = "php"; - } - } - - return scope; - }; - - this.getActiveScopes = function(editor) { - var scope = this.$getScope(editor); - var scopes = [scope]; - var snippetMap = this.snippetMap; - if (snippetMap[scope] && snippetMap[scope].includeScopes) { - scopes.push.apply(scopes, snippetMap[scope].includeScopes); - } - scopes.push("_"); - return scopes; - }; - - this.expandWithTab = function(editor, options) { - var self = this; - var result = editor.forEachSelection(function() { - return self.expandSnippetForSelection(editor, options); - }, null, {keepOrder: true}); - if (result && editor.tabstopManager) - editor.tabstopManager.tabNext(); - return result; - }; - - this.expandSnippetForSelection = function(editor, options) { - var cursor = editor.getCursorPosition(); - var line = editor.session.getLine(cursor.row); - var before = line.substring(0, cursor.column); - var after = line.substr(cursor.column); - - var snippetMap = this.snippetMap; - var snippet; - this.getActiveScopes(editor).some(function(scope) { - var snippets = snippetMap[scope]; - if (snippets) - snippet = this.findMatchingSnippet(snippets, before, after); - return !!snippet; - }, this); - if (!snippet) - return false; - if (options && options.dryRun) - return true; - editor.session.doc.removeInLine(cursor.row, - cursor.column - snippet.replaceBefore.length, - cursor.column + snippet.replaceAfter.length - ); - - this.variables.M__ = snippet.matchBefore; - this.variables.T__ = snippet.matchAfter; - this.insertSnippetForSelection(editor, snippet.content); - - this.variables.M__ = this.variables.T__ = null; - return true; - }; - - this.findMatchingSnippet = function(snippetList, before, after) { - for (var i = snippetList.length; i--;) { - var s = snippetList[i]; - if (s.startRe && !s.startRe.test(before)) - continue; - if (s.endRe && !s.endRe.test(after)) - continue; - if (!s.startRe && !s.endRe) - continue; - - s.matchBefore = s.startRe ? s.startRe.exec(before) : [""]; - s.matchAfter = s.endRe ? s.endRe.exec(after) : [""]; - s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : ""; - s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : ""; - return s; - } - }; - - this.snippetMap = {}; - this.snippetNameMap = {}; - this.register = function(snippets, scope) { - var snippetMap = this.snippetMap; - var snippetNameMap = this.snippetNameMap; - var self = this; - - if (!snippets) - snippets = []; - - function wrapRegexp(src) { - if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src)) - src = "(?:" + src + ")"; - - return src || ""; - } - function guardedRegexp(re, guard, opening) { - re = wrapRegexp(re); - guard = wrapRegexp(guard); - if (opening) { - re = guard + re; - if (re && re[re.length - 1] != "$") - re = re + "$"; - } else { - re = re + guard; - if (re && re[0] != "^") - re = "^" + re; - } - return new RegExp(re); - } - - function addSnippet(s) { - if (!s.scope) - s.scope = scope || "_"; - scope = s.scope; - if (!snippetMap[scope]) { - snippetMap[scope] = []; - snippetNameMap[scope] = {}; - } - - var map = snippetNameMap[scope]; - if (s.name) { - var old = map[s.name]; - if (old) - self.unregister(old); - map[s.name] = s; - } - snippetMap[scope].push(s); - - if (s.prefix) - s.tabTrigger = s.prefix; - - if (!s.content && s.body) - s.content = Array.isArray(s.body) ? s.body.join("\n") : s.body; - - if (s.tabTrigger && !s.trigger) { - if (!s.guard && /^\w/.test(s.tabTrigger)) - s.guard = "\\b"; - s.trigger = lang.escapeRegExp(s.tabTrigger); - } - - if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard) - return; - - s.startRe = guardedRegexp(s.trigger, s.guard, true); - s.triggerRe = new RegExp(s.trigger); - - s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true); - s.endTriggerRe = new RegExp(s.endTrigger); - } - - if (Array.isArray(snippets)) { - snippets.forEach(addSnippet); - } else { - Object.keys(snippets).forEach(function(key) { - addSnippet(snippets[key]); - }); - } - - this._signal("registerSnippets", {scope: scope}); - }; - this.unregister = function(snippets, scope) { - var snippetMap = this.snippetMap; - var snippetNameMap = this.snippetNameMap; - - function removeSnippet(s) { - var nameMap = snippetNameMap[s.scope||scope]; - if (nameMap && nameMap[s.name]) { - delete nameMap[s.name]; - var map = snippetMap[s.scope||scope]; - var i = map && map.indexOf(s); - if (i >= 0) - map.splice(i, 1); - } - } - if (snippets.content) - removeSnippet(snippets); - else if (Array.isArray(snippets)) - snippets.forEach(removeSnippet); - }; - this.parseSnippetFile = function(str) { - str = str.replace(/\r/g, ""); - var list = [], snippet = {}; - var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm; - var m; - while (m = re.exec(str)) { - if (m[1]) { - try { - snippet = JSON.parse(m[1]); - list.push(snippet); - } catch (e) {} - } if (m[4]) { - snippet.content = m[4].replace(/^\t/gm, ""); - list.push(snippet); - snippet = {}; - } else { - var key = m[2], val = m[3]; - if (key == "regex") { - var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g; - snippet.guard = guardRe.exec(val)[1]; - snippet.trigger = guardRe.exec(val)[1]; - snippet.endTrigger = guardRe.exec(val)[1]; - snippet.endGuard = guardRe.exec(val)[1]; - } else if (key == "snippet") { - snippet.tabTrigger = val.match(/^\S*/)[0]; - if (!snippet.name) - snippet.name = val; - } else if (key) { - snippet[key] = val; - } - } - } - return list; - }; - this.getSnippetByName = function(name, editor) { - var snippetMap = this.snippetNameMap; - var snippet; - this.getActiveScopes(editor).some(function(scope) { - var snippets = snippetMap[scope]; - if (snippets) - snippet = snippets[name]; - return !!snippet; - }, this); - return snippet; - }; - -}).call(SnippetManager.prototype); - - -var TabstopManager = function(editor) { - if (editor.tabstopManager) - return editor.tabstopManager; - editor.tabstopManager = this; - this.$onChange = this.onChange.bind(this); - this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule; - this.$onChangeSession = this.onChangeSession.bind(this); - this.$onAfterExec = this.onAfterExec.bind(this); - this.attach(editor); -}; -(function() { - this.attach = function(editor) { - this.index = 0; - this.ranges = []; - this.tabstops = []; - this.$openTabstops = null; - this.selectedTabstop = null; - - this.editor = editor; - this.editor.on("change", this.$onChange); - this.editor.on("changeSelection", this.$onChangeSelection); - this.editor.on("changeSession", this.$onChangeSession); - this.editor.commands.on("afterExec", this.$onAfterExec); - this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - }; - this.detach = function() { - this.tabstops.forEach(this.removeTabstopMarkers, this); - this.ranges = null; - this.tabstops = null; - this.selectedTabstop = null; - this.editor.removeListener("change", this.$onChange); - this.editor.removeListener("changeSelection", this.$onChangeSelection); - this.editor.removeListener("changeSession", this.$onChangeSession); - this.editor.commands.removeListener("afterExec", this.$onAfterExec); - this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); - this.editor.tabstopManager = null; - this.editor = null; - }; - - this.onChange = function(delta) { - var isRemove = delta.action[0] == "r"; - var selectedTabstop = this.selectedTabstop || {}; - var parents = selectedTabstop.parents || {}; - var tabstops = (this.tabstops || []).slice(); - for (var i = 0; i < tabstops.length; i++) { - var ts = tabstops[i]; - var active = ts == selectedTabstop || parents[ts.index]; - ts.rangeList.$bias = active ? 0 : 1; - - if (delta.action == "remove" && ts !== selectedTabstop) { - var parentActive = ts.parents && ts.parents[selectedTabstop.index]; - var startIndex = ts.rangeList.pointIndex(delta.start, parentActive); - startIndex = startIndex < 0 ? -startIndex - 1 : startIndex + 1; - var endIndex = ts.rangeList.pointIndex(delta.end, parentActive); - endIndex = endIndex < 0 ? -endIndex - 1 : endIndex - 1; - var toRemove = ts.rangeList.ranges.slice(startIndex, endIndex); - for (var j = 0; j < toRemove.length; j++) - this.removeRange(toRemove[j]); - } - ts.rangeList.$onChange(delta); - } - var session = this.editor.session; - if (!this.$inChange && isRemove && session.getLength() == 1 && !session.getValue()) - this.detach(); - }; - this.updateLinkedFields = function() { - var ts = this.selectedTabstop; - if (!ts || !ts.hasLinkedRanges || !ts.firstNonLinked) - return; - this.$inChange = true; - var session = this.editor.session; - var text = session.getTextRange(ts.firstNonLinked); - for (var i = 0; i < ts.length; i++) { - var range = ts[i]; - if (!range.linked) - continue; - var original = range.original; - var fmt = exports.snippetManager.tmStrFormat(text, original, this.editor); - session.replace(range, fmt); - } - this.$inChange = false; - }; - this.onAfterExec = function(e) { - if (e.command && !e.command.readOnly) - this.updateLinkedFields(); - }; - this.onChangeSelection = function() { - if (!this.editor) - return; - var lead = this.editor.selection.lead; - var anchor = this.editor.selection.anchor; - var isEmpty = this.editor.selection.isEmpty(); - for (var i = 0; i < this.ranges.length; i++) { - if (this.ranges[i].linked) - continue; - var containsLead = this.ranges[i].contains(lead.row, lead.column); - var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column); - if (containsLead && containsAnchor) - return; - } - this.detach(); - }; - this.onChangeSession = function() { - this.detach(); - }; - this.tabNext = function(dir) { - var max = this.tabstops.length; - var index = this.index + (dir || 1); - index = Math.min(Math.max(index, 1), max); - if (index == max) - index = 0; - this.selectTabstop(index); - if (index === 0) - this.detach(); - }; - this.selectTabstop = function(index) { - this.$openTabstops = null; - var ts = this.tabstops[this.index]; - if (ts) - this.addTabstopMarkers(ts); - this.index = index; - ts = this.tabstops[this.index]; - if (!ts || !ts.length) - return; - - this.selectedTabstop = ts; - var range = ts.firstNonLinked || ts; - if (ts.choices) range.cursor = range.start; - if (!this.editor.inVirtualSelectionMode) { - var sel = this.editor.multiSelect; - sel.toSingleRange(range); - for (var i = 0; i < ts.length; i++) { - if (ts.hasLinkedRanges && ts[i].linked) - continue; - sel.addRange(ts[i].clone(), true); - } - } else { - this.editor.selection.fromOrientedRange(range); - } - - this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - if (this.selectedTabstop && this.selectedTabstop.choices) - this.editor.execCommand("startAutocomplete", {matches: this.selectedTabstop.choices}); - }; - this.addTabstops = function(tabstops, start, end) { - var useLink = this.useLink || !this.editor.getOption("enableMultiselect"); - - if (!this.$openTabstops) - this.$openTabstops = []; - if (!tabstops[0]) { - var p = Range.fromPoints(end, end); - moveRelative(p.start, start); - moveRelative(p.end, start); - tabstops[0] = [p]; - tabstops[0].index = 0; - } - - var i = this.index; - var arg = [i + 1, 0]; - var ranges = this.ranges; - tabstops.forEach(function(ts, index) { - var dest = this.$openTabstops[index] || ts; - - for (var i = 0; i < ts.length; i++) { - var p = ts[i]; - var range = Range.fromPoints(p.start, p.end || p.start); - movePoint(range.start, start); - movePoint(range.end, start); - range.original = p; - range.tabstop = dest; - ranges.push(range); - if (dest != ts) - dest.unshift(range); - else - dest[i] = range; - if (p.fmtString || (dest.firstNonLinked && useLink)) { - range.linked = true; - dest.hasLinkedRanges = true; - } else if (!dest.firstNonLinked) - dest.firstNonLinked = range; - } - if (!dest.firstNonLinked) - dest.hasLinkedRanges = false; - if (dest === ts) { - arg.push(dest); - this.$openTabstops[index] = dest; - } - this.addTabstopMarkers(dest); - dest.rangeList = dest.rangeList || new RangeList(); - dest.rangeList.$bias = 0; - dest.rangeList.addList(dest); - }, this); - - if (arg.length > 2) { - if (this.tabstops.length) - arg.push(arg.splice(2, 1)[0]); - this.tabstops.splice.apply(this.tabstops, arg); - } - }; - - this.addTabstopMarkers = function(ts) { - var session = this.editor.session; - ts.forEach(function(range) { - if (!range.markerId) - range.markerId = session.addMarker(range, "ace_snippet-marker", "text"); - }); - }; - this.removeTabstopMarkers = function(ts) { - var session = this.editor.session; - ts.forEach(function(range) { - session.removeMarker(range.markerId); - range.markerId = null; - }); - }; - this.removeRange = function(range) { - var i = range.tabstop.indexOf(range); - if (i != -1) range.tabstop.splice(i, 1); - i = this.ranges.indexOf(range); - if (i != -1) this.ranges.splice(i, 1); - i = range.tabstop.rangeList.ranges.indexOf(range); - if (i != -1) range.tabstop.splice(i, 1); - this.editor.session.removeMarker(range.markerId); - if (!range.tabstop.length) { - i = this.tabstops.indexOf(range.tabstop); - if (i != -1) - this.tabstops.splice(i, 1); - if (!this.tabstops.length) - this.detach(); - } - }; - - this.keyboardHandler = new HashHandler(); - this.keyboardHandler.bindKeys({ - "Tab": function(editor) { - if (exports.snippetManager && exports.snippetManager.expandWithTab(editor)) - return; - editor.tabstopManager.tabNext(1); - editor.renderer.scrollCursorIntoView(); - }, - "Shift-Tab": function(editor) { - editor.tabstopManager.tabNext(-1); - editor.renderer.scrollCursorIntoView(); - }, - "Esc": function(editor) { - editor.tabstopManager.detach(); - } - }); -}).call(TabstopManager.prototype); - - - -var movePoint = function(point, diff) { - if (point.row == 0) - point.column += diff.column; - point.row += diff.row; -}; - -var moveRelative = function(point, start) { - if (point.row == start.row) - point.column -= start.column; - point.row -= start.row; -}; - - -dom.importCssString("\ -.ace_snippet-marker {\ - -moz-box-sizing: border-box;\ - box-sizing: border-box;\ - background: rgba(194, 193, 208, 0.09);\ - border: 1px dotted rgba(211, 208, 235, 0.62);\ - position: absolute;\ -}", "snippets.css", false); - -exports.snippetManager = new SnippetManager(); - - -var Editor = require("./editor").Editor; -(function() { - this.insertSnippet = function(content, options) { - return exports.snippetManager.insertSnippet(this, content, options); - }; - this.expandSnippet = function(options) { - return exports.snippetManager.expandWithTab(this, options); - }; -}).call(Editor.prototype); - -}); - -define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/lang","ace/lib/dom","ace/snippets","ace/config"], function(require, exports, module) { -"use strict"; - -var HashHandler = require("./keyboard/hash_handler").HashHandler; -var AcePopup = require("./autocomplete/popup").AcePopup; -var util = require("./autocomplete/util"); -var lang = require("./lib/lang"); -var dom = require("./lib/dom"); -var snippetManager = require("./snippets").snippetManager; -var config = require("./config"); - -var Autocomplete = function() { - this.autoInsert = false; - this.autoSelect = true; - this.exactMatch = false; - this.gatherCompletionsId = 0; - this.keyboardHandler = new HashHandler(); - this.keyboardHandler.bindKeys(this.commands); - - this.blurListener = this.blurListener.bind(this); - this.changeListener = this.changeListener.bind(this); - this.mousedownListener = this.mousedownListener.bind(this); - this.mousewheelListener = this.mousewheelListener.bind(this); - - this.changeTimer = lang.delayedCall(function() { - this.updateCompletions(true); - }.bind(this)); - - this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50); -}; - -(function() { - - this.$init = function() { - this.popup = new AcePopup(document.body || document.documentElement); - this.popup.on("click", function(e) { - this.insertMatch(); - e.stop(); - }.bind(this)); - this.popup.focus = this.editor.focus.bind(this.editor); - this.popup.on("show", this.tooltipTimer.bind(null, null)); - this.popup.on("select", this.tooltipTimer.bind(null, null)); - this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null)); - return this.popup; - }; - - this.getPopup = function() { - return this.popup || this.$init(); - }; - - this.openPopup = function(editor, prefix, keepPopupPosition) { - if (!this.popup) - this.$init(); - - this.popup.autoSelect = this.autoSelect; - - this.popup.setData(this.completions.filtered, this.completions.filterText); - - editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - - var renderer = editor.renderer; - this.popup.setRow(this.autoSelect ? 0 : -1); - if (!keepPopupPosition) { - this.popup.setTheme(editor.getTheme()); - this.popup.setFontSize(editor.getFontSize()); - - var lineHeight = renderer.layerConfig.lineHeight; - - var pos = renderer.$cursorLayer.getPixelPosition(this.base, true); - pos.left -= this.popup.getTextLeftOffset(); - - var rect = editor.container.getBoundingClientRect(); - pos.top += rect.top - renderer.layerConfig.offset; - pos.left += rect.left - editor.renderer.scrollLeft; - pos.left += renderer.gutterWidth; - - this.popup.show(pos, lineHeight); - } else if (keepPopupPosition && !prefix) { - this.detach(); - } - this.changeTimer.cancel(); - }; - - this.detach = function() { - this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); - this.editor.off("changeSelection", this.changeListener); - this.editor.off("blur", this.blurListener); - this.editor.off("mousedown", this.mousedownListener); - this.editor.off("mousewheel", this.mousewheelListener); - this.changeTimer.cancel(); - this.hideDocTooltip(); - - this.gatherCompletionsId += 1; - if (this.popup && this.popup.isOpen) - this.popup.hide(); - - if (this.base) - this.base.detach(); - this.activated = false; - this.completions = this.base = null; - }; - - this.changeListener = function(e) { - var cursor = this.editor.selection.lead; - if (cursor.row != this.base.row || cursor.column < this.base.column) { - this.detach(); - } - if (this.activated) - this.changeTimer.schedule(); - else - this.detach(); - }; - - this.blurListener = function(e) { - var el = document.activeElement; - var text = this.editor.textInput.getElement(); - var fromTooltip = e.relatedTarget && this.tooltipNode && this.tooltipNode.contains(e.relatedTarget); - var container = this.popup && this.popup.container; - if (el != text && el.parentNode != container && !fromTooltip - && el != this.tooltipNode && e.relatedTarget != text - ) { - this.detach(); - } - }; - - this.mousedownListener = function(e) { - this.detach(); - }; - - this.mousewheelListener = function(e) { - this.detach(); - }; - - this.goTo = function(where) { - this.popup.goTo(where); - }; - - this.insertMatch = function(data, options) { - if (!data) - data = this.popup.getData(this.popup.getRow()); - if (!data) - return false; - - var completions = this.completions; - this.editor.startOperation({command: {name: "insertMatch"}}); - if (data.completer && data.completer.insertMatch) { - data.completer.insertMatch(this.editor, data); - } else { - if (completions.filterText) { - var ranges = this.editor.selection.getAllRanges(); - for (var i = 0, range; range = ranges[i]; i++) { - range.start.column -= completions.filterText.length; - this.editor.session.remove(range); - } - } - if (data.snippet) - snippetManager.insertSnippet(this.editor, data.snippet); - else - this.editor.execCommand("insertstring", data.value || data); - } - if (this.completions == completions) - this.detach(); - this.editor.endOperation(); - }; - - - this.commands = { - "Up": function(editor) { editor.completer.goTo("up"); }, - "Down": function(editor) { editor.completer.goTo("down"); }, - "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); }, - "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); }, - - "Esc": function(editor) { editor.completer.detach(); }, - "Return": function(editor) { return editor.completer.insertMatch(); }, - "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); }, - "Tab": function(editor) { - var result = editor.completer.insertMatch(); - if (!result && !editor.tabstopManager) - editor.completer.goTo("down"); - else - return result; - }, - - "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); }, - "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); } - }; - - this.gatherCompletions = function(editor, callback) { - var session = editor.getSession(); - var pos = editor.getCursorPosition(); - - var prefix = util.getCompletionPrefix(editor); - - this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length); - this.base.$insertRight = true; - - var matches = []; - var total = editor.completers.length; - editor.completers.forEach(function(completer, i) { - completer.getCompletions(editor, session, pos, prefix, function(err, results) { - if (!err && results) - matches = matches.concat(results); - callback(null, { - prefix: util.getCompletionPrefix(editor), - matches: matches, - finished: (--total === 0) - }); - }); - }); - return true; - }; - - this.showPopup = function(editor, options) { - if (this.editor) - this.detach(); - - this.activated = true; - - this.editor = editor; - if (editor.completer != this) { - if (editor.completer) - editor.completer.detach(); - editor.completer = this; - } - - editor.on("changeSelection", this.changeListener); - editor.on("blur", this.blurListener); - editor.on("mousedown", this.mousedownListener); - editor.on("mousewheel", this.mousewheelListener); - - this.updateCompletions(false, options); - }; - - this.updateCompletions = function(keepPopupPosition, options) { - if (keepPopupPosition && this.base && this.completions) { - var pos = this.editor.getCursorPosition(); - var prefix = this.editor.session.getTextRange({start: this.base, end: pos}); - if (prefix == this.completions.filterText) - return; - this.completions.setFilter(prefix); - if (!this.completions.filtered.length) - return this.detach(); - if (this.completions.filtered.length == 1 - && this.completions.filtered[0].value == prefix - && !this.completions.filtered[0].snippet) - return this.detach(); - this.openPopup(this.editor, prefix, keepPopupPosition); - return; - } - - if (options && options.matches) { - var pos = this.editor.getSelectionRange().start; - this.base = this.editor.session.doc.createAnchor(pos.row, pos.column); - this.base.$insertRight = true; - this.completions = new FilteredList(options.matches); - return this.openPopup(this.editor, "", keepPopupPosition); - } - var _id = this.gatherCompletionsId; - var detachIfFinished = function(results) { - if (!results.finished) return; - return this.detach(); - }.bind(this); - - var processResults = function(results) { - var prefix = results.prefix; - var matches = results.matches; - - this.completions = new FilteredList(matches); - - if (this.exactMatch) - this.completions.exactMatch = true; - - this.completions.setFilter(prefix); - var filtered = this.completions.filtered; - if (!filtered.length) - return detachIfFinished(results); - if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet) - return detachIfFinished(results); - if (this.autoInsert && filtered.length == 1 && results.finished) - return this.insertMatch(filtered[0]); - - this.openPopup(this.editor, prefix, keepPopupPosition); - }.bind(this); - - var isImmediate = true; - var immediateResults = null; - this.gatherCompletions(this.editor, function(err, results) { - var prefix = results.prefix; - var matches = results && results.matches; - - if (!matches || !matches.length) - return detachIfFinished(results); - if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId) - return; - if (isImmediate) { - immediateResults = results; - return; - } - - processResults(results); - }.bind(this)); - - isImmediate = false; - if (immediateResults) { - var results = immediateResults; - immediateResults = null; - processResults(results); - } - }; - - this.cancelContextMenu = function() { - this.editor.$mouseHandler.cancelContextMenu(); - }; - - this.updateDocTooltip = function() { - var popup = this.popup; - var all = popup.data; - var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]); - var doc = null; - if (!selected || !this.editor || !this.popup.isOpen) - return this.hideDocTooltip(); - this.editor.completers.some(function(completer) { - if (completer.getDocTooltip) - doc = completer.getDocTooltip(selected); - return doc; - }); - if (!doc && typeof selected != "string") - doc = selected; - - if (typeof doc == "string") - doc = {docText: doc}; - if (!doc || !(doc.docHTML || doc.docText)) - return this.hideDocTooltip(); - this.showDocTooltip(doc); - }; - - this.showDocTooltip = function(item) { - if (!this.tooltipNode) { - this.tooltipNode = dom.createElement("div"); - this.tooltipNode.className = "ace_tooltip ace_doc-tooltip"; - this.tooltipNode.style.margin = 0; - this.tooltipNode.style.pointerEvents = "auto"; - this.tooltipNode.tabIndex = -1; - this.tooltipNode.onblur = this.blurListener.bind(this); - this.tooltipNode.onclick = this.onTooltipClick.bind(this); - } - - var tooltipNode = this.tooltipNode; - if (item.docHTML) { - tooltipNode.innerHTML = item.docHTML; - } else if (item.docText) { - tooltipNode.textContent = item.docText; - } - - if (!tooltipNode.parentNode) - document.body.appendChild(tooltipNode); - var popup = this.popup; - var rect = popup.container.getBoundingClientRect(); - tooltipNode.style.top = popup.container.style.top; - tooltipNode.style.bottom = popup.container.style.bottom; - - tooltipNode.style.display = "block"; - if (window.innerWidth - rect.right < 320) { - if (rect.left < 320) { - if(popup.isTopdown) { - tooltipNode.style.top = rect.bottom + "px"; - tooltipNode.style.left = rect.left + "px"; - tooltipNode.style.right = ""; - tooltipNode.style.bottom = ""; - } else { - tooltipNode.style.top = popup.container.offsetTop - tooltipNode.offsetHeight + "px"; - tooltipNode.style.left = rect.left + "px"; - tooltipNode.style.right = ""; - tooltipNode.style.bottom = ""; - } - } else { - tooltipNode.style.right = window.innerWidth - rect.left + "px"; - tooltipNode.style.left = ""; - } - } else { - tooltipNode.style.left = (rect.right + 1) + "px"; - tooltipNode.style.right = ""; - } - }; - - this.hideDocTooltip = function() { - this.tooltipTimer.cancel(); - if (!this.tooltipNode) return; - var el = this.tooltipNode; - if (!this.editor.isFocused() && document.activeElement == el) - this.editor.focus(); - this.tooltipNode = null; - if (el.parentNode) - el.parentNode.removeChild(el); - }; - - this.onTooltipClick = function(e) { - var a = e.target; - while (a && a != this.tooltipNode) { - if (a.nodeName == "A" && a.href) { - a.rel = "noreferrer"; - a.target = "_blank"; - break; - } - a = a.parentNode; - } - }; - - this.destroy = function() { - this.detach(); - if (this.popup) { - this.popup.destroy(); - var el = this.popup.container; - if (el && el.parentNode) - el.parentNode.removeChild(el); - } - if (this.editor && this.editor.completer == this) - this.editor.completer == null; - this.popup = null; - }; - -}).call(Autocomplete.prototype); - - -Autocomplete.for = function(editor) { - if (editor.completer) { - return editor.completer; - } - if (config.get("sharedPopups")) { - if (!Autocomplete.$shared) - Autocomplete.$sharedInstance = new Autocomplete(); - editor.completer = Autocomplete.$sharedInstance; - } else { - editor.completer = new Autocomplete(); - editor.once("destroy", function(e, editor) { - editor.completer.destroy(); - }); - } - return editor.completer; -}; - -Autocomplete.startCommand = { - name: "startAutocomplete", - exec: function(editor, options) { - var completer = Autocomplete.for(editor); - completer.autoInsert = false; - completer.autoSelect = true; - completer.showPopup(editor, options); - completer.cancelContextMenu(); - }, - bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space" -}; - -var FilteredList = function(array, filterText) { - this.all = array; - this.filtered = array; - this.filterText = filterText || ""; - this.exactMatch = false; -}; -(function(){ - this.setFilter = function(str) { - if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0) - var matches = this.filtered; - else - var matches = this.all; - - this.filterText = str; - matches = this.filterCompletions(matches, this.filterText); - matches = matches.sort(function(a, b) { - return b.exactMatch - a.exactMatch || b.$score - a.$score - || (a.caption || a.value).localeCompare(b.caption || b.value); - }); - var prev = null; - matches = matches.filter(function(item){ - var caption = item.snippet || item.caption || item.value; - if (caption === prev) return false; - prev = caption; - return true; - }); - - this.filtered = matches; - }; - this.filterCompletions = function(items, needle) { - var results = []; - var upper = needle.toUpperCase(); - var lower = needle.toLowerCase(); - loop: for (var i = 0, item; item = items[i]; i++) { - var caption = item.caption || item.value || item.snippet; - if (!caption) continue; - var lastIndex = -1; - var matchMask = 0; - var penalty = 0; - var index, distance; - - if (this.exactMatch) { - if (needle !== caption.substr(0, needle.length)) - continue loop; - } else { - var fullMatchIndex = caption.toLowerCase().indexOf(lower); - if (fullMatchIndex > -1) { - penalty = fullMatchIndex; - } else { - for (var j = 0; j < needle.length; j++) { - var i1 = caption.indexOf(lower[j], lastIndex + 1); - var i2 = caption.indexOf(upper[j], lastIndex + 1); - index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2; - if (index < 0) - continue loop; - distance = index - lastIndex - 1; - if (distance > 0) { - if (lastIndex === -1) - penalty += 10; - penalty += distance; - matchMask = matchMask | (1 << j); - } - lastIndex = index; - } - } - } - item.matchMask = matchMask; - item.exactMatch = penalty ? 0 : 1; - item.$score = (item.score || 0) - penalty; - results.push(item); - } - return results; - }; -}).call(FilteredList.prototype); - -exports.Autocomplete = Autocomplete; -exports.FilteredList = FilteredList; - -}); - -define("ace/ext/menu_tools/overlay_page",["require","exports","module","ace/lib/dom"], function(require, exports, module) { -'use strict'; -var dom = require("../../lib/dom"); -var cssText = "#ace_settingsmenu, #kbshortcutmenu {\ -background-color: #F7F7F7;\ -color: black;\ -box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\ -padding: 1em 0.5em 2em 1em;\ -overflow: auto;\ -position: absolute;\ -margin: 0;\ -bottom: 0;\ -right: 0;\ -top: 0;\ -z-index: 9991;\ -cursor: default;\ -}\ -.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\ -box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\ -background-color: rgba(255, 255, 255, 0.6);\ -color: black;\ -}\ -.ace_optionsMenuEntry:hover {\ -background-color: rgba(100, 100, 100, 0.1);\ -transition: all 0.3s\ -}\ -.ace_closeButton {\ -background: rgba(245, 146, 146, 0.5);\ -border: 1px solid #F48A8A;\ -border-radius: 50%;\ -padding: 7px;\ -position: absolute;\ -right: -8px;\ -top: -8px;\ -z-index: 100000;\ -}\ -.ace_closeButton{\ -background: rgba(245, 146, 146, 0.9);\ -}\ -.ace_optionsMenuKey {\ -color: darkslateblue;\ -font-weight: bold;\ -}\ -.ace_optionsMenuCommand {\ -color: darkcyan;\ -font-weight: normal;\ -}\ -.ace_optionsMenuEntry input, .ace_optionsMenuEntry button {\ -vertical-align: middle;\ -}\ -.ace_optionsMenuEntry button[ace_selected_button=true] {\ -background: #e7e7e7;\ -box-shadow: 1px 0px 2px 0px #adadad inset;\ -border-color: #adadad;\ -}\ -.ace_optionsMenuEntry button {\ -background: white;\ -border: 1px solid lightgray;\ -margin: 0px;\ -}\ -.ace_optionsMenuEntry button:hover{\ -background: #f0f0f0;\ -}"; -dom.importCssString(cssText, "settings_menu.css", false); - -module.exports.overlayPage = function overlayPage(editor, contentElement, callback) { - var closer = document.createElement('div'); - var ignoreFocusOut = false; - - function documentEscListener(e) { - if (e.keyCode === 27) { - close(); - } - } - - function close() { - if (!closer) return; - document.removeEventListener('keydown', documentEscListener); - closer.parentNode.removeChild(closer); - if (editor) { - editor.focus(); - } - closer = null; - callback && callback(); - } - function setIgnoreFocusOut(ignore) { - ignoreFocusOut = ignore; - if (ignore) { - closer.style.pointerEvents = "none"; - contentElement.style.pointerEvents = "auto"; - } - } - - closer.style.cssText = 'margin: 0; padding: 0; ' + - 'position: fixed; top:0; bottom:0; left:0; right:0;' + - 'z-index: 9990; ' + - (editor ? 'background-color: rgba(0, 0, 0, 0.3);' : ''); - closer.addEventListener('click', function(e) { - if (!ignoreFocusOut) { - close(); - } - }); - document.addEventListener('keydown', documentEscListener); - - contentElement.addEventListener('click', function (e) { - e.stopPropagation(); - }); - - closer.appendChild(contentElement); - document.body.appendChild(closer); - if (editor) { - editor.blur(); - } - return { - close: close, - setIgnoreFocusOut: setIgnoreFocusOut - }; -}; - -}); - -define("ace/ext/modelist",["require","exports","module"], function(require, exports, module) { -"use strict"; - -var modes = []; -function getModeForPath(path) { - var mode = modesByName.text; - var fileName = path.split(/[\/\\]/).pop(); - for (var i = 0; i < modes.length; i++) { - if (modes[i].supportsFile(fileName)) { - mode = modes[i]; - break; - } - } - return mode; -} - -var Mode = function(name, caption, extensions) { - this.name = name; - this.caption = caption; - this.mode = "ace/mode/" + name; - this.extensions = extensions; - var re; - if (/\^/.test(extensions)) { - re = extensions.replace(/\|(\^)?/g, function(a, b){ - return "$|" + (b ? "^" : "^.*\\."); - }) + "$"; - } else { - re = "^.*\\.(" + extensions + ")$"; - } - - this.extRe = new RegExp(re, "gi"); -}; - -Mode.prototype.supportsFile = function(filename) { - return filename.match(this.extRe); -}; -var supportedModes = { - ABAP: ["abap"], - ABC: ["abc"], - ActionScript:["as"], - ADA: ["ada|adb"], - Alda: ["alda"], - Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"], - Apex: ["apex|cls|trigger|tgr"], - AQL: ["aql"], - AsciiDoc: ["asciidoc|adoc"], - ASL: ["dsl|asl|asl.json"], - Assembly_x86:["asm|a"], - AutoHotKey: ["ahk"], - BatchFile: ["bat|cmd"], - C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp|ino"], - C9Search: ["c9search_results"], - Cirru: ["cirru|cr"], - Clojure: ["clj|cljs"], - Cobol: ["CBL|COB"], - coffee: ["coffee|cf|cson|^Cakefile"], - ColdFusion: ["cfm"], - Crystal: ["cr"], - CSharp: ["cs"], - Csound_Document: ["csd"], - Csound_Orchestra: ["orc"], - Csound_Score: ["sco"], - CSS: ["css"], - Curly: ["curly"], - D: ["d|di"], - Dart: ["dart"], - Diff: ["diff|patch"], - Dockerfile: ["^Dockerfile"], - Dot: ["dot"], - Drools: ["drl"], - Edifact: ["edi"], - Eiffel: ["e|ge"], - EJS: ["ejs"], - Elixir: ["ex|exs"], - Elm: ["elm"], - Erlang: ["erl|hrl"], - Forth: ["frt|fs|ldr|fth|4th"], - Fortran: ["f|f90"], - FSharp: ["fsi|fs|ml|mli|fsx|fsscript"], - FSL: ["fsl"], - FTL: ["ftl"], - Gcode: ["gcode"], - Gherkin: ["feature"], - Gitignore: ["^.gitignore"], - Glsl: ["glsl|frag|vert"], - Gobstones: ["gbs"], - golang: ["go"], - GraphQLSchema: ["gql"], - Groovy: ["groovy"], - HAML: ["haml"], - Handlebars: ["hbs|handlebars|tpl|mustache"], - Haskell: ["hs"], - Haskell_Cabal: ["cabal"], - haXe: ["hx"], - Hjson: ["hjson"], - HTML: ["html|htm|xhtml|vue|we|wpy"], - HTML_Elixir: ["eex|html.eex"], - HTML_Ruby: ["erb|rhtml|html.erb"], - INI: ["ini|conf|cfg|prefs"], - Io: ["io"], - Jack: ["jack"], - Jade: ["jade|pug"], - Java: ["java"], - JavaScript: ["js|jsm|jsx"], - JSON: ["json"], - JSON5: ["json5"], - JSONiq: ["jq"], - JSP: ["jsp"], - JSSM: ["jssm|jssm_state"], - JSX: ["jsx"], - Julia: ["jl"], - Kotlin: ["kt|kts"], - LaTeX: ["tex|latex|ltx|bib"], - Latte: ["latte"], - LESS: ["less"], - Liquid: ["liquid"], - Lisp: ["lisp"], - LiveScript: ["ls"], - LogiQL: ["logic|lql"], - LSL: ["lsl"], - Lua: ["lua"], - LuaPage: ["lp"], - Lucene: ["lucene"], - Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"], - Markdown: ["md|markdown"], - Mask: ["mask"], - MATLAB: ["matlab"], - Maze: ["mz"], - MediaWiki: ["wiki|mediawiki"], - MEL: ["mel"], - MIPS: ["s|asm"], - MIXAL: ["mixal"], - MUSHCode: ["mc|mush"], - MySQL: ["mysql"], - Nginx: ["nginx|conf"], - Nim: ["nim"], - Nix: ["nix"], - NSIS: ["nsi|nsh"], - Nunjucks: ["nunjucks|nunjs|nj|njk"], - ObjectiveC: ["m|mm"], - OCaml: ["ml|mli"], - Pascal: ["pas|p"], - Perl: ["pl|pm"], - pgSQL: ["pgsql"], - PHP: ["php|inc|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"], - PHP_Laravel_blade: ["blade.php"], - Pig: ["pig"], - Powershell: ["ps1"], - Praat: ["praat|praatscript|psc|proc"], - Prisma: ["prisma"], - Prolog: ["plg|prolog"], - Properties: ["properties"], - Protobuf: ["proto"], - Puppet: ["epp|pp"], - Python: ["py"], - QML: ["qml"], - R: ["r"], - Raku: ["raku|rakumod|rakutest|p6|pl6|pm6"], - Razor: ["cshtml|asp"], - RDoc: ["Rd"], - Red: ["red|reds"], - RHTML: ["Rhtml"], - RST: ["rst"], - Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"], - Rust: ["rs"], - SASS: ["sass"], - SCAD: ["scad"], - Scala: ["scala|sbt"], - Scheme: ["scm|sm|rkt|oak|scheme"], - Scrypt: ["scrypt"], - SCSS: ["scss"], - SH: ["sh|bash|^.bashrc"], - SJS: ["sjs"], - Slim: ["slim|skim"], - Smarty: ["smarty|tpl"], - Smithy: ["smithy"], - snippets: ["snippets"], - Soy_Template:["soy"], - Space: ["space"], - SQL: ["sql"], - SQLServer: ["sqlserver"], - Stylus: ["styl|stylus"], - SVG: ["svg"], - Swift: ["swift"], - Tcl: ["tcl"], - Terraform: ["tf", "tfvars", "terragrunt"], - Tex: ["tex"], - Text: ["txt"], - Textile: ["textile"], - Toml: ["toml"], - TSX: ["tsx"], - Twig: ["twig|swig"], - Typescript: ["ts|typescript|str"], - Vala: ["vala"], - VBScript: ["vbs|vb"], - Velocity: ["vm"], - Verilog: ["v|vh|sv|svh"], - VHDL: ["vhd|vhdl"], - Visualforce: ["vfp|component|page"], - Wollok: ["wlk|wpgm|wtest"], - XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"], - XQuery: ["xq"], - YAML: ["yaml|yml"], - Zeek: ["zeek|bro"], - Django: ["html"] -}; - -var nameOverrides = { - ObjectiveC: "Objective-C", - CSharp: "C#", - golang: "Go", - C_Cpp: "C and C++", - Csound_Document: "Csound Document", - Csound_Orchestra: "Csound", - Csound_Score: "Csound Score", - coffee: "CoffeeScript", - HTML_Ruby: "HTML (Ruby)", - HTML_Elixir: "HTML (Elixir)", - FTL: "FreeMarker", - PHP_Laravel_blade: "PHP (Blade Template)", - Perl6: "Perl 6", - AutoHotKey: "AutoHotkey / AutoIt" -}; - -var modesByName = {}; -for (var name in supportedModes) { - var data = supportedModes[name]; - var displayName = (nameOverrides[name] || name).replace(/_/g, " "); - var filename = name.toLowerCase(); - var mode = new Mode(filename, displayName, data[0]); - modesByName[filename] = mode; - modes.push(mode); -} - -module.exports = { - getModeForPath: getModeForPath, - modes: modes, - modesByName: modesByName -}; - -}); - -define("ace/ext/prompt",["require","exports","module","ace/range","ace/lib/dom","ace/ext/menu_tools/get_editor_keyboard_shortcuts","ace/autocomplete","ace/autocomplete/popup","ace/autocomplete/popup","ace/undomanager","ace/tokenizer","ace/ext/menu_tools/overlay_page","ace/ext/modelist"], function(require, exports, module) { -"use strict"; - -var Range = require("../range").Range; -var dom = require("../lib/dom"); -var shortcuts = require("../ext/menu_tools/get_editor_keyboard_shortcuts"); -var FilteredList= require("../autocomplete").FilteredList; -var AcePopup = require('../autocomplete/popup').AcePopup; -var $singleLineEditor = require('../autocomplete/popup').$singleLineEditor; -var UndoManager = require("../undomanager").UndoManager; -var Tokenizer = require("../tokenizer").Tokenizer; -var overlayPage = require("./menu_tools/overlay_page").overlayPage; -var modelist = require("./modelist"); -var openPrompt; - -function prompt(editor, message, options, callback) { - if (typeof message == "object") { - return prompt(editor, "", message, options); - } - if (openPrompt) { - var lastPrompt = openPrompt; - editor = lastPrompt.editor; - lastPrompt.close(); - if (lastPrompt.name && lastPrompt.name == options.name) - return; - } - if (options.$type) - return prompt[options.$type](editor, callback); - - var cmdLine = $singleLineEditor(); - cmdLine.session.setUndoManager(new UndoManager()); - - var el = dom.buildDom(["div", {class: "ace_prompt_container" + (options.hasDescription ? " input-box-with-description" : "")}]); - var overlay = overlayPage(editor, el, done); - el.appendChild(cmdLine.container); - - if (editor) { - editor.cmdLine = cmdLine; - cmdLine.setOption("fontSize", editor.getOption("fontSize")); - } - if (message) { - cmdLine.setValue(message, 1); - } - if (options.selection) { - cmdLine.selection.setRange({ - start: cmdLine.session.doc.indexToPosition(options.selection[0]), - end: cmdLine.session.doc.indexToPosition(options.selection[1]) - }); - } - - if (options.getCompletions) { - var popup = new AcePopup(); - popup.renderer.setStyle("ace_autocomplete_inline"); - popup.container.style.display = "block"; - popup.container.style.maxWidth = "600px"; - popup.container.style.width = "100%"; - popup.container.style.marginTop = "3px"; - popup.renderer.setScrollMargin(2, 2, 0, 0); - popup.autoSelect = false; - popup.renderer.$maxLines = 15; - popup.setRow(-1); - popup.on("click", function(e) { - var data = popup.getData(popup.getRow()); - if (!data.error) { - cmdLine.setValue(data.value || data.name || data); - accept(); - e.stop(); - } - }); - el.appendChild(popup.container); - updateCompletions(); - } - - if (options.$rules) { - var tokenizer = new Tokenizer(options.$rules); - cmdLine.session.bgTokenizer.setTokenizer(tokenizer); - } - - if (options.placeholder) { - cmdLine.setOption("placeholder", options.placeholder); - } - - if (options.hasDescription) { - var promptTextContainer = dom.buildDom(["div", {class: "ace_prompt_text_container"}]); - dom.buildDom(options.prompt || "Press 'Enter' to confirm or 'Escape' to cancel", promptTextContainer); - el.appendChild(promptTextContainer); - } - - overlay.setIgnoreFocusOut(options.ignoreFocusOut); - - function accept() { - var val; - if (popup && popup.getCursorPosition().row > 0) { - val = valueFromRecentList(); - } else { - val = cmdLine.getValue(); - } - var curData = popup ? popup.getData(popup.getRow()) : val; - if (curData && !curData.error) { - done(); - options.onAccept && options.onAccept({ - value: val, - item: curData - }, cmdLine); - } - } - - var keys = { - "Enter": accept, - "Esc|Shift-Esc": function() { - options.onCancel && options.onCancel(cmdLine.getValue(), cmdLine); - done(); - } - }; - - if (popup) { - Object.assign(keys, { - "Up": function(editor) { popup.goTo("up"); valueFromRecentList();}, - "Down": function(editor) { popup.goTo("down"); valueFromRecentList();}, - "Ctrl-Up|Ctrl-Home": function(editor) { popup.goTo("start"); valueFromRecentList();}, - "Ctrl-Down|Ctrl-End": function(editor) { popup.goTo("end"); valueFromRecentList();}, - "Tab": function(editor) { - popup.goTo("down"); valueFromRecentList(); - }, - "PageUp": function(editor) { popup.gotoPageUp(); valueFromRecentList();}, - "PageDown": function(editor) { popup.gotoPageDown(); valueFromRecentList();} - }); - } - - cmdLine.commands.bindKeys(keys); - - function done() { - overlay.close(); - callback && callback(); - openPrompt = null; - } - - cmdLine.on("input", function() { - options.onInput && options.onInput(); - updateCompletions(); - }); - - function updateCompletions() { - if (options.getCompletions) { - var prefix; - if (options.getPrefix) { - prefix = options.getPrefix(cmdLine); - } - - var completions = options.getCompletions(cmdLine); - popup.setData(completions, prefix); - popup.resize(true); - } - } - - function valueFromRecentList() { - var current = popup.getData(popup.getRow()); - if (current && !current.error) - return current.value || current.caption || current; - } - - cmdLine.resize(true); - if (popup) { - popup.resize(true); - } - cmdLine.focus(); - - openPrompt = { - close: done, - name: options.name, - editor: editor - }; -} - -prompt.gotoLine = function(editor, callback) { - function stringifySelection(selection) { - if (!Array.isArray(selection)) - selection = [selection]; - return selection.map(function(r) { - var cursor = r.isBackwards ? r.start: r.end; - var anchor = r.isBackwards ? r.end: r.start; - var row = anchor.row; - var s = (row + 1) + ":" + anchor.column; - - if (anchor.row == cursor.row) { - if (anchor.column != cursor.column) - s += ">" + ":" + cursor.column; - } else { - s += ">" + (cursor.row + 1) + ":" + cursor.column; - } - return s; - }).reverse().join(", "); - } - - prompt(editor, ":" + stringifySelection(editor.selection.toJSON()), { - name: "gotoLine", - selection: [1, Number.MAX_VALUE], - onAccept: function(data) { - var value = data.value; - var _history = prompt.gotoLine._history; - if (!_history) - prompt.gotoLine._history = _history = []; - if (_history.indexOf(value) != -1) - _history.splice(_history.indexOf(value), 1); - _history.unshift(value); - if (_history.length > 20) _history.length = 20; - - - var pos = editor.getCursorPosition(); - var ranges = []; - value.replace(/^:/, "").split(/,/).map(function(str) { - var parts = str.split(/([<>:+-]|c?\d+)|[^c\d<>:+-]+/).filter(Boolean); - var i = 0; - function readPosition() { - var c = parts[i++]; - if (!c) return; - if (c[0] == "c") { - var index = parseInt(c.slice(1)) || 0; - return editor.session.doc.indexToPosition(index); - } - var row = pos.row; - var column = 0; - if (/\d/.test(c)) { - row = parseInt(c) - 1; - c = parts[i++]; - } - if (c == ":") { - c = parts[i++]; - if (/\d/.test(c)) { - column = parseInt(c) || 0; - } - } - return {row: row, column: column}; - } - pos = readPosition(); - var range = Range.fromPoints(pos, pos); - if (parts[i] == ">") { - i++; - range.end = readPosition(); - } - else if (parts[i] == "<") { - i++; - range.start = readPosition(); - } - ranges.unshift(range); - }); - editor.selection.fromJSON(ranges); - var scrollTop = editor.renderer.scrollTop; - editor.renderer.scrollSelectionIntoView( - editor.selection.anchor, - editor.selection.cursor, - 0.5 - ); - editor.renderer.animateScrolling(scrollTop); - }, - history: function() { - var undoManager = editor.session.getUndoManager(); - if (!prompt.gotoLine._history) - return []; - return prompt.gotoLine._history; - - }, - getCompletions: function(cmdLine) { - var value = cmdLine.getValue(); - var m = value.replace(/^:/, "").split(":"); - var row = Math.min(parseInt(m[0]) || 1, editor.session.getLength()) - 1; - var line = editor.session.getLine(row); - var current = value + " " + line; - return [current].concat(this.history()); - }, - $rules: { - start: [{ - regex: /\d+/, - token: "string" - }, { - regex: /[:,><+\-c]/, - token: "keyword" - }] - } - }); -}; - -prompt.commands = function(editor, callback) { - function normalizeName(name) { - return (name || "").replace(/^./, function(x) { - return x.toUpperCase(x); - }).replace(/[a-z][A-Z]/g, function(x) { - return x[0] + " " + x[1].toLowerCase(x); - }); - } - function getEditorCommandsByName(excludeCommands) { - var commandsByName = []; - var commandMap = {}; - editor.keyBinding.$handlers.forEach(function(handler) { - var platform = handler.platform; - var cbn = handler.byName; - for (var i in cbn) { - var key = cbn[i].bindKey; - if (typeof key !== "string") { - key = key && key[platform] || ""; - } - var commands = cbn[i]; - var description = commands.description || normalizeName(commands.name); - if (!Array.isArray(commands)) - commands = [commands]; - commands.forEach(function(command) { - if (typeof command != "string") - command = command.name; - var needle = excludeCommands.find(function(el) { - return el === command; - }); - if (!needle) { - if (commandMap[command]) { - commandMap[command].key += "|" + key; - } else { - commandMap[command] = {key: key, command: command, description: description}; - commandsByName.push(commandMap[command]); - } - } - }); - } - }); - return commandsByName; - } - var excludeCommandsList = ["insertstring", "inserttext", "setIndentation", "paste"]; - var shortcutsArray = getEditorCommandsByName(excludeCommandsList); - shortcutsArray = shortcutsArray.map(function(item) { - return {value: item.description, meta: item.key, command: item.command}; - }); - prompt(editor, "", { - name: "commands", - selection: [0, Number.MAX_VALUE], - maxHistoryCount: 5, - onAccept: function(data) { - if (data.item) { - var commandName = data.item.command; - this.addToHistory(data.item); - - editor.execCommand(commandName); - } - }, - addToHistory: function(item) { - var history = this.history(); - history.unshift(item); - delete item.message; - for (var i = 1; i < history.length; i++) { - if (history[i]["command"] == item.command ) { - history.splice(i, 1); - break; - } - } - if (this.maxHistoryCount > 0 && history.length > this.maxHistoryCount) { - history.splice(history.length - 1, 1); - } - prompt.commands.history = history; - }, - history: function() { - return prompt.commands.history || []; - }, - getPrefix: function(cmdLine) { - var currentPos = cmdLine.getCursorPosition(); - var filterValue = cmdLine.getValue(); - return filterValue.substring(0, currentPos.column); - }, - getCompletions: function(cmdLine) { - function getFilteredCompletions(commands, prefix) { - var resultCommands = JSON.parse(JSON.stringify(commands)); - - var filtered = new FilteredList(resultCommands); - return filtered.filterCompletions(resultCommands, prefix); - } - - function getUniqueCommandList(commands, usedCommands) { - if (!usedCommands || !usedCommands.length) { - return commands; - } - var excludeCommands = []; - usedCommands.forEach(function(item) { - excludeCommands.push(item.command); - }); - - var resultCommands = []; - - commands.forEach(function(item) { - if (excludeCommands.indexOf(item.command) === -1) { - resultCommands.push(item); - } - }); - - return resultCommands; - } - - var prefix = this.getPrefix(cmdLine); - var recentlyUsedCommands = getFilteredCompletions(this.history(), prefix); - var otherCommands = getUniqueCommandList(shortcutsArray, recentlyUsedCommands); - otherCommands = getFilteredCompletions(otherCommands, prefix); - - if (recentlyUsedCommands.length && otherCommands.length) { - recentlyUsedCommands[0]["message"] = " Recently used"; - otherCommands[0]["message"] = " Other commands"; - } - - var completions = recentlyUsedCommands.concat(otherCommands); - return completions.length > 0 ? completions : [{ - value: "No matching commands", - error: 1 - }]; - } - }); -}; - -prompt.modes = function(editor, callback) { - var modesArray = modelist.modes; - modesArray = modesArray.map(function(item) { - return {value: item.caption, mode: item.name}; - }); - prompt(editor, "", { - name: "modes", - selection: [0, Number.MAX_VALUE], - onAccept: function(data) { - if (data.item) { - var modeName = "ace/mode/" + data.item.mode; - editor.session.setMode(modeName); - } - }, - getPrefix: function(cmdLine) { - var currentPos = cmdLine.getCursorPosition(); - var filterValue = cmdLine.getValue(); - return filterValue.substring(0, currentPos.column); - }, - getCompletions: function(cmdLine) { - function getFilteredCompletions(modes, prefix) { - var resultCommands = JSON.parse(JSON.stringify(modes)); - - var filtered = new FilteredList(resultCommands); - return filtered.filterCompletions(resultCommands, prefix); - } - - var prefix = this.getPrefix(cmdLine); - var completions = getFilteredCompletions(modesArray, prefix); - return completions.length > 0 ? completions : [{ - "caption": "No mode matching", - "value": "No mode matching", - "error": 1 - }]; - } - }); -}; - -dom.importCssString(".ace_prompt_container {\ - max-width: 600px;\ - width: 100%;\ - margin: 20px auto;\ - padding: 3px;\ - background: white;\ - border-radius: 2px;\ - box-shadow: 0px 2px 3px 0px #555;\ -}", "promtp.css", false); - - -exports.prompt = prompt; - -}); (function() { - window.require(["ace/ext/prompt"], function(m) { - if (typeof module == "object" && typeof exports == "object" && module) { - module.exports = m; - } - }); - })(); - \ No newline at end of file diff --git a/GameDev/bin/Release/editor/ace/ext-searchbox.js b/GameDev/bin/Release/editor/ace/ext-searchbox.js deleted file mode 100644 index 8be7e8c1..00000000 --- a/GameDev/bin/Release/editor/ace/ext-searchbox.js +++ /dev/null @@ -1,514 +0,0 @@ -define("ace/ext/searchbox",["require","exports","module","ace/lib/dom","ace/lib/lang","ace/lib/event","ace/keyboard/hash_handler","ace/lib/keys"], function(require, exports, module) { -"use strict"; - -var dom = require("../lib/dom"); -var lang = require("../lib/lang"); -var event = require("../lib/event"); -var searchboxCss = "\ -.ace_search {\ -background-color: #ddd;\ -color: #666;\ -border: 1px solid #cbcbcb;\ -border-top: 0 none;\ -overflow: hidden;\ -margin: 0;\ -padding: 4px 6px 0 4px;\ -position: absolute;\ -top: 0;\ -z-index: 99;\ -white-space: normal;\ -}\ -.ace_search.left {\ -border-left: 0 none;\ -border-radius: 0px 0px 5px 0px;\ -left: 0;\ -}\ -.ace_search.right {\ -border-radius: 0px 0px 0px 5px;\ -border-right: 0 none;\ -right: 0;\ -}\ -.ace_search_form, .ace_replace_form {\ -margin: 0 20px 4px 0;\ -overflow: hidden;\ -line-height: 1.9;\ -}\ -.ace_replace_form {\ -margin-right: 0;\ -}\ -.ace_search_form.ace_nomatch {\ -outline: 1px solid red;\ -}\ -.ace_search_field {\ -border-radius: 3px 0 0 3px;\ -background-color: white;\ -color: black;\ -border: 1px solid #cbcbcb;\ -border-right: 0 none;\ -outline: 0;\ -padding: 0;\ -font-size: inherit;\ -margin: 0;\ -line-height: inherit;\ -padding: 0 6px;\ -min-width: 17em;\ -vertical-align: top;\ -min-height: 1.8em;\ -box-sizing: content-box;\ -}\ -.ace_searchbtn {\ -border: 1px solid #cbcbcb;\ -line-height: inherit;\ -display: inline-block;\ -padding: 0 6px;\ -background: #fff;\ -border-right: 0 none;\ -border-left: 1px solid #dcdcdc;\ -cursor: pointer;\ -margin: 0;\ -position: relative;\ -color: #666;\ -}\ -.ace_searchbtn:last-child {\ -border-radius: 0 3px 3px 0;\ -border-right: 1px solid #cbcbcb;\ -}\ -.ace_searchbtn:disabled {\ -background: none;\ -cursor: default;\ -}\ -.ace_searchbtn:hover {\ -background-color: #eef1f6;\ -}\ -.ace_searchbtn.prev, .ace_searchbtn.next {\ -padding: 0px 0.7em\ -}\ -.ace_searchbtn.prev:after, .ace_searchbtn.next:after {\ -content: \"\";\ -border: solid 2px #888;\ -width: 0.5em;\ -height: 0.5em;\ -border-width: 2px 0 0 2px;\ -display:inline-block;\ -transform: rotate(-45deg);\ -}\ -.ace_searchbtn.next:after {\ -border-width: 0 2px 2px 0 ;\ -}\ -.ace_searchbtn_close {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\ -border-radius: 50%;\ -border: 0 none;\ -color: #656565;\ -cursor: pointer;\ -font: 16px/16px Arial;\ -padding: 0;\ -height: 14px;\ -width: 14px;\ -top: 9px;\ -right: 7px;\ -position: absolute;\ -}\ -.ace_searchbtn_close:hover {\ -background-color: #656565;\ -background-position: 50% 100%;\ -color: white;\ -}\ -.ace_button {\ -margin-left: 2px;\ -cursor: pointer;\ --webkit-user-select: none;\ --moz-user-select: none;\ --o-user-select: none;\ --ms-user-select: none;\ -user-select: none;\ -overflow: hidden;\ -opacity: 0.7;\ -border: 1px solid rgba(100,100,100,0.23);\ -padding: 1px;\ -box-sizing: border-box!important;\ -color: black;\ -}\ -.ace_button:hover {\ -background-color: #eee;\ -opacity:1;\ -}\ -.ace_button:active {\ -background-color: #ddd;\ -}\ -.ace_button.checked {\ -border-color: #3399ff;\ -opacity:1;\ -}\ -.ace_search_options{\ -margin-bottom: 3px;\ -text-align: right;\ --webkit-user-select: none;\ --moz-user-select: none;\ --o-user-select: none;\ --ms-user-select: none;\ -user-select: none;\ -clear: both;\ -}\ -.ace_search_counter {\ -float: left;\ -font-family: arial;\ -padding: 0 8px;\ -}"; -var HashHandler = require("../keyboard/hash_handler").HashHandler; -var keyUtil = require("../lib/keys"); - -var MAX_COUNT = 999; - -dom.importCssString(searchboxCss, "ace_searchbox", false); - -var SearchBox = function(editor, range, showReplaceForm) { - var div = dom.createElement("div"); - dom.buildDom(["div", {class:"ace_search right"}, - ["span", {action: "hide", class: "ace_searchbtn_close"}], - ["div", {class: "ace_search_form"}, - ["input", {class: "ace_search_field", placeholder: "Search for", spellcheck: "false"}], - ["span", {action: "findPrev", class: "ace_searchbtn prev"}, "\u200b"], - ["span", {action: "findNext", class: "ace_searchbtn next"}, "\u200b"], - ["span", {action: "findAll", class: "ace_searchbtn", title: "Alt-Enter"}, "All"] - ], - ["div", {class: "ace_replace_form"}, - ["input", {class: "ace_search_field", placeholder: "Replace with", spellcheck: "false"}], - ["span", {action: "replaceAndFindNext", class: "ace_searchbtn"}, "Replace"], - ["span", {action: "replaceAll", class: "ace_searchbtn"}, "All"] - ], - ["div", {class: "ace_search_options"}, - ["span", {action: "toggleReplace", class: "ace_button", title: "Toggle Replace mode", - style: "float:left;margin-top:-2px;padding:0 5px;"}, "+"], - ["span", {class: "ace_search_counter"}], - ["span", {action: "toggleRegexpMode", class: "ace_button", title: "RegExp Search"}, ".*"], - ["span", {action: "toggleCaseSensitive", class: "ace_button", title: "CaseSensitive Search"}, "Aa"], - ["span", {action: "toggleWholeWords", class: "ace_button", title: "Whole Word Search"}, "\\b"], - ["span", {action: "searchInSelection", class: "ace_button", title: "Search In Selection"}, "S"] - ] - ], div); - this.element = div.firstChild; - - this.setSession = this.setSession.bind(this); - - this.$init(); - this.setEditor(editor); - dom.importCssString(searchboxCss, "ace_searchbox", editor.container); -}; - -(function() { - this.setEditor = function(editor) { - editor.searchBox = this; - editor.renderer.scroller.appendChild(this.element); - this.editor = editor; - }; - - this.setSession = function(e) { - this.searchRange = null; - this.$syncOptions(true); - }; - - this.$initElements = function(sb) { - this.searchBox = sb.querySelector(".ace_search_form"); - this.replaceBox = sb.querySelector(".ace_replace_form"); - this.searchOption = sb.querySelector("[action=searchInSelection]"); - this.replaceOption = sb.querySelector("[action=toggleReplace]"); - this.regExpOption = sb.querySelector("[action=toggleRegexpMode]"); - this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]"); - this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]"); - this.searchInput = this.searchBox.querySelector(".ace_search_field"); - this.replaceInput = this.replaceBox.querySelector(".ace_search_field"); - this.searchCounter = sb.querySelector(".ace_search_counter"); - }; - - this.$init = function() { - var sb = this.element; - - this.$initElements(sb); - - var _this = this; - event.addListener(sb, "mousedown", function(e) { - setTimeout(function(){ - _this.activeInput.focus(); - }, 0); - event.stopPropagation(e); - }); - event.addListener(sb, "click", function(e) { - var t = e.target || e.srcElement; - var action = t.getAttribute("action"); - if (action && _this[action]) - _this[action](); - else if (_this.$searchBarKb.commands[action]) - _this.$searchBarKb.commands[action].exec(_this); - event.stopPropagation(e); - }); - - event.addCommandKeyListener(sb, function(e, hashId, keyCode) { - var keyString = keyUtil.keyCodeToString(keyCode); - var command = _this.$searchBarKb.findKeyCommand(hashId, keyString); - if (command && command.exec) { - command.exec(_this); - event.stopEvent(e); - } - }); - - this.$onChange = lang.delayedCall(function() { - _this.find(false, false); - }); - - event.addListener(this.searchInput, "input", function() { - _this.$onChange.schedule(20); - }); - event.addListener(this.searchInput, "focus", function() { - _this.activeInput = _this.searchInput; - _this.searchInput.value && _this.highlight(); - }); - event.addListener(this.replaceInput, "focus", function() { - _this.activeInput = _this.replaceInput; - _this.searchInput.value && _this.highlight(); - }); - }; - this.$closeSearchBarKb = new HashHandler([{ - bindKey: "Esc", - name: "closeSearchBar", - exec: function(editor) { - editor.searchBox.hide(); - } - }]); - this.$searchBarKb = new HashHandler(); - this.$searchBarKb.bindKeys({ - "Ctrl-f|Command-f": function(sb) { - var isReplace = sb.isReplace = !sb.isReplace; - sb.replaceBox.style.display = isReplace ? "" : "none"; - sb.replaceOption.checked = false; - sb.$syncOptions(); - sb.searchInput.focus(); - }, - "Ctrl-H|Command-Option-F": function(sb) { - if (sb.editor.getReadOnly()) - return; - sb.replaceOption.checked = true; - sb.$syncOptions(); - sb.replaceInput.focus(); - }, - "Ctrl-G|Command-G": function(sb) { - sb.findNext(); - }, - "Ctrl-Shift-G|Command-Shift-G": function(sb) { - sb.findPrev(); - }, - "esc": function(sb) { - setTimeout(function() { sb.hide();}); - }, - "Return": function(sb) { - if (sb.activeInput == sb.replaceInput) - sb.replace(); - sb.findNext(); - }, - "Shift-Return": function(sb) { - if (sb.activeInput == sb.replaceInput) - sb.replace(); - sb.findPrev(); - }, - "Alt-Return": function(sb) { - if (sb.activeInput == sb.replaceInput) - sb.replaceAll(); - sb.findAll(); - }, - "Tab": function(sb) { - (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus(); - } - }); - - this.$searchBarKb.addCommands([{ - name: "toggleRegexpMode", - bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"}, - exec: function(sb) { - sb.regExpOption.checked = !sb.regExpOption.checked; - sb.$syncOptions(); - } - }, { - name: "toggleCaseSensitive", - bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"}, - exec: function(sb) { - sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked; - sb.$syncOptions(); - } - }, { - name: "toggleWholeWords", - bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"}, - exec: function(sb) { - sb.wholeWordOption.checked = !sb.wholeWordOption.checked; - sb.$syncOptions(); - } - }, { - name: "toggleReplace", - exec: function(sb) { - sb.replaceOption.checked = !sb.replaceOption.checked; - sb.$syncOptions(); - } - }, { - name: "searchInSelection", - exec: function(sb) { - sb.searchOption.checked = !sb.searchRange; - sb.setSearchRange(sb.searchOption.checked && sb.editor.getSelectionRange()); - sb.$syncOptions(); - } - }]); - - this.setSearchRange = function(range) { - this.searchRange = range; - if (range) { - this.searchRangeMarker = this.editor.session.addMarker(range, "ace_active-line"); - } else if (this.searchRangeMarker) { - this.editor.session.removeMarker(this.searchRangeMarker); - this.searchRangeMarker = null; - } - }; - - this.$syncOptions = function(preventScroll) { - dom.setCssClass(this.replaceOption, "checked", this.searchRange); - dom.setCssClass(this.searchOption, "checked", this.searchOption.checked); - this.replaceOption.textContent = this.replaceOption.checked ? "-" : "+"; - dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked); - dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked); - dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked); - var readOnly = this.editor.getReadOnly(); - this.replaceOption.style.display = readOnly ? "none" : ""; - this.replaceBox.style.display = this.replaceOption.checked && !readOnly ? "" : "none"; - this.find(false, false, preventScroll); - }; - - this.highlight = function(re) { - this.editor.session.highlight(re || this.editor.$search.$options.re); - this.editor.renderer.updateBackMarkers(); - }; - this.find = function(skipCurrent, backwards, preventScroll) { - var range = this.editor.find(this.searchInput.value, { - skipCurrent: skipCurrent, - backwards: backwards, - wrap: true, - regExp: this.regExpOption.checked, - caseSensitive: this.caseSensitiveOption.checked, - wholeWord: this.wholeWordOption.checked, - preventScroll: preventScroll, - range: this.searchRange - }); - var noMatch = !range && this.searchInput.value; - dom.setCssClass(this.searchBox, "ace_nomatch", noMatch); - this.editor._emit("findSearchBox", { match: !noMatch }); - this.highlight(); - this.updateCounter(); - }; - this.updateCounter = function() { - var editor = this.editor; - var regex = editor.$search.$options.re; - var all = 0; - var before = 0; - if (regex) { - var value = this.searchRange - ? editor.session.getTextRange(this.searchRange) - : editor.getValue(); - - var offset = editor.session.doc.positionToIndex(editor.selection.anchor); - if (this.searchRange) - offset -= editor.session.doc.positionToIndex(this.searchRange.start); - - var last = regex.lastIndex = 0; - var m; - while ((m = regex.exec(value))) { - all++; - last = m.index; - if (last <= offset) - before++; - if (all > MAX_COUNT) - break; - if (!m[0]) { - regex.lastIndex = last += 1; - if (last >= value.length) - break; - } - } - } - this.searchCounter.textContent = before + " of " + (all > MAX_COUNT ? MAX_COUNT + "+" : all); - }; - this.findNext = function() { - this.find(true, false); - }; - this.findPrev = function() { - this.find(true, true); - }; - this.findAll = function(){ - var range = this.editor.findAll(this.searchInput.value, { - regExp: this.regExpOption.checked, - caseSensitive: this.caseSensitiveOption.checked, - wholeWord: this.wholeWordOption.checked - }); - var noMatch = !range && this.searchInput.value; - dom.setCssClass(this.searchBox, "ace_nomatch", noMatch); - this.editor._emit("findSearchBox", { match: !noMatch }); - this.highlight(); - this.hide(); - }; - this.replace = function() { - if (!this.editor.getReadOnly()) - this.editor.replace(this.replaceInput.value); - }; - this.replaceAndFindNext = function() { - if (!this.editor.getReadOnly()) { - this.editor.replace(this.replaceInput.value); - this.findNext(); - } - }; - this.replaceAll = function() { - if (!this.editor.getReadOnly()) - this.editor.replaceAll(this.replaceInput.value); - }; - - this.hide = function() { - this.active = false; - this.setSearchRange(null); - this.editor.off("changeSession", this.setSession); - - this.element.style.display = "none"; - this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb); - this.editor.focus(); - }; - this.show = function(value, isReplace) { - this.active = true; - this.editor.on("changeSession", this.setSession); - this.element.style.display = ""; - this.replaceOption.checked = isReplace; - - if (value) - this.searchInput.value = value; - - this.searchInput.focus(); - this.searchInput.select(); - - this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb); - - this.$syncOptions(true); - }; - - this.isFocused = function() { - var el = document.activeElement; - return el == this.searchInput || el == this.replaceInput; - }; -}).call(SearchBox.prototype); - -exports.SearchBox = SearchBox; - -exports.Search = function(editor, isReplace) { - var sb = editor.searchBox || new SearchBox(editor); - sb.show(editor.session.getTextRange(), isReplace); -}; - -}); (function() { - window.require(["ace/ext/searchbox"], function(m) { - if (typeof module == "object" && typeof exports == "object" && module) { - module.exports = m; - } - }); - })(); - \ No newline at end of file diff --git a/GameDev/bin/Release/editor/ace/mode-javascript.js b/GameDev/bin/Release/editor/ace/mode-javascript.js deleted file mode 100644 index 9aa6bab0..00000000 --- a/GameDev/bin/Release/editor/ace/mode-javascript.js +++ /dev/null @@ -1,720 +0,0 @@ -ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module){"use strict"; -var oop = require("../lib/oop"); -var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; -var DocCommentHighlightRules = function () { - this.$rules = { - "start": [{ - token: "comment.doc.tag", - regex: "@[\\w\\d_]+" // TODO: fix email addresses - }, - DocCommentHighlightRules.getTagRule(), - { - defaultToken: "comment.doc", - caseInsensitive: true - }] - }; -}; -oop.inherits(DocCommentHighlightRules, TextHighlightRules); -DocCommentHighlightRules.getTagRule = function (start) { - return { - token: "comment.doc.tag.storage.type", - regex: "\\b(?:TODO|FIXME|XXX|HACK)\\b" - }; -}; -DocCommentHighlightRules.getStartRule = function (start) { - return { - token: "comment.doc", - regex: "\\/\\*(?=\\*)", - next: start - }; -}; -DocCommentHighlightRules.getEndRule = function (start) { - return { - token: "comment.doc", - regex: "\\*\\/", - next: start - }; -}; -exports.DocCommentHighlightRules = DocCommentHighlightRules; - -}); - -ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module){"use strict"; -var oop = require("../lib/oop"); -var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; -var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; -var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; -var JavaScriptHighlightRules = function (options) { - var keywordMapper = this.createKeywordMapper({ - "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors - "Namespace|QName|XML|XMLList|" + // E4X - "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + - "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + - "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors - "SyntaxError|TypeError|URIError|" + - "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions - "isNaN|parseFloat|parseInt|" + - "JSON|Math|" + // Other - "this|arguments|prototype|window|document", - "keyword": "const|yield|import|get|set|async|await|" + - "break|case|catch|continue|default|delete|do|else|finally|for|function|" + - "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + - "__parent__|__count__|escape|unescape|with|__proto__|" + - "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", - "storage.type": "const|let|var|function", - "constant.language": "null|Infinity|NaN|undefined", - "support.function": "alert", - "constant.language.boolean": "true|false" - }, "identifier"); - var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; - var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex - "u[0-9a-fA-F]{4}|" + // unicode - "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode - "[0-2][0-7]{0,2}|" + // oct - "3[0-7][0-7]?|" + // oct - "[4-7][0-7]?|" + //oct - ".)"; - this.$rules = { - "no_regex": [ - DocCommentHighlightRules.getStartRule("doc-start"), - comments("no_regex"), - { - token: "string", - regex: "'(?=.)", - next: "qstring" - }, { - token: "string", - regex: '"(?=.)', - next: "qqstring" - }, { - token: "constant.numeric", - regex: /0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\b/ - }, { - token: "constant.numeric", - regex: /(?:\d\d*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+\b)?/ - }, { - token: [ - "storage.type", "punctuation.operator", "support.function", - "punctuation.operator", "entity.name.function", "text", "keyword.operator" - ], - regex: "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe + ")(\\s*)(=)", - next: "function_arguments" - }, { - token: [ - "storage.type", "punctuation.operator", "entity.name.function", "text", - "keyword.operator", "text", "storage.type", "text", "paren.lparen" - ], - regex: "(" + identifierRe + ")(\\.)(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token: [ - "entity.name.function", "text", "keyword.operator", "text", "storage.type", - "text", "paren.lparen" - ], - regex: "(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token: [ - "storage.type", "punctuation.operator", "entity.name.function", "text", - "keyword.operator", "text", - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex: "(" + identifierRe + ")(\\.)(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", - next: "function_arguments" - }, { - token: [ - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex: "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", - next: "function_arguments" - }, { - token: [ - "entity.name.function", "text", "punctuation.operator", - "text", "storage.type", "text", "paren.lparen" - ], - regex: "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token: [ - "text", "text", "storage.type", "text", "paren.lparen" - ], - regex: "(:)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token: "keyword", - regex: "from(?=\\s*('|\"))" - }, { - token: "keyword", - regex: "(?:" + kwBeforeRe + ")\\b", - next: "start" - }, { - token: ["support.constant"], - regex: /that\b/ - }, { - token: ["storage.type", "punctuation.operator", "support.function.firebug"], - regex: /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ - }, { - token: keywordMapper, - regex: identifierRe - }, { - token: "punctuation.operator", - regex: /[.](?![.])/, - next: "property" - }, { - token: "storage.type", - regex: /=>/, - next: "start" - }, { - token: "keyword.operator", - regex: /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, - next: "start" - }, { - token: "punctuation.operator", - regex: /[?:,;.]/, - next: "start" - }, { - token: "paren.lparen", - regex: /[\[({]/, - next: "start" - }, { - token: "paren.rparen", - regex: /[\])}]/ - }, { - token: "comment", - regex: /^#!.*$/ - } - ], - property: [{ - token: "text", - regex: "\\s+" - }, { - token: [ - "storage.type", "punctuation.operator", "entity.name.function", "text", - "keyword.operator", "text", - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex: "(" + identifierRe + ")(\\.)(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", - next: "function_arguments" - }, { - token: "punctuation.operator", - regex: /[.](?![.])/ - }, { - token: "support.function", - regex: /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ - }, { - token: "support.function.dom", - regex: /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ - }, { - token: "support.constant", - regex: /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ - }, { - token: "identifier", - regex: identifierRe - }, { - regex: "", - token: "empty", - next: "no_regex" - } - ], - "start": [ - DocCommentHighlightRules.getStartRule("doc-start"), - comments("start"), - { - token: "string.regexp", - regex: "\\/", - next: "regex" - }, { - token: "text", - regex: "\\s+|^$", - next: "start" - }, { - token: "empty", - regex: "", - next: "no_regex" - } - ], - "regex": [ - { - token: "regexp.keyword.operator", - regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" - }, { - token: "string.regexp", - regex: "/[sxngimy]*", - next: "no_regex" - }, { - token: "invalid", - regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ - }, { - token: "constant.language.escape", - regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ - }, { - token: "constant.language.delimiter", - regex: /\|/ - }, { - token: "constant.language.escape", - regex: /\[\^?/, - next: "regex_character_class" - }, { - token: "empty", - regex: "$", - next: "no_regex" - }, { - defaultToken: "string.regexp" - } - ], - "regex_character_class": [ - { - token: "regexp.charclass.keyword.operator", - regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" - }, { - token: "constant.language.escape", - regex: "]", - next: "regex" - }, { - token: "constant.language.escape", - regex: "-" - }, { - token: "empty", - regex: "$", - next: "no_regex" - }, { - defaultToken: "string.regexp.charachterclass" - } - ], - "function_arguments": [ - { - token: "variable.parameter", - regex: identifierRe - }, { - token: "punctuation.operator", - regex: "[, ]+" - }, { - token: "punctuation.operator", - regex: "$" - }, { - token: "empty", - regex: "", - next: "no_regex" - } - ], - "qqstring": [ - { - token: "constant.language.escape", - regex: escapedRe - }, { - token: "string", - regex: "\\\\$", - consumeLineEnd: true - }, { - token: "string", - regex: '"|$', - next: "no_regex" - }, { - defaultToken: "string" - } - ], - "qstring": [ - { - token: "constant.language.escape", - regex: escapedRe - }, { - token: "string", - regex: "\\\\$", - consumeLineEnd: true - }, { - token: "string", - regex: "'|$", - next: "no_regex" - }, { - defaultToken: "string" - } - ] - }; - if (!options || !options.noES6) { - this.$rules.no_regex.unshift({ - regex: "[{}]", onMatch: function (val, state, stack) { - this.next = val == "{" ? this.nextState : ""; - if (val == "{" && stack.length) { - stack.unshift("start", state); - } - else if (val == "}" && stack.length) { - stack.shift(); - this.next = stack.shift(); - if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) - return "paren.quasi.end"; - } - return val == "{" ? "paren.lparen" : "paren.rparen"; - }, - nextState: "start" - }, { - token: "string.quasi.start", - regex: /`/, - push: [{ - token: "constant.language.escape", - regex: escapedRe - }, { - token: "paren.quasi.start", - regex: /\${/, - push: "start" - }, { - token: "string.quasi.end", - regex: /`/, - next: "pop" - }, { - defaultToken: "string.quasi" - }] - }); - if (!options || options.jsx != false) - JSX.call(this); - } - this.embedRules(DocCommentHighlightRules, "doc-", [DocCommentHighlightRules.getEndRule("no_regex")]); - this.normalizeRules(); -}; -oop.inherits(JavaScriptHighlightRules, TextHighlightRules); -function JSX() { - var tagRegex = identifierRe.replace("\\d", "\\d\\-"); - var jsxTag = { - onMatch: function (val, state, stack) { - var offset = val.charAt(1) == "/" ? 2 : 1; - if (offset == 1) { - if (state != this.nextState) - stack.unshift(this.next, this.nextState, 0); - else - stack.unshift(this.next); - stack[2]++; - } - else if (offset == 2) { - if (state == this.nextState) { - stack[1]--; - if (!stack[1] || stack[1] < 0) { - stack.shift(); - stack.shift(); - } - } - } - return [{ - type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", - value: val.slice(0, offset) - }, { - type: "meta.tag.tag-name.xml", - value: val.substr(offset) - }]; - }, - regex: "", - onMatch: function (value, currentState, stack) { - if (currentState == stack[0]) - stack.shift(); - if (value.length == 2) { - if (stack[0] == this.nextState) - stack[1]--; - if (!stack[1] || stack[1] < 0) { - stack.splice(0, 2); - } - } - this.next = stack[0] || "start"; - return [{ type: this.token, value: value }]; - }, - nextState: "jsx" - }, - jsxJsRule, - comments("jsxAttributes"), - { - token: "entity.other.attribute-name.xml", - regex: tagRegex - }, { - token: "keyword.operator.attribute-equals.xml", - regex: "=" - }, { - token: "text.tag-whitespace.xml", - regex: "\\s+" - }, { - token: "string.attribute-value.xml", - regex: "'", - stateName: "jsx_attr_q", - push: [ - { token: "string.attribute-value.xml", regex: "'", next: "pop" }, - { include: "reference" }, - { defaultToken: "string.attribute-value.xml" } - ] - }, { - token: "string.attribute-value.xml", - regex: '"', - stateName: "jsx_attr_qq", - push: [ - { token: "string.attribute-value.xml", regex: '"', next: "pop" }, - { include: "reference" }, - { defaultToken: "string.attribute-value.xml" } - ] - }, - jsxTag - ]; - this.$rules.reference = [{ - token: "constant.language.escape.reference.xml", - regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" - }]; -} -function comments(next) { - return [ - { - token: "comment", - regex: /\/\*/, - next: [ - DocCommentHighlightRules.getTagRule(), - { token: "comment", regex: "\\*\\/", next: next || "pop" }, - { defaultToken: "comment", caseInsensitive: true } - ] - }, { - token: "comment", - regex: "\\/\\/", - next: [ - DocCommentHighlightRules.getTagRule(), - { token: "comment", regex: "$|^", next: next || "pop" }, - { defaultToken: "comment", caseInsensitive: true } - ] - } - ]; -} -exports.JavaScriptHighlightRules = JavaScriptHighlightRules; - -}); - -ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module){"use strict"; -var Range = require("../range").Range; -var MatchingBraceOutdent = function () { }; -(function () { - this.checkOutdent = function (line, input) { - if (!/^\s+$/.test(line)) - return false; - return /^\s*\}/.test(input); - }; - this.autoOutdent = function (doc, row) { - var line = doc.getLine(row); - var match = line.match(/^(\s*\})/); - if (!match) - return 0; - var column = match[1].length; - var openBracePos = doc.findMatchingBracket({ row: row, column: column }); - if (!openBracePos || openBracePos.row == row) - return 0; - var indent = this.$getIndent(doc.getLine(openBracePos.row)); - doc.replace(new Range(row, 0, row, column - 1), indent); - }; - this.$getIndent = function (line) { - return line.match(/^\s*/)[0]; - }; -}).call(MatchingBraceOutdent.prototype); -exports.MatchingBraceOutdent = MatchingBraceOutdent; - -}); - -ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module){"use strict"; -var oop = require("../../lib/oop"); -var Range = require("../../range").Range; -var BaseFoldMode = require("./fold_mode").FoldMode; -var FoldMode = exports.FoldMode = function (commentRegex) { - if (commentRegex) { - this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)); - this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)); - } -}; -oop.inherits(FoldMode, BaseFoldMode); -(function () { - this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/; - this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/; - this.singleLineBlockCommentRe = /^\s*(\/\*).*\*\/\s*$/; - this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; - this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; - this._getFoldWidgetBase = this.getFoldWidget; - this.getFoldWidget = function (session, foldStyle, row) { - var line = session.getLine(row); - if (this.singleLineBlockCommentRe.test(line)) { - if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) - return ""; - } - var fw = this._getFoldWidgetBase(session, foldStyle, row); - if (!fw && this.startRegionRe.test(line)) - return "start"; // lineCommentRegionStart - return fw; - }; - this.getFoldWidgetRange = function (session, foldStyle, row, forceMultiline) { - var line = session.getLine(row); - if (this.startRegionRe.test(line)) - return this.getCommentRegionBlock(session, line, row); - var match = line.match(this.foldingStartMarker); - if (match) { - var i = match.index; - if (match[1]) - return this.openingBracketBlock(session, match[1], row, i); - var range = session.getCommentFoldRange(row, i + match[0].length, 1); - if (range && !range.isMultiLine()) { - if (forceMultiline) { - range = this.getSectionRange(session, row); - } - else if (foldStyle != "all") - range = null; - } - return range; - } - if (foldStyle === "markbegin") - return; - var match = line.match(this.foldingStopMarker); - if (match) { - var i = match.index + match[0].length; - if (match[1]) - return this.closingBracketBlock(session, match[1], row, i); - return session.getCommentFoldRange(row, i, -1); - } - }; - this.getSectionRange = function (session, row) { - var line = session.getLine(row); - var startIndent = line.search(/\S/); - var startRow = row; - var startColumn = line.length; - row = row + 1; - var endRow = row; - var maxRow = session.getLength(); - while (++row < maxRow) { - line = session.getLine(row); - var indent = line.search(/\S/); - if (indent === -1) - continue; - if (startIndent > indent) - break; - var subRange = this.getFoldWidgetRange(session, "all", row); - if (subRange) { - if (subRange.start.row <= startRow) { - break; - } - else if (subRange.isMultiLine()) { - row = subRange.end.row; - } - else if (startIndent == indent) { - break; - } - } - endRow = row; - } - return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); - }; - this.getCommentRegionBlock = function (session, line, row) { - var startColumn = line.search(/\s*$/); - var maxRow = session.getLength(); - var startRow = row; - var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; - var depth = 1; - while (++row < maxRow) { - line = session.getLine(row); - var m = re.exec(line); - if (!m) - continue; - if (m[1]) - depth--; - else - depth++; - if (!depth) - break; - } - var endRow = row; - if (endRow > startRow) { - return new Range(startRow, startColumn, endRow, line.length); - } - }; -}).call(FoldMode.prototype); - -}); - -ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module){"use strict"; -var oop = require("../lib/oop"); -var TextMode = require("./text").Mode; -var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; -var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; -var WorkerClient = require("../worker/worker_client").WorkerClient; -var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; -var CStyleFoldMode = require("./folding/cstyle").FoldMode; -var Mode = function () { - this.HighlightRules = JavaScriptHighlightRules; - this.$outdent = new MatchingBraceOutdent(); - this.$behaviour = new CstyleBehaviour(); - this.foldingRules = new CStyleFoldMode(); -}; -oop.inherits(Mode, TextMode); -(function () { - this.lineCommentStart = "//"; - this.blockComment = { start: "/*", end: "*/" }; - this.$quotes = { '"': '"', "'": "'", "`": "`" }; - this.getNextLineIndent = function (state, line, tab) { - var indent = this.$getIndent(line); - var tokenizedLine = this.getTokenizer().getLineTokens(line, state); - var tokens = tokenizedLine.tokens; - var endState = tokenizedLine.state; - if (tokens.length && tokens[tokens.length - 1].type == "comment") { - return indent; - } - if (state == "start" || state == "no_regex") { - var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); - if (match) { - indent += tab; - } - } - else if (state == "doc-start") { - if (endState == "start" || endState == "no_regex") { - return ""; - } - var match = line.match(/^\s*(\/?)\*/); - if (match) { - if (match[1]) { - indent += " "; - } - indent += "* "; - } - } - return indent; - }; - this.checkOutdent = function (state, line, input) { - return this.$outdent.checkOutdent(line, input); - }; - this.autoOutdent = function (state, doc, row) { - this.$outdent.autoOutdent(doc, row); - }; - this.createWorker = function (session) { - var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); - worker.attachToDocument(session.getDocument()); - worker.on("annotate", function (results) { - session.setAnnotations(results.data); - }); - worker.on("terminate", function () { - session.clearAnnotations(); - }); - return worker; - }; - this.$id = "ace/mode/javascript"; - this.snippetFileId = "ace/snippets/javascript"; -}).call(Mode.prototype); -exports.Mode = Mode; - -}); (function() { - ace.require(["ace/mode/javascript"], function(m) { - if (typeof module == "object" && typeof exports == "object" && module) { - module.exports = m; - } - }); - })(); - \ No newline at end of file diff --git a/GameDev/bin/Release/editor/ace/mode-json.js b/GameDev/bin/Release/editor/ace/mode-json.js deleted file mode 100644 index 1585dea2..00000000 --- a/GameDev/bin/Release/editor/ace/mode-json.js +++ /dev/null @@ -1,276 +0,0 @@ -ace.define("ace/mode/json_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module){"use strict"; -var oop = require("../lib/oop"); -var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; -var JsonHighlightRules = function () { - this.$rules = { - "start": [ - { - token: "variable", - regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]\\s*(?=:)' - }, { - token: "string", - regex: '"', - next: "string" - }, { - token: "constant.numeric", - regex: "0[xX][0-9a-fA-F]+\\b" - }, { - token: "constant.numeric", - regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token: "constant.language.boolean", - regex: "(?:true|false)\\b" - }, { - token: "text", - regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" - }, { - token: "comment", - regex: "\\/\\/.*$" - }, { - token: "comment.start", - regex: "\\/\\*", - next: "comment" - }, { - token: "paren.lparen", - regex: "[[({]" - }, { - token: "paren.rparen", - regex: "[\\])}]" - }, { - token: "punctuation.operator", - regex: /[,]/ - }, { - token: "text", - regex: "\\s+" - } - ], - "string": [ - { - token: "constant.language.escape", - regex: /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|["\\\/bfnrt])/ - }, { - token: "string", - regex: '"|$', - next: "start" - }, { - defaultToken: "string" - } - ], - "comment": [ - { - token: "comment.end", - regex: "\\*\\/", - next: "start" - }, { - defaultToken: "comment" - } - ] - }; -}; -oop.inherits(JsonHighlightRules, TextHighlightRules); -exports.JsonHighlightRules = JsonHighlightRules; - -}); - -ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module){"use strict"; -var Range = require("../range").Range; -var MatchingBraceOutdent = function () { }; -(function () { - this.checkOutdent = function (line, input) { - if (!/^\s+$/.test(line)) - return false; - return /^\s*\}/.test(input); - }; - this.autoOutdent = function (doc, row) { - var line = doc.getLine(row); - var match = line.match(/^(\s*\})/); - if (!match) - return 0; - var column = match[1].length; - var openBracePos = doc.findMatchingBracket({ row: row, column: column }); - if (!openBracePos || openBracePos.row == row) - return 0; - var indent = this.$getIndent(doc.getLine(openBracePos.row)); - doc.replace(new Range(row, 0, row, column - 1), indent); - }; - this.$getIndent = function (line) { - return line.match(/^\s*/)[0]; - }; -}).call(MatchingBraceOutdent.prototype); -exports.MatchingBraceOutdent = MatchingBraceOutdent; - -}); - -ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module){"use strict"; -var oop = require("../../lib/oop"); -var Range = require("../../range").Range; -var BaseFoldMode = require("./fold_mode").FoldMode; -var FoldMode = exports.FoldMode = function (commentRegex) { - if (commentRegex) { - this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)); - this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)); - } -}; -oop.inherits(FoldMode, BaseFoldMode); -(function () { - this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/; - this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/; - this.singleLineBlockCommentRe = /^\s*(\/\*).*\*\/\s*$/; - this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; - this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; - this._getFoldWidgetBase = this.getFoldWidget; - this.getFoldWidget = function (session, foldStyle, row) { - var line = session.getLine(row); - if (this.singleLineBlockCommentRe.test(line)) { - if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) - return ""; - } - var fw = this._getFoldWidgetBase(session, foldStyle, row); - if (!fw && this.startRegionRe.test(line)) - return "start"; // lineCommentRegionStart - return fw; - }; - this.getFoldWidgetRange = function (session, foldStyle, row, forceMultiline) { - var line = session.getLine(row); - if (this.startRegionRe.test(line)) - return this.getCommentRegionBlock(session, line, row); - var match = line.match(this.foldingStartMarker); - if (match) { - var i = match.index; - if (match[1]) - return this.openingBracketBlock(session, match[1], row, i); - var range = session.getCommentFoldRange(row, i + match[0].length, 1); - if (range && !range.isMultiLine()) { - if (forceMultiline) { - range = this.getSectionRange(session, row); - } - else if (foldStyle != "all") - range = null; - } - return range; - } - if (foldStyle === "markbegin") - return; - var match = line.match(this.foldingStopMarker); - if (match) { - var i = match.index + match[0].length; - if (match[1]) - return this.closingBracketBlock(session, match[1], row, i); - return session.getCommentFoldRange(row, i, -1); - } - }; - this.getSectionRange = function (session, row) { - var line = session.getLine(row); - var startIndent = line.search(/\S/); - var startRow = row; - var startColumn = line.length; - row = row + 1; - var endRow = row; - var maxRow = session.getLength(); - while (++row < maxRow) { - line = session.getLine(row); - var indent = line.search(/\S/); - if (indent === -1) - continue; - if (startIndent > indent) - break; - var subRange = this.getFoldWidgetRange(session, "all", row); - if (subRange) { - if (subRange.start.row <= startRow) { - break; - } - else if (subRange.isMultiLine()) { - row = subRange.end.row; - } - else if (startIndent == indent) { - break; - } - } - endRow = row; - } - return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); - }; - this.getCommentRegionBlock = function (session, line, row) { - var startColumn = line.search(/\s*$/); - var maxRow = session.getLength(); - var startRow = row; - var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; - var depth = 1; - while (++row < maxRow) { - line = session.getLine(row); - var m = re.exec(line); - if (!m) - continue; - if (m[1]) - depth--; - else - depth++; - if (!depth) - break; - } - var endRow = row; - if (endRow > startRow) { - return new Range(startRow, startColumn, endRow, line.length); - } - }; -}).call(FoldMode.prototype); - -}); - -ace.define("ace/mode/json",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/json_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/worker/worker_client"], function(require, exports, module){"use strict"; -var oop = require("../lib/oop"); -var TextMode = require("./text").Mode; -var HighlightRules = require("./json_highlight_rules").JsonHighlightRules; -var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; -var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; -var CStyleFoldMode = require("./folding/cstyle").FoldMode; -var WorkerClient = require("../worker/worker_client").WorkerClient; -var Mode = function () { - this.HighlightRules = HighlightRules; - this.$outdent = new MatchingBraceOutdent(); - this.$behaviour = new CstyleBehaviour(); - this.foldingRules = new CStyleFoldMode(); -}; -oop.inherits(Mode, TextMode); -(function () { - this.lineCommentStart = "//"; - this.blockComment = { start: "/*", end: "*/" }; - this.getNextLineIndent = function (state, line, tab) { - var indent = this.$getIndent(line); - if (state == "start") { - var match = line.match(/^.*[\{\(\[]\s*$/); - if (match) { - indent += tab; - } - } - return indent; - }; - this.checkOutdent = function (state, line, input) { - return this.$outdent.checkOutdent(line, input); - }; - this.autoOutdent = function (state, doc, row) { - this.$outdent.autoOutdent(doc, row); - }; - this.createWorker = function (session) { - var worker = new WorkerClient(["ace"], "ace/mode/json_worker", "JsonWorker"); - worker.attachToDocument(session.getDocument()); - worker.on("annotate", function (e) { - session.setAnnotations(e.data); - }); - worker.on("terminate", function () { - session.clearAnnotations(); - }); - return worker; - }; - this.$id = "ace/mode/json"; -}).call(Mode.prototype); -exports.Mode = Mode; - -}); (function() { - ace.require(["ace/mode/json"], function(m) { - if (typeof module == "object" && typeof exports == "object" && module) { - module.exports = m; - } - }); - })(); - \ No newline at end of file diff --git a/GameDev/bin/Release/editor/ace/mode-xml.js b/GameDev/bin/Release/editor/ace/mode-xml.js deleted file mode 100644 index e5521d3c..00000000 --- a/GameDev/bin/Release/editor/ace/mode-xml.js +++ /dev/null @@ -1,469 +0,0 @@ -ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module){"use strict"; -var oop = require("../lib/oop"); -var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; -var XmlHighlightRules = function (normalize) { - var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; - this.$rules = { - start: [ - { token: "string.cdata.xml", regex: "<\\!\\[CDATA\\[", next: "cdata" }, - { - token: ["punctuation.instruction.xml", "keyword.instruction.xml"], - regex: "(<\\?)(" + tagRegex + ")", next: "processing_instruction" - }, - { token: "comment.start.xml", regex: "<\\!--", next: "comment" }, - { - token: ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], - regex: "(<\\!)(DOCTYPE)(?=[\\s])", next: "doctype", caseInsensitive: true - }, - { include: "tag" }, - { token: "text.end-tag-open.xml", regex: "", - next: "start" - }], - doctype: [ - { include: "whitespace" }, - { include: "string" }, - { token: "xml-pe.doctype.xml", regex: ">", next: "start" }, - { token: "xml-pe.xml", regex: "[-_a-zA-Z0-9:]+" }, - { token: "punctuation.int-subset", regex: "\\[", push: "int_subset" } - ], - int_subset: [{ - token: "text.xml", - regex: "\\s+" - }, { - token: "punctuation.int-subset.xml", - regex: "]", - next: "pop" - }, { - token: ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], - regex: "(<\\!)(" + tagRegex + ")", - push: [{ - token: "text", - regex: "\\s+" - }, - { - token: "punctuation.markup-decl.xml", - regex: ">", - next: "pop" - }, - { include: "string" }] - }], - cdata: [ - { token: "string.cdata.xml", regex: "\\]\\]>", next: "start" }, - { token: "text.xml", regex: "\\s+" }, - { token: "text.xml", regex: "(?:[^\\]]|\\](?!\\]>))+" } - ], - comment: [ - { token: "comment.end.xml", regex: "-->", next: "start" }, - { defaultToken: "comment.xml" } - ], - reference: [{ - token: "constant.language.escape.reference.xml", - regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" - }], - attr_reference: [{ - token: "constant.language.escape.reference.attribute-value.xml", - regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" - }], - tag: [{ - token: ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], - regex: "(?:(<)|(", next: "start" } - ] - }], - tag_whitespace: [ - { token: "text.tag-whitespace.xml", regex: "\\s+" } - ], - whitespace: [ - { token: "text.whitespace.xml", regex: "\\s+" } - ], - string: [{ - token: "string.xml", - regex: "'", - push: [ - { token: "string.xml", regex: "'", next: "pop" }, - { defaultToken: "string.xml" } - ] - }, { - token: "string.xml", - regex: '"', - push: [ - { token: "string.xml", regex: '"', next: "pop" }, - { defaultToken: "string.xml" } - ] - }], - attributes: [{ - token: "entity.other.attribute-name.xml", - regex: tagRegex - }, { - token: "keyword.operator.attribute-equals.xml", - regex: "=" - }, { - include: "tag_whitespace" - }, { - include: "attribute_value" - }], - attribute_value: [{ - token: "string.attribute-value.xml", - regex: "'", - push: [ - { token: "string.attribute-value.xml", regex: "'", next: "pop" }, - { include: "attr_reference" }, - { defaultToken: "string.attribute-value.xml" } - ] - }, { - token: "string.attribute-value.xml", - regex: '"', - push: [ - { token: "string.attribute-value.xml", regex: '"', next: "pop" }, - { include: "attr_reference" }, - { defaultToken: "string.attribute-value.xml" } - ] - }] - }; - if (this.constructor === XmlHighlightRules) - this.normalizeRules(); -}; -(function () { - this.embedTagRules = function (HighlightRules, prefix, tag) { - this.$rules.tag.unshift({ - token: ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], - regex: "(<)(" + tag + "(?=\\s|>|$))", - next: [ - { include: "attributes" }, - { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: prefix + "start" } - ] - }); - this.$rules[tag + "-end"] = [ - { include: "attributes" }, - { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: "start", - onMatch: function (value, currentState, stack) { - stack.splice(0); - return this.token; - } } - ]; - this.embedRules(HighlightRules, prefix, [{ - token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], - regex: "(|$))", - next: tag + "-end" - }, { - token: "string.cdata.xml", - regex: "<\\!\\[CDATA\\[" - }, { - token: "string.cdata.xml", - regex: "\\]\\]>" - }]); - }; -}).call(TextHighlightRules.prototype); -oop.inherits(XmlHighlightRules, TextHighlightRules); -exports.XmlHighlightRules = XmlHighlightRules; - -}); - -ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module){"use strict"; -var oop = require("../../lib/oop"); -var Behaviour = require("../behaviour").Behaviour; -var TokenIterator = require("../../token_iterator").TokenIterator; -var lang = require("../../lib/lang"); -function is(token, type) { - return token && token.type.lastIndexOf(type + ".xml") > -1; -} -var XmlBehaviour = function () { - this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"' || text == "'") { - var quote = text; - var selected = session.doc.getTextRange(editor.getSelectionRange()); - if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { - return { - text: quote + selected + quote, - selection: false - }; - } - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - var rightChar = line.substring(cursor.column, cursor.column + 1); - var iterator = new TokenIterator(session, cursor.row, cursor.column); - var token = iterator.getCurrentToken(); - if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { - return { - text: "", - selection: [1, 1] - }; - } - if (!token) - token = iterator.stepBackward(); - if (!token) - return; - while (is(token, "tag-whitespace") || is(token, "whitespace")) { - token = iterator.stepBackward(); - } - var rightSpace = !rightChar || rightChar.match(/\s/); - if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { - return { - text: quote + quote, - selection: [1, 1] - }; - } - } - }); - this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { - var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && (selected == '"' || selected == "'")) { - var line = session.doc.getLine(range.start.row); - var rightChar = line.substring(range.start.column + 1, range.start.column + 2); - if (rightChar == selected) { - range.end.column++; - return range; - } - } - }); - this.add("autoclosing", "insertion", function (state, action, editor, session, text) { - if (text == '>') { - var position = editor.getSelectionRange().start; - var iterator = new TokenIterator(session, position.row, position.column); - var token = iterator.getCurrentToken() || iterator.stepBackward(); - if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) - return; - if (is(token, "reference.attribute-value")) - return; - if (is(token, "attribute-value")) { - var tokenEndColumn = iterator.getCurrentTokenColumn() + token.value.length; - if (position.column < tokenEndColumn) - return; - if (position.column == tokenEndColumn) { - var nextToken = iterator.stepForward(); - if (nextToken && is(nextToken, "attribute-value")) - return; - iterator.stepBackward(); - } - } - if (/^\s*>/.test(session.getLine(position.row).slice(position.column))) - return; - while (!is(token, "tag-name")) { - token = iterator.stepBackward(); - if (token.value == "<") { - token = iterator.stepForward(); - break; - } - } - var tokenRow = iterator.getCurrentTokenRow(); - var tokenColumn = iterator.getCurrentTokenColumn(); - if (is(iterator.stepBackward(), "end-tag-open")) - return; - var element = token.value; - if (tokenRow == position.row) - element = element.substring(0, position.column - tokenColumn); - if (this.voidElements.hasOwnProperty(element.toLowerCase())) - return; - return { - text: ">" + "", - selection: [1, 1] - }; - } - }); - this.add("autoindent", "insertion", function (state, action, editor, session, text) { - if (text == "\n") { - var cursor = editor.getCursorPosition(); - var line = session.getLine(cursor.row); - var iterator = new TokenIterator(session, cursor.row, cursor.column); - var token = iterator.getCurrentToken(); - if (token && token.type.indexOf("tag-close") !== -1) { - if (token.value == "/>") - return; - while (token && token.type.indexOf("tag-name") === -1) { - token = iterator.stepBackward(); - } - if (!token) { - return; - } - var tag = token.value; - var row = iterator.getCurrentTokenRow(); - token = iterator.stepBackward(); - if (!token || token.type.indexOf("end-tag") !== -1) { - return; - } - if (this.voidElements && !this.voidElements[tag]) { - var nextToken = session.getTokenAt(cursor.row, cursor.column + 1); - var line = session.getLine(row); - var nextIndent = this.$getIndent(line); - var indent = nextIndent + session.getTabString(); - if (nextToken && nextToken.value === " -1; -} -(function () { - this.getFoldWidget = function (session, foldStyle, row) { - var tag = this._getFirstTagInLine(session, row); - if (!tag) - return this.getCommentFoldWidget(session, row); - if (tag.closing || (!tag.tagName && tag.selfClosing)) - return foldStyle === "markbeginend" ? "end" : ""; - if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) - return ""; - if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) - return ""; - return "start"; - }; - this.getCommentFoldWidget = function (session, row) { - if (/comment/.test(session.getState(row)) && /'; - break; - } - } - return tag; - } - else if (is(token, "tag-close")) { - tag.selfClosing = token.value == '/>'; - return tag; - } - tag.start.column += token.value.length; - } - return null; - }; - this._findEndTagInLine = function (session, row, tagName, startColumn) { - var tokens = session.getTokens(row); - var column = 0; - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - column += token.value.length; - if (column < startColumn) - continue; - if (is(token, "end-tag-open")) { - token = tokens[i + 1]; - if (token && token.value == tagName) - return true; - } - } - return false; - }; - this.getFoldWidgetRange = function (session, foldStyle, row) { - var tags = session.getMatchingTags({ row: row, column: 0 }); - if (tags) { - return new Range(tags.openTag.end.row, tags.openTag.end.column, tags.closeTag.start.row, tags.closeTag.start.column); - } - else { - return this.getCommentFoldWidget(session, row) - && session.getCommentFoldRange(row, session.getLine(row).length); - } - }; -}).call(FoldMode.prototype); - -}); - -ace.define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(require, exports, module){"use strict"; -var oop = require("../lib/oop"); -var lang = require("../lib/lang"); -var TextMode = require("./text").Mode; -var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; -var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; -var XmlFoldMode = require("./folding/xml").FoldMode; -var WorkerClient = require("../worker/worker_client").WorkerClient; -var Mode = function () { - this.HighlightRules = XmlHighlightRules; - this.$behaviour = new XmlBehaviour(); - this.foldingRules = new XmlFoldMode(); -}; -oop.inherits(Mode, TextMode); -(function () { - this.voidElements = lang.arrayToMap([]); - this.blockComment = { start: "" }; - this.createWorker = function (session) { - var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker"); - worker.attachToDocument(session.getDocument()); - worker.on("error", function (e) { - session.setAnnotations(e.data); - }); - worker.on("terminate", function () { - session.clearAnnotations(); - }); - return worker; - }; - this.$id = "ace/mode/xml"; -}).call(Mode.prototype); -exports.Mode = Mode; - -}); (function() { - ace.require(["ace/mode/xml"], function(m) { - if (typeof module == "object" && typeof exports == "object" && module) { - module.exports = m; - } - }); - })(); - \ No newline at end of file diff --git a/GameDev/bin/Release/editor/ace/theme-dawn.js b/GameDev/bin/Release/editor/ace/theme-dawn.js deleted file mode 100644 index 923dad68..00000000 --- a/GameDev/bin/Release/editor/ace/theme-dawn.js +++ /dev/null @@ -1,115 +0,0 @@ -define("ace/theme/dawn",["require","exports","module","ace/lib/dom"], function(require, exports, module) { - -exports.isDark = false; -exports.cssClass = "ace-dawn"; -exports.cssText = ".ace-dawn .ace_gutter {\ -background: #ebebeb;\ -color: #333\ -}\ -.ace-dawn .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8\ -}\ -.ace-dawn {\ -background-color: #F9F9F9;\ -color: #080808\ -}\ -.ace-dawn .ace_cursor {\ -color: #000000\ -}\ -.ace-dawn .ace_marker-layer .ace_selection {\ -background: rgba(39, 95, 255, 0.30)\ -}\ -.ace-dawn.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #F9F9F9;\ -}\ -.ace-dawn .ace_marker-layer .ace_step {\ -background: rgb(255, 255, 0)\ -}\ -.ace-dawn .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgba(75, 75, 126, 0.50)\ -}\ -.ace-dawn .ace_marker-layer .ace_active-line {\ -background: rgba(36, 99, 180, 0.12)\ -}\ -.ace-dawn .ace_gutter-active-line {\ -background-color : #dcdcdc\ -}\ -.ace-dawn .ace_marker-layer .ace_selected-word {\ -border: 1px solid rgba(39, 95, 255, 0.30)\ -}\ -.ace-dawn .ace_invisible {\ -color: rgba(75, 75, 126, 0.50)\ -}\ -.ace-dawn .ace_keyword,\ -.ace-dawn .ace_meta {\ -color: #794938\ -}\ -.ace-dawn .ace_constant,\ -.ace-dawn .ace_constant.ace_character,\ -.ace-dawn .ace_constant.ace_character.ace_escape,\ -.ace-dawn .ace_constant.ace_other {\ -color: #811F24\ -}\ -.ace-dawn .ace_invalid.ace_illegal {\ -text-decoration: underline;\ -font-style: italic;\ -color: #F8F8F8;\ -background-color: #B52A1D\ -}\ -.ace-dawn .ace_invalid.ace_deprecated {\ -text-decoration: underline;\ -font-style: italic;\ -color: #B52A1D\ -}\ -.ace-dawn .ace_support {\ -color: #691C97\ -}\ -.ace-dawn .ace_support.ace_constant {\ -color: #B4371F\ -}\ -.ace-dawn .ace_fold {\ -background-color: #794938;\ -border-color: #080808\ -}\ -.ace-dawn .ace_list,\ -.ace-dawn .ace_markup.ace_list,\ -.ace-dawn .ace_support.ace_function {\ -color: #693A17\ -}\ -.ace-dawn .ace_storage {\ -font-style: italic;\ -color: #A71D5D\ -}\ -.ace-dawn .ace_string {\ -color: #0B6125\ -}\ -.ace-dawn .ace_string.ace_regexp {\ -color: #CF5628\ -}\ -.ace-dawn .ace_comment {\ -font-style: italic;\ -color: #5A525F\ -}\ -.ace-dawn .ace_heading,\ -.ace-dawn .ace_markup.ace_heading {\ -color: #19356D\ -}\ -.ace-dawn .ace_variable {\ -color: #234A97\ -}\ -.ace-dawn .ace_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYLh/5+x/AAizA4hxNNsZAAAAAElFTkSuQmCC) right repeat-y\ -}"; - -var dom = require("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass, false); -}); (function() { - window.require(["ace/theme/dawn"], function(m) { - if (typeof module == "object" && typeof exports == "object" && module) { - module.exports = m; - } - }); - })(); - \ No newline at end of file diff --git a/GameDev/bin/Release/editor/js_editor.html b/GameDev/bin/Release/editor/js_editor.html deleted file mode 100644 index be2fe67a..00000000 --- a/GameDev/bin/Release/editor/js_editor.html +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - GameDev - - -
   
-    
-      
-    
-
-    
-
-
diff --git a/GameDev/bin/Release/editor/json_editor.html b/GameDev/bin/Release/editor/json_editor.html
deleted file mode 100644
index 05b7088e..00000000
--- a/GameDev/bin/Release/editor/json_editor.html
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
-    
-        
-        
-               
-            
-        GameDev
-    
-    
-        
   
-    
-      
-    
-
-    
-
-
diff --git a/GameDev/bin/Release/editor/xml_editor.html b/GameDev/bin/Release/editor/xml_editor.html
deleted file mode 100644
index f1b82a31..00000000
--- a/GameDev/bin/Release/editor/xml_editor.html
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
-    
-        
-        
-               
-            
-        GameDev
-    
-    
-        
   
-    
-      
-    
-
-    
-
-
diff --git a/GameDev/bin/Release/help/Targets.jpg b/GameDev/bin/Release/help/Targets.jpg
deleted file mode 100644
index d2559ca2..00000000
Binary files a/GameDev/bin/Release/help/Targets.jpg and /dev/null differ
diff --git a/GameDev/bin/Release/help/UIAndroid.png b/GameDev/bin/Release/help/UIAndroid.png
deleted file mode 100644
index c8938a51..00000000
Binary files a/GameDev/bin/Release/help/UIAndroid.png and /dev/null differ
diff --git a/GameDev/bin/Release/help/UILayout.jpg b/GameDev/bin/Release/help/UILayout.jpg
deleted file mode 100644
index 8b46571f..00000000
Binary files a/GameDev/bin/Release/help/UILayout.jpg and /dev/null differ
diff --git a/GameDev/bin/Release/help/UIWin.jpg b/GameDev/bin/Release/help/UIWin.jpg
deleted file mode 100644
index 2d74df79..00000000
Binary files a/GameDev/bin/Release/help/UIWin.jpg and /dev/null differ
diff --git a/GameDev/bin/Release/help/ambient_light.jpg b/GameDev/bin/Release/help/ambient_light.jpg
deleted file mode 100644
index 8092b08d..00000000
Binary files a/GameDev/bin/Release/help/ambient_light.jpg and /dev/null differ
diff --git a/GameDev/bin/Release/help/api/AVCPlayer.html b/GameDev/bin/Release/help/api/AVCPlayer.html
deleted file mode 100644
index 87346674..00000000
--- a/GameDev/bin/Release/help/api/AVCPlayer.html
+++ /dev/null
@@ -1,1319 +0,0 @@
-
-
-
-  
-  
-  
-  
-  
-  
-  
-  
-  
-
-
-  

<--Home

-

class AVCPlayer

-

Play back a raw opus stream.

-

Can be used as an image source.

-

class AVCPlayer

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
AVCPlayer()Creates an AVC-player.
Properties
widthWidth of the image source.
heightHeight of the image source.
Methods
dispose()Dispose the unmanaged resource.
addPacket()Add an AVC packet to the play queue.
updateTexture()Add an AVC packet to the play queue.
-

Constructors

-

AVCPlayer()

-

AVCPlayer()

-

Creates an AVC-player.

-

Properties

-

width

-

.width: Number

-

Width of the image source.

-

Read-only.

-

height

-

.height: Number

-

Height of the image source.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

addPacket()

-

.addPacket(data: ArrayBuffer): undefined

-

Add an AVC packet to the play queue.

-

updateTexture()

-

.updateTexture(): undefined

-

Attempt to read new frames and update the texture data.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/AVCRecorder.html b/GameDev/bin/Release/help/api/AVCRecorder.html deleted file mode 100644 index 0767a0e3..00000000 --- a/GameDev/bin/Release/help/api/AVCRecorder.html +++ /dev/null @@ -1,1298 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class AVCRecorder

-

Record from a video device and encode as a raw AVC stream.

-

class AVCRecorder

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
AVCRecorder()Creates an AVC-recorder.
Properties
callbackCallback function for recieving AVC packets.
Methods
dispose()Dispose the unmanaged resource.
-

Constructors

-

AVCRecorder()

-

AVCRecorder(id_device: Number)

-

Creates an AVC-recorder.

-

Parameters

-

id_device : index of the camera device.

-

Properties

-

callback

-

.callback: Function - .callback(data: ArrayBuffer): undefined

-

Callback function for recieving AVC packets.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/AmbientLight.html b/GameDev/bin/Release/help/api/AmbientLight.html deleted file mode 100644 index 4785b737..00000000 --- a/GameDev/bin/Release/help/api/AmbientLight.html +++ /dev/null @@ -1,1314 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class AmbientLight

-

This light globally illuminates all objects in the scene equally.

-

This light cannot be used to cast shadows as it does not have a direction.

-

class AmbientLight extends IndirectLight

-

Inheritance IndirectLight --> AmbientLight

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
AmbientLight()Creates a new AmbientLight.
Properties
colorThe color of the ambient light.
intensityThe intensity of the ambient light.
Methods
getColorGet the value of .color
setColorSet the value of .color
-

Constructors

-

AmbientLight()

-

Creates a new AmbientLight.

-

Properties

-

color

-

.color: Object

-

The color of the ambient light.

-

Read-only. Use the method .setColor to modify this property.

-

intensity

-

.intensity: Number

-

The intensity of the ambient light.

-

Readable and writable.

-

Methods

-

getColor()

-

.getColor(color: Vector3) : Vector3

-

Copy the value of .color into color.

-

setColor()

-

.setColor(color: Vector3): undefined

-

Set the value of .color according to color.

-

.setColor(r: Number, g: Number, b: Number ): undefined

-

Set the value of .color according to the r, g, b values.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Android.png b/GameDev/bin/Release/help/api/Android.png deleted file mode 100644 index a135c162..00000000 Binary files a/GameDev/bin/Release/help/api/Android.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/AnimationMixer.html b/GameDev/bin/Release/help/api/AnimationMixer.html deleted file mode 100644 index c7ba9c6a..00000000 --- a/GameDev/bin/Release/help/api/AnimationMixer.html +++ /dev/null @@ -1,1432 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class AnimationMixer

-

Utility for linear blending of animation clips.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
AnimationMixer()Creates a new AnimationMixer.
Properties
animationslist of current added animation clips
currentPlayinglist of current playing animation clips
Methods
dispose()Dispose the unmanaged resource.
getAnimationGet an added animation clip by name.
getAnimationsGet all added animation clips.
addAnimationAdd an animation clip to the mixer.
addAnimationsAdd multiple animation clips to the mixer.
startAnimationStart an animation by name.
stopAnimationStop an animation by name.
setWeightsSet blending weigths for each animation currently being played.
getFrameGet the mixed animation frame of current time point.
-

Constructors

-

AnimationMixer()

-

AnimationMixer()

-

Creates a new AnimationMixer.

-

Properties

-

animations()

-

.animations: Array

-

Read-only property for displaying the info of added animation clips.

-

.currentPlaying: Array

-

Read-only property for displaying the info of currently playing animation clips.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

getAnimation()

-

.getAnimation(name: String): Object

-

Get an added animation clip by name.

-

The returned object has the following properties:

-

.name: String

-

Name of the animation clip.

-

.duration: Number

-

Duration of the animation clip in seconds.

-

.morphs: Array

-

Optional. Morph tracks.

-

.morphs[i].name: String

-

Name of the morphable mesh.

-

.morphs[i].targets: Number

-

Number of morph targets of the morphable mesh.

-

.morphs[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR" or "CUBICSPLINE"

-

.morphs[i].times: Float32Array

-

Time stamp of each frame.

-

.morphs[i].values: Float32Array

-

Weight values of each frame.

-

.translations: Array

-

Optional. Translation tracks.

-

.translations[i].name: String

-

Name of the targeted node.

-

.translations[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR" or "CUBICSPLINE"

-

.translations[i].times: Float32Array

-

Time stamp of each frame.

-

.translations[i].values: Float32Array

-

Translation values of each frame.

-

.rotations: Array

-

Optional. Rotation tracks.

-

.rotations[i].name: String

-

Name of the targeted node.

-

.rotations[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR"

-

.rotations[i].times: Float32Array

-

Time stamp of each frame.

-

.rotations[i].values: Float32Array

-

Rotation values of each frame.

-

.scales: Array

-

Optional. Scale tracks.

-

.scales[i].name: String

-

Name of the targeted node.

-

.scales[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR" or "CUBICSPLINE"

-

.scales[i].times: Float32Array

-

Time stamp of each frame.

-

.scales[i].values: Float32Array

-

Scale values of each frame.

-

getAnimations()

-

.getAnimations(): Array

-

Get all added animation clips.

-

Each element of the returned array has the same structure as the return value of .getAnimation().

-

addAnimation()

-

.addAnimation(animation: Object): undefined

-

Add an animation clip to the mixer.

-

The animation object should have the same structure as the return value of .getAnimation().

-

addAnimations()

-

.addAnimations(animations: Array): undefined

-

Add multiple animation clips to the mixer.

-

Each element of the array should have the same structure as the return value of .getAnimation().

-

startAnimation()

-

.startAnimation(name: String) : undefined

-

Start an animation by name.

-

stopAnimation()

-

.stopAnimation(name: String) : undefined

-

Stop an animation by name.

-

setWeights()

-

.setWeights(weights: Array) : undefined

-

Set blending weigths for each animation currently being played.

-

A weight of 0 will cause the corresponding animation clip being removed from the current playing list.

-

getFrame()

-

.getFrame() : Object

-

Get the mixed animation frame of current time point.

-

The returned frame object has the following properties:

-

frame.morphs: Array

-

Optional. Morph state for morphable meshes.

-

frame.morphs[i].name: String

-

Name of a morphable mesh.

-

frame.morphs[i].weights: Array

-

Weight for each morph target of the mesh.

-

frame.translations: Array

-

Optional. Translation states for nodes.

-

frame.translations[i].name: String

-

Name of the targeted node.

-

frame.translations[i].translation: Vector3

-

Translation state of the node.

-

frame.rotations: Array

-

Optional. Rotation states for nodes.

-

frame.rotations[i].name: String

-

Name of the targeted node.

-

frame.rotations[i].rotation: Quaternion

-

Rotation state of the node.

-

frame.scales: Array

-

Optional. Scale states for nodes.

-

frame.scales[i].name: String

-

Name of the targeted node.

-

frame.translations[i].scale: Vector3

-

Scale state of the node.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Background.html b/GameDev/bin/Release/help/api/Background.html deleted file mode 100644 index 756d72a0..00000000 --- a/GameDev/bin/Release/help/api/Background.html +++ /dev/null @@ -1,1271 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Background

-

Abstract class for all backgrounds

-

No contructor, never used directly.

- - - - - - - - - - - - - - - -
NameDescription
Methods
dispose()Dispose the unmanaged resource.
-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/BackgroundScene.html b/GameDev/bin/Release/help/api/BackgroundScene.html deleted file mode 100644 index af468181..00000000 --- a/GameDev/bin/Release/help/api/BackgroundScene.html +++ /dev/null @@ -1,1303 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class BackgroundScene

-

Use another scene as background.

-

class BackgroundScene extends Background

-

Inheritance Background --> BackgroundScene

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
BackgroundScene()Creates a new BackgroundScene.
Properties
sceneReference to the scene.
nearnear clipping distance for rendering the background
farfar clipping distance for rendering the background
-

Constructors

-

BackgroundScene()

-

BackgroundScene(scene: Scene, near: Number, far: Number)

-

Creates a new BackgroundScene.

-

Parameters

-

scene: reference to the scene used as background.

-

near: near clipping distance for rendering the background. Default value 10.0.

-

far: far clipping distance for rendering the background. Default value 10000.0.

-

Properties

-

scene

-

.scene: Scene

-

Reference to the scene.

-

Readable & writable.

-

near

-

.near: Number

-

Near clipping distance for rendering the background

-

far

-

.far: Number

-

Far clipping distance for rendering the background

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/BoundingVolumeHierarchy.html b/GameDev/bin/Release/help/api/BoundingVolumeHierarchy.html deleted file mode 100644 index a7bea76e..00000000 --- a/GameDev/bin/Release/help/api/BoundingVolumeHierarchy.html +++ /dev/null @@ -1,1319 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class BoundingVolumeHierarchy

-

Acceleration structure for ray-casting.

-

class BoundingVolumeHierarchy

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
BoundingVolumeHierarchy()Creates a new BoundingVolumeHierarchy.
Methods
disposeDispose the unmanaged resource.
updateUpdate the BVH with a new model.
removeRemove a model from the BVH.
intersectIntersect the given ray with the acceleration structure.
-

Constructors

-

BoundingVolumeHierarchy()

-

BoundingVolumeHierarchy(objects: Array)

-

Create a BoundingVolumeHierarchy from a list of Object3D objects.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

update()

-

.update(obj: Object3D): undefined

-

Update the BVH with a new model.

-

remove()

-

.remove(obj: Object3D): undefined

-

Remove a model from the BVH.

-

intersect()

-

.intersect(ray: Object): Object

-

Intersect the given ray with the acceleration structure.

-

The input ray object should have the following properties:

-

ray.origin: Vector3

-

Origin of the ray.

-

ray.direction: Vector3

-

Direction of the ray.

-

ray.near: Number

-

Optional. Nearest distance of search.

-

ray.far: Number

-

Optional. Furthest distance of search.

-

The returned object has the following properties:

-

.name: String

-

Name of the first intersected object.

-

.distance: Number

-

Distance of the first intersection point.

-

At the event of missing intersection, it will return null;

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Camera.html b/GameDev/bin/Release/help/api/Camera.html deleted file mode 100644 index 61ae038b..00000000 --- a/GameDev/bin/Release/help/api/Camera.html +++ /dev/null @@ -1,1329 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Camera

-

Base class for cameras.

-

class Camera extends Object3D

-

Inheritance Object3D --> Camera

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
Camera()Creates a new Camera.
Properties
matrixWorldInverseInverse of .matrixWorld
projectionMatrixMatrix which contains the projection.
projectionMatrixInverseThe inverse of .projectionMatrix
Methods
getMatrixWorldInverseGet the value of .matrixWorldInverse
getProjectionMatrixGet the value of .projectionMatrix
getProjectionMatrixInverseGet the value of .projectionMatrixInverse
-

Constructors

-

Camera()

-

Camera()

-

Creates a new Camera. Note that this class is not intended to be created directly.

-

Properties

-

See the base Object3D class for common properties.

-

matrixWorldInverse

-

.matrixWorldInverse: Object

-

This is the inverse of .matrixWorld. .matrixWorld contains the Matrix which has the world transform of the Camera.

-

Read-only.

-

projectionMatrix

-

.projectionMatrix: Object

-

This is the matrix which contains the projection.

-

Read-only.

-

projectionMatrixInverse

-

.projectionMatrixInverse: Object

-

The inverse of .projectionMatrix.

-

Read-only.

-

Methods

-

See the base Object3D class for common methods.

-

getMatrixWorldInverse()

-

.getMatrixWorldInverse(matrix: Matrix4) : Matrix4

-

Copy the value of .matrixWorldInverse into matrix.

-

getProjectionMatrix()

-

.getProjectionMatrix(matrix: Matrix4) : Matrix4

-

Copy the value of .projectionMatrix into matrix.

-

getProjectionMatrixInverse()

-

.getProjectionMatrixInverse(matrix: Matrix4) : Matrix4

-

Copy the value of .projectionMatrixInverse into matrix.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/ColorBackground.html b/GameDev/bin/Release/help/api/ColorBackground.html deleted file mode 100644 index 7b00b5ee..00000000 --- a/GameDev/bin/Release/help/api/ColorBackground.html +++ /dev/null @@ -1,1306 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class ColorBackground

-

A background that has a monotone color.

-

class ColorBackground extends Background

-

Inheritance Background --> ColorBackground

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
ColorBackground()Creates a new ColorBackground.
Properties
colorColor of the background.
Methods
getColorGet the value of .color
setColorSet the value of .color
-

Constructors

-

ColorBackground()

-

ColorBackground()

-

Creates a new ColorBackground.

-

Properties

-

color

-

.color: Object

-

The color of the background.

-

Read-only. Use the method .setColor to modify this property.

-

Methods

-

getColor()

-

.getColor(color: Vector3) : Vector3

-

Copy the value of .color into color.

-

setColor()

-

.setColor(color: Vector3): undefined

-

Set the value of .color according to color.

-

.setColor(r: Number, g: Number, b: Number ): undefined

-

Set the value of .color according to the r, g, b values.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/CubeBackground.html b/GameDev/bin/Release/help/api/CubeBackground.html deleted file mode 100644 index 4ea1177a..00000000 --- a/GameDev/bin/Release/help/api/CubeBackground.html +++ /dev/null @@ -1,1284 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class CubeBackground

-

A background using a CubeMap.

-

class CubeBackground extends Background

-

Inheritance Background --> CubeBackground

- - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
CubeBackground()Creates a new CubeBackground.
Methods
setCubemapSet the cube-map data.
-

Constructors

-

CubeBackground()

-

CubeBackground()

-

Creates a new CubeBackground.

-

Methods

-

setCubemap()

-

.setCubemap(cubeMap: CubeImage): undefined

-

Set the cube-map data.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/CubeImage.html b/GameDev/bin/Release/help/api/CubeImage.html deleted file mode 100644 index 8ccea216..00000000 --- a/GameDev/bin/Release/help/api/CubeImage.html +++ /dev/null @@ -1,1306 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class CubeImage

-

Class that represents a cubemap image that resides in CPU memory.

-

A CubeImage contains 6 images.

-

Usually not created directly. Use ImageLoader class to create a cubemap image.

-

class CubeImage

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
CubeImage()Creates a cube image.
Properties
widthWidth of the image.
heightHeight of the image.
Methods
dispose()Dispose the unmanaged resource.
-

Constructors

-

CubeImage()

-

CubeImage()

-

Note that this constructor is not intended to be called directly.

-

Properties

-

width

-

.width: Number

-

Width of the image.

-

Read-only.

-

height

-

.height: Number

-

Height of the image.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/CubeRenderTarget.html b/GameDev/bin/Release/help/api/CubeRenderTarget.html deleted file mode 100644 index 6dce3a04..00000000 --- a/GameDev/bin/Release/help/api/CubeRenderTarget.html +++ /dev/null @@ -1,1287 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class CubeRenderTarget

-

A cubemap render target.

-

Can be used in GLRenderer.renderCube().

-

class CubeRenderTarget

- - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
CubeRenderTarget()Creates a new CubeRenderTarget.
Methods
disposeDispose the unmanaged resource.
-

Constructors

-

CubeRenderTarget()

-

CubeRenderTarget(width: Number, height: Number)

-

Create a new CubeRenderTarget.

-

Parameters

-

width: width of the image data

-

height: height of the image data

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/DDSImage.html b/GameDev/bin/Release/help/api/DDSImage.html deleted file mode 100644 index d50aeb28..00000000 --- a/GameDev/bin/Release/help/api/DDSImage.html +++ /dev/null @@ -1,1316 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class DDSImage

-

Class that represents an image loaded from a DDS file that resides in CPU memory.

-

Usually not created directly. Use DDSImageLoader class to create a dds-image.

-

Note that the implementation is incomplete. Supported formats include:

-
BGRA,
-BC1,
-BC2,
-BC3,
-BC4,
-BC5,
-BC6H,
-BC7,
-

Faces and mipmaps are not implemented.

-

Currently this class is mainly used as an option for loading lightmaps stored in BC6H.

-

class DDSImage

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
DDSImage()Creates a dds-image.
Properties
widthWidth of the dds-image.
heightHeight of the dds-image.
Methods
dispose()Dispose the unmanaged resource.
-

Constructors

-

DDSImage()

-

DDSImage()

-

Creates an empty dds-image.

-

Properties

-

width

-

.width: Number

-

Width of the image.

-

Read-only.

-

height

-

.height: Number

-

Height of the image.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/DDSImageLoader.html b/GameDev/bin/Release/help/api/DDSImageLoader.html deleted file mode 100644 index eab987ca..00000000 --- a/GameDev/bin/Release/help/api/DDSImageLoader.html +++ /dev/null @@ -1,1290 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class DDSImageLoader

-

Provides a few interfaces to load dds-images from local files or from memory.

-

No constructor, exposed as a global object DDSImageLoader.

-

Note that the implementation is incomplete. Supported formats include:

-
BGRA,
-BC1,
-BC2,
-BC3,
-BC4,
-BC5,
-BC6H,
-BC7,
-

Faces and mipmaps are not implemented.

-

Currently this class is mainly used as an option for loading lightmaps stored in BC6H.

-

class DDSImageLoader

- - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
loadFile()Load a dds-image from local file.
loadMemory()Load a dds-image from a memory buffer.
-

Methods

-

loadFile()

-

.loadFile(name: String): DDSImage

-

Load a dds-image from local file.

-

loadMemory()

-

.loadMemory(buf: ArrayBuffer): DDSImage

-

Load a dds-image from a memory buffer.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/DirectionalLight.html b/GameDev/bin/Release/help/api/DirectionalLight.html deleted file mode 100644 index 5484a82a..00000000 --- a/GameDev/bin/Release/help/api/DirectionalLight.html +++ /dev/null @@ -1,1347 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class DirectionalLight

-

A light that gets emitted in a specific direction. This light will behave as though it is infinitely far away and the rays produced from it are all parallel. The common use case for this is to simulate daylight; the sun is far enough away that its position can be considered to be infinite, and all light rays coming from it are parallel.

-

This light can cast shadows.

-

class DirectionalLight extends Light

-

Inheritance Light --> DirectionalLight

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
DirectionalLight()Creates a new DirectionalLight.
Properties
targetTarget object
biasbias for double-sided materials
forceCullfront-face cull even for double-sided materials
Methods
setShadowSet the basic shadow-map options.
setShadowProjectionSet the orthographic frustum parameters.
setShadowRadiusSet the soft-shadow radius.
getBoundingBoxGet the bounding box of a scene in the shadow coordinate.
-

Constructors

-

DirectionalLight()

-

Creates a new DirectionalLight.

-

Properties

-

See the base Light class for common properties.

-

target

-

.target: Object3D

-

The DirectionalLight points from its position to target.position. The default position of the target is (0, 0, 0).

-

bias

-

.bias: Number

-

Bias for double-sided materials.

-

Readable & Writable. Default value is 0.001.

-

forceCull

-

.forceCull: Boolean

-

Whether apply front-face culling even for double-sided materials.

-

Methods

-

See the base Light class for common methods.

-

setShadow

-

.setShadow(enable : Boolean, width: Number, height: Number): undefined

-

Set basic shadow-map options.

-

Parameters

-

enable: If set to true light will cast dynamic shadows.

-

width: width of the shadow map.

-

height: height of the shadow map.

-

setShadowProjection

-

.setShadowProjection(left: Number, right: Number, bottom: Number, top: Number, zNear: Number, zFar: Number): undefined

-

Set the orthographic frustum parameters.

-

Parameters

-

left: Frustum left plane.

-

right: Frustum right plane.

-

top: Frustum top plane.

-

bottom: Frustum bottom plane.

-

near: Frustum near plane.

-

far: Frustum far plane.

-

setShadowRadius

-

.setShadowRadius(radius: Number): undefined

-

Set the soft-shadow radius at distance 1.0.

-

radius>0 would activate the PCSS rendering path.

-

getBoundingBox

-

.getBoundingBox(scene: Scene): Object

-

Get the bounding box of a scene in the shadow coordinate.

-

The returned object contains a 'minPos' property and a 'maxPos' property, each of which is a Vector3.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/EnvironmentMap.html b/GameDev/bin/Release/help/api/EnvironmentMap.html deleted file mode 100644 index 43948ac2..00000000 --- a/GameDev/bin/Release/help/api/EnvironmentMap.html +++ /dev/null @@ -1,1283 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class EnvironmentMap

-

class EnvironmentMap extends IndirectLight

-

Inheritance IndirectLight --> EnvironmentMap

- - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
EnvironmentMap()Creates a new EnvironmentMap.
Properties
shCoefficientsSpherical harmonics basis
-

Constructors

-

EnvironmentMap()

-

EnvironmentMap()

-

Usually not created directly. Use EnvironmentMapCreator class to create an EnvironmentMap object.

-

Properties

-

shCoefficients

-

.shCoefficients: Array

-

Spherical harmonics basis. An array of 9 elements, each of which is an array of 3 numbers.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/EnvironmentMapCreator.html b/GameDev/bin/Release/help/api/EnvironmentMapCreator.html deleted file mode 100644 index e0ebc065..00000000 --- a/GameDev/bin/Release/help/api/EnvironmentMapCreator.html +++ /dev/null @@ -1,1295 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class EnvironmentMapCreator

-

class EnvironmentMapCreator

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
EnvironmentMapCreator()Creates a new EnvironmentMapCreator.
Methods
dispose()Dispose the unmanaged resource.
create()Create an EnvironmentMap object.
-

Constructors

-

EnvironmentMapCreator()

-

EnvironmentMapCreator()

-

Create an EnvironmentMapCreator object, which can be used to create EnvironmentMap objects.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

create()

-

.create(image: CubeImage): EnvironmentMap

-

Create an EnvironmentMap object using a cubemap image.

-

.create(image: HDRCubeImage): EnvironmentMap

-

Create an EnvironmentMap object using a HDR cubemap image.

-

.create(background: CubeBackground): EnvironmentMap

-

Create an EnvironmentMap object using a cubemap background.

-

.create(target: CubeRenderTarget, irradiance_only = false: Boolean): EnvironmentMap

-

Create an EnvironmentMap object using a cubemap render target.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Features.html b/GameDev/bin/Release/help/api/Features.html deleted file mode 100644 index 350d12c0..00000000 --- a/GameDev/bin/Release/help/api/Features.html +++ /dev/null @@ -1,1604 +0,0 @@ - - - - - - - - - - - - - - -

Basic Routine

-
import { OrbitControls } from "./controls/OrbitControls.js";
-import { view } from "./view.js";
-
-let renderer, scene, camera, controls;
-
-function init(width, height)
-{
-    renderer = new GLRenderer();
-    scene = new Scene();
-
-    camera = new PerspectiveCamera(45.0, width / height, 0.1, 100.0);
-    camera.setPosition(0.0, 0.0, 7.0);
-
-    controls = new OrbitControls(camera, view);
-    controls.enableDamping = true;
-
-}
-
-function dispose()
-{    
-    camera.dispose();
-    scene.dispose();
-    renderer.dispose();
-}
-
-function render(width, height, size_changed)
-{
-    if (size_changed) 
-    {
-        camera.aspect = width / height;
-        camera.updateProjectionMatrix();
-    }
-
-    if (controls.hasOwnProperty('update'))
-    {
-        controls.update();
-    }
-    renderer.render(scene, camera);
-
-}
-
-setCallback('init', init);
-setCallback('dispose', dispose);
-setCallback('render', render);
-

In the basic routine above, we register 3 callback functions for init, dispose, render events. In addition, mouse events are recieved and dispatched by the imported view object. The view object serves as an event dispatcher. The OrbitControls object uses view to listen to the mouse events.

-

The basic routine contains a GLRenderer, a Scene, and a Camera. These are -wrappers of engine objects. The classes are defined in native code.

-

The each engine object has a dispose method, which can be called explictly to release the underlying resources before garbage collection.

-

The OrbitControls is an ordinary JS object. The class is defined in "./controls/OrbitControls.js". The code is directly ported from Three.js. There are other utilities from Three.js like Vector3, Matrix4, Quaternion, which we are going to use later.

-

Currently, PerspectiveCamera is the only option for camera, but can be easily extended in the future.

-

All scripts need to be pre-bundled. For exmaple:

-
rollup game.js --file bundle.js
-

To run a script, use GamePlayer to load the bundled script.

-

Backgrounds

-

The Scene class has a .background property.

-

A background is optional in a Three.V8 Scene. It is possible to integrate background/foreground layers from outside the engine.

-

When user choose to use a Three.V8 background, now we have the following options:

-

ColorBackground: Use a monotone color.

-

CubeBackground: Use a cubemap.

-

HemisphereBackground: Use a gradient change from sky-color to ground-color.

-

BackgroundScene: Use another scene as background.

-

ColorBackground:

-
bg = new ColorBackground();
-bg.setColor(0.26225, 0.51492, 0.67244);
-scene.background = bg;
-

HemisphereBackground:

-
bg = new HemisphereBackground();   
-bg.setSkyColor(0.318, 0.318, 0.318);
-bg.setGroundColor(0.01, 0.025, 0.025);
-scene.background = bg;
-

CubeBackground:

-
bg = new CubeBackground();
-let cube_img = imageLoader.loadCubeFromFile(
-"assets/textures/sky_cube_face0.jpg", "assets/textures/sky_cube_face1.jpg",
-"assets/textures/sky_cube_face2.jpg", "assets/textures/sky_cube_face3.jpg",
-"assets/textures/sky_cube_face4.jpg", "assets/textures/sky_cube_face5.jpg");        
-bg.setCubemap(cube_img);      
-cube_img.dispose();
-scene.background = bg;
-

For CubeBackground, the cubemap image is loaded using the global object imageLoader.

-

The effect when a HemisphereBackground is set-up: -background.png

-

Models

-

Like Three.js, Three.V8 also has a scene graph, with the Scene object as the root. In Three.V8, we have cameras, lights, and models. However, unlike in Three.js, the scene graph in Three.V8 doesn't get all the way down to meshes. Models, as high-level objects, can have internal structures, which are preserved when a specific type of model is loaded. We believe this is good for efficiency, but the downside is that user only has limited access to the internal structures.

-

Currently, there are the following types of models:

-

SimpleModel: A Model containing a single simple geometry.

-

GLTFModel: A Model that has a GLTF style internal structure.

-

SimpleModel:

-
import { Vector3 } from "./math/Vector3.js";
-
-box = new SimpleModel();
-box.name = "box";
-box.createBox(2.0, 2.0, 2.0);
-box.translateX(-1.5);
-let axis = new Vector3(1.0, 1.0, 0.0);
-axis.normalize();
-box.rotateOnAxis(axis, 1.0);
-{
-    let img = imageLoader.loadFile("assets/textures/uv-test-bw.png");
-    box.setColorTexture(img);
-    img.dispose();
-}
-scene.add(box);
-
-sphere = new SimpleModel();
-sphere.name = "sphere";
-sphere.createSphere(1.0);
-sphere.translateX(1.5);
-{
-    let img = imageLoader.loadFile("assets/textures/uv-test-col.png");
-    sphere.setColorTexture(img);
-    img.dispose();
-}
-sphere.metalness = 0.5;
-sphere.roughness = 0.5;
-scene.add(sphere);
-
-ground = new SimpleModel();
-ground.createPlane(10.0, 10.0);    
-ground.translateY(-1.7);
-ground.rotateX(-3.1416*0.5);
-scene.add(ground);
-

For SimpleModel, first create by "new". Then, call one of the ".create" functions to create geometry. For material, you can set base color by calling .setColor, or .setColorTexture to set a base color map. The image is loaded using the global object imageLoader.

-

GLTFModel:

-
model = gltfLoader.loadModelFromFile("assets/models/RZYAS.glb");
-model.setPosition(0, -8, 0); 
-scene.add(model); 
-

For GLTFModel, the global object gltfLoader should be used to create the model.

-

The effect when a few simple models are added to the scene: -models.png -Since that no lighting has been set, the models appear black.

-

Indirect Lighting

-

In an open scene, we can use a global indirect light source to create a natural looking. Therefore, we put the indirect lighting before the direct lighting. A global indirect light source can be set through scene.indirectLight. In contrary to Three.js, in Three.v8, an IndirectLight is not an Object3D.

-

Currently we have to following options for indirect light source.

-

AmbientLight: corresponding to ColorBackground. Monotone ambient light.

-

EnvironmentMap: corresponding to CubeBackground. Image based lighting.

-

HemisphereLight: corresponding to HemisphereBackground. Gradient ambient light.

-

ProbeGrid: an uniform grid of light-probes.

-

LODProbeGrid: a mixed-resolution grid of light-probes.

-

AmbientLight:

-
envLight = new AmbientLight();
-envLight.setColor(0.0, 0.52, 1.0);
-scene.indirectLight = envLight;
-

EnvironmentMap:

-
let cube_img = imageLoader.loadCubeFromFile(
-"assets/textures/sky_cube_face0.jpg", "assets/textures/sky_cube_face1.jpg",
-"assets/textures/sky_cube_face2.jpg", "assets/textures/sky_cube_face3.jpg",
-"assets/textures/sky_cube_face4.jpg", "assets/textures/sky_cube_face5.jpg");
-
-let envMapCreator = new EnvironmentMapCreator();
-envLight = envMapCreator.create(cube_img);
-scene.indirectLight = envLight;
-envMapCreator.dispose();
-cube_img.dispose();
-

You can use the same CubeImage for both the background and the indirect light of the scene, before disposing it.

-

HemisphereLight:

-
envLight = new HemisphereLight();
-envLight.setSkyColor(0.318, 0.318, 0.318);
-envLight.setGroundColor(0.01, 0.025, 0.025);
-scene.indirectLight = envLight;
-

The effect after setting a HemisphereLight: -indirect_light.png

-

Direct Lighting

-

Direct light sources are explict light emitting 3d objects placed into the scene.

-

Currently we have to following options for direct light source.

-

DirectionalLight: A light that gets emitted in a specific direction. This light will behave as though it is infinitely far away and the rays produced from it are all parallel.

-

DirectionalLight:

-
directional_light = new DirectionalLight();
-directional_light.intensity = 4.0;
-directional_light.setPosition(5.0, 10.0, 5.0);
-directional_light.setShadow(true, 4096, 4096);
-directional_light.setShadowProjection(-10.0, 10.0, -10.0, 10.0, 0.0, 50.0);
-scene.add(directional_light);
-

The DirectionalLight points from its position to target.position. The default position of the target is (0, 0, 0). Shadow is optional. When it is enabled. The projection parameters needs to be carefully specified as the shadow-map covers only a limited area.

-

The effect after adding a DirectionalLight, without shadow: -noshadow.png

-

The effect after enabling shadow: -screenshot.png

-

Animation

-

Animation features are enabled on a per model basis.

-

Currently, only GLTFModel has the animation features.

-

Animation Clip Management

-

Animation clips are owned by each model. When a model is loaded, the animations clips are also loaded if they are present

-

GLTFModel.addAnimation and GLTFModel.addAnimations: add more animation clips to a model. These animation clips might be loaded separately.

-

Animation Control

-

First, a static pose can be specified without involving any animation clip.

-

GLTFModel.setAnimationFrame: specify the state of each movable parts.

-

Second, the play/stop state of each animation clip can be controlled separately.

-

GLTFModel.playAnimation: start playing an animation clip.

-

GLTFModel.stopAnimation: stop playing an animation clip.

-

In order to have the animation clip being played to take effect, call GLTFModel.updateAnimation from the render callback function.

-

The following code loads the Parrot model and starts the animation that comes with the model:

-
model = gltfLoader.loadModelFromFile("assets/models/Parrot.glb");
-model.playAnimation("KeyAction");
-

Parrot.png

-

Ray Casting

-

Accelerated ray-casting is most handy for basic physical simulation such as collision detection. Three.V8 provides a BoundingVolumeHierarchy helper class to accelerate ray-geometry intersection calculation, which is powered by the bvh library.

-

The constructor creates a bvh acceleration structure from a list of 3d objects.

-

The .intersect method intersects the accleration structure with a given ray. Both input and output are expressed using ordinary JS objects.

-

Network Sub-system

-

To provide a usable app framework, networking functionality is necessary.

-

Currently, Three.V8 only support basic HTTP-Get requests.

-

The global object http provides 2 methods:

-
    -
  • get(): for synchronized HTTP-Get.
  • -
  • getAsync(): for asynchronized HTTP-Get.
  • -
-

Both get methods supports binary and text(utf-8 encoded) modes.

-

getAsync() uses callback. To convert it into an actual async function, use the following code-snippet:

-
function httpGetAsync(url, is_text)
-{
-    return new Promise((resolve, reject) => {
-        http.getAsync(url, is_text, (suc, data)=>
-        {
-            resolve(data);
-        });
-    });
-}
-

The returned ArrayBuffer can then be used with ImageLoader or GLTFLoader.

-

GUI Sub-system

-

Again, to provide a usable app framework, GUI functionality is necessary.

-

Currently, Three.V8 provides a minimalism GUI sub-system which is embedded into the 3D rendering flow.

-

The system is incomplete. It doesn't include any layout calculation. The position and size of each ui element need to be explicitly specified by user. The up-side of this is that the ui elements are very accurately positioned, and behaves consistently across different devices.

-

Structure

-

UIManager.png

-

Each script context has a single UIManager object. The UIManager manages one or more UIArea objects, each contains multiple UIElement objects.

-

Each UIArea maintains a framebuffer where the ui-elements are rendered.

-

The UIManager processes all the Mouse/Touch/Keyboard inputs by traversing each UIArea and UIElement.

-

While all ui-elements are directly owned by an UIArea, they can be geometrically nested.

-

The geometry relationship can be specified using UIElement.block. The block property specifies the geometry parent of an element.

-

In the hierachy of UIElement classes: -UIElement.png

-

only those derived from UIBlock can be used as UIElement.block, which means the other ui-elements can only be the leaf elements.

-

Example

-

GUI_Demo.png

-
function setupUI()
-{
-    if (!gamePlayer.hasFont("default"))
-    {
-        gamePlayer.createFontFromFile("default", "assets/fonts/NotoSansSC-Bold.otf");
-    }
-
-    ui_area = new UIArea();
-    ui_area.setOrigin(15.0, 30.0);
-    ui_area.setSize(320.0, 480.0);
-    UIManager.add(ui_area);
-
-    panel2 = new UIPanel();
-    panel2.setOrigin(0.0, 0.0);
-    panel2.setSize(300.0, 200.0);
-    ui_area.add(panel2);
-
-    {
-        text_msg = new UIText();
-        text_msg.text = "Accurate GUI Layout";
-        text_msg.block = panel2;
-        text_msg.setStyle({ "alignmentVertical": 0});
-        text_msg.setOrigin(0.0, 30.0);    
-        ui_area.add(text_msg); 
-
-        edit = new UILineEdit();
-        edit.setOrigin(50.0, 60.0);
-        edit.block = panel2;
-        edit.text = "你好ABC,Can you see me?";
-        ui_area.add(edit);
-
-        btn = new UIButton();
-        btn.setOrigin(50.0, 120.0);
-        btn.setSize(90.0, 40.0);
-        btn.block = panel2;    
-        btn.onClick = ClearUI;
-        ui_area.add(btn);        
-        {
-
-            img = imageLoader.loadFile("assets/textures/ok.png");
-            btn_img = new UIImage();
-            btn_img.setImage(img);
-            btn_img.block = btn;
-            btn_img.setSize(30,30);
-            ui_area.add(btn_img);
-
-            btn_text = new UIText();
-            btn_text.text = "OK";
-            btn_text.block = btn;
-            btn_text.setStyle({ "alignmentHorizontal": 0 });
-            btn_text.setOrigin(40.0, 0.0); 
-            btn.onLongPress = () =>
-            {
-                print("Long Press");
-            }   
-            ui_area.add(btn_text); 
-        }
-
-        btn2 = new UIButton();
-        btn2.setOrigin(150.0, 120.0);
-        btn2.setSize(110.0, 40.0);
-        btn2.block = panel2;
-        btn2.onClick = ClearUI;
-        ui_area.add(btn2);
-        {        
-            img2 = imageLoader.loadFile("assets/textures/cancel.png");
-            btn_img2 = new UIImage();
-            btn_img2.setImage(img2);
-            btn_img2.block = btn2;
-            btn_img2.setSize(30,30);
-            ui_area.add(btn_img2);
-
-            btn_text2 = new UIText();
-            btn_text2.text = "Cancel";
-            btn_text2.block = btn2;
-            btn_text2.setStyle({ "alignmentHorizontal": 0 });
-            btn_text2.setOrigin(40.0, 0.0);
-            ui_area.add(btn_text2);   
-        }
-    }
-
-    sview = new UIScrollViewer();    
-    sview.setOrigin(0.0, 220.0);
-    sview.setSize(280.0, 240.0);    
-    ui_area.add(sview); 
-    {
-        picture = new UIImage();
-        picture.block = sview;
-        {
-            img3 = imageLoader.loadFile("assets/textures/uv-test-col.png");            
-            picture.setImage(img3);
-            picture.setSize(180,180);
-        }        
-        ui_area.add(picture);
-        sview.setContentSize(200,400);
-
-        btn3 = new UIButton();
-        btn3.block = sview;
-        btn3.setOrigin(20, 200);
-        btn3.setSize(100.0, 40.0);
-        ui_area.add(btn3);
-        {
-            btn_text3 = new UIText();
-            btn_text3.text = "Test1";
-            btn_text3.block = btn3;                       
-            ui_area.add(btn_text3);   
-        }
-
-        btn4 = new UIButton();
-        btn4.block = sview;
-        btn4.setOrigin(20, 250);
-        btn4.setSize(100.0, 40.0);
-        ui_area.add(btn4);
-        {
-            btn_text4 = new UIText();
-            btn_text4.text = "Test2";
-            btn_text4.block = btn4;                       
-            ui_area.add(btn_text4);   
-        }
-    }
-}
-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/FileLoader.html b/GameDev/bin/Release/help/api/FileLoader.html deleted file mode 100644 index ee1d07e0..00000000 --- a/GameDev/bin/Release/help/api/FileLoader.html +++ /dev/null @@ -1,1278 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class FileLoader

-

Provides a few interfaces to loading local files into memory.

-

No constructor, exposed as a global object fileLoader.

- - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
loadBinaryFile()Load a binary file into memory.
loadTextFile()Load a text file into memory.
-

Methods

-

loadBinaryFile()

-

.loadBinaryFile(name: String): ArrayBuffer

-

Load a binary file into memory.

-

loadTextFile()

-

.loadTextFile(name: String): String

-

Load a text file (utf8 encoding assumed) into memory.

-
- - diff --git a/GameDev/bin/Release/help/api/Fog.html b/GameDev/bin/Release/help/api/Fog.html deleted file mode 100644 index e05a88de..00000000 --- a/GameDev/bin/Release/help/api/Fog.html +++ /dev/null @@ -1,1343 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Fog

-

Class that represents the particle substance in the air.

-

Setting a fog object to a scene would trigger a ray-marching calculation when some kind of light source is present.

-

class Fog

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
Fog()Creates a Fog object.
Properties
colorThe color of the Fog.
densityThe density of the Fog.
maxNumStepsMaximum number of steps for each ray-marching.
minStepMinimal distance to march for each ray-marching step.
Methods
dispose()Dispose the unmanaged resource.
getColorGet the value of .color
setColorSet the value of .color
-

Constructors

-

Fog()

-

Fog()

-

Creates a Fog object.

-

Properties

-

color

-

.color: Object

-

The color of the fog.

-

Read-only. Use the method .setColor to modify this property.

-

density

-

.density: Number

-

Density of the fog, which is the opacity of thickness 1 of the fog.

-

Valid range: 0.0 ~ 1.0

-

Defalut value: 0.1

-

Readable and writable.

-

maxNumSteps

-

.maxNumSteps: Number

-

Maximum number of steps for each ray-marching.

-

Valid range: > 0

-

Default value: 50

-

Readable and writable.

-

minStep

-

.minStep: Number

-

Minimal distance to march for each ray-marching step.

-

Valid range: > 0.0

-

Default value: 0.15

-

Readable and writable.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

getColor()

-

.getColor(color: Vector3) : Vector3

-

Copy the value of .color into color.

-

setColor()

-

.setColor(color: Vector3): undefined

-

Set the value of .color according to color.

-

.setColor(r: Number, g: Number, b: Number ): undefined

-

Set the value of .color according to the r, g, b values.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/GLRenderTarget.html b/GameDev/bin/Release/help/api/GLRenderTarget.html deleted file mode 100644 index 2e095bac..00000000 --- a/GameDev/bin/Release/help/api/GLRenderTarget.html +++ /dev/null @@ -1,1302 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class GLRenderTarget

-

An off-screen render target.

-

Can be used as an extra parameter to GLRenderer.render().

-

class GLRenderTarget

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
GLRenderTarget()Creates a new GLRenderTarget.
Methods
disposeDispose the unmanaged resource.
getImageGet the rendering result as an Image
setSizeUpdate the size of the render target.
-

Constructors

-

GLRenderTarget()

-

GLRenderTarget(width: Number, height: Number, msaa= true: Boolean)

-

Create a new GLRenderTarget.

-

Parameters

-

width: width of the image data

-

height: height of the image data

-

msaa: should MSAA be used

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

getImage()

-

.getImage(): Image

-

Returns the rendering result as an Image object.

-

setSize()

-

.setSize(width: Number, height: Number): undefined

-

Update the size of the render target.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/GLRenderer.html b/GameDev/bin/Release/help/api/GLRenderer.html deleted file mode 100644 index 655b5d65..00000000 --- a/GameDev/bin/Release/help/api/GLRenderer.html +++ /dev/null @@ -1,1323 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class GLRenderer

-

The OpenGL renderer displays your beautifully crafted scenes using OpenGL.

-

class GLRenderer

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
GLRenderer()Creates a new GLRenderer.
Properties
useSSAOWhether enable SSAO.
Methods
disposeDispose the unmanaged resource.
renderRenders a scene.
renderCubeRenders a scene to a cubemap.
renderTextureRender a 2d media to screen.
-

Constructors

-

GLRenderer()

-

GLRenderer()

-

Create a GLRenderer.

-

Properties

-

useSSAO

-

.useSSAO: Boolean

-

Whether enable SSAO.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

render()

-

.render(scene: Scene, camera: Camera): undefined

-

Renders scene using camera to the main view of the game-player.

-

Should be called from the render() callback function.

-

.render(scene: Scene, camera: Camera, ui3dviewer: UI3DViewer): undefined

-

Renders scene using camera to ui3dviewer.

-

Should be called from the onRender() callback function of the ui3dviewer.

-

.render(scene: Scene, camera: Camera, target: GLRenderTarget): undefined

-

Renders scene using camera to target.

-

renderCube()

-

.renderCube(scene: Scene, target: CubeRenderTarget, position: Object, near=0.1: Number, far=100.0: Number): undefined

-

Renders scene to a cubemap target centered at position.

-

renderTexture()

-

.renderTexure(img: GLRenderTarget/MMCamera/MMLazyVideo/MMVideo/AVCPlayer, x:Number, y:Number, width:Number, height:Number, alpha = 1.0:Number, target=undefined: UI3DViewer/GLRenderTarget): undefined

-

Render a 2D media to screen.

-

When target is not specified, the media is rendered to the main view of the game-player by default.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/GLTFLoader.html b/GameDev/bin/Release/help/api/GLTFLoader.html deleted file mode 100644 index 9a3cb06b..00000000 --- a/GameDev/bin/Release/help/api/GLTFLoader.html +++ /dev/null @@ -1,1295 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class GLTFLoader

-

Provides a few interfaces to load GLTF models from local files or from memory.

-

No constructor, exposed as a global object gltfLoader.

-

class GLTFLoader

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
loadModelFromFile()Load a GLTF model from a local GLTF file.
loadAnimationsFromFile()Load only animation data from a local GLTF file.
loadModelFromMemory()Load a GLTF model from a memory buffer.
loadAnimationsFromMemory()Load only animation data from a memory buffer.
-

Methods

-

loadModelFromFile()

-

.loadModelFromFile(name: String): GLTFModel

-

Load a GLTF model from a local GLTF file.

-

loadAnimationsFromFile()

-

.loadAnimationsFromFile(name: String): Object

-

Load only animation data from a local GLTF file.

-

The returned object has the same structure as the return value of GLTFModel.getAnimation.

-

loadModelFromMemory()

-

.loadModelFromMemory(buf: ArrayBuffer): GLTFModel

-

Load a GLTF model from a memory buffer.

-

loadAnimationsFromMemory()

-

.loadAnimationsFromMemory(buf: ArrayBuffer): Object

-

Load only animation data from a memory buffer.

-

The returned object has the same structure as the return value of GLTFModel.getAnimation.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/GLTFModel.html b/GameDev/bin/Release/help/api/GLTFModel.html deleted file mode 100644 index 4c317010..00000000 --- a/GameDev/bin/Release/help/api/GLTFModel.html +++ /dev/null @@ -1,1472 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class GLTFModel

-

A Model that has a GLTF style internal structure.

-

class GLTFModel extends Object3D

-

Inheritance Object3D --> GLTFModel

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
GLTFModel()Creates a new GLTFModel.
Properties
minPosBounding box min-position.
maxPosBounding box max-position.
meshesInfo of internal meshes.
animationsInfo of internal animation clips.
Methods
setTextureReplace a texture using texture name.
batchPrimitivesBatch together primitives of the same materials.
setAnimationFrameAssign the current stage of movable parts.
getAnimationGet a loaded animation clip by name.
getAnimationsGet all loaded animation clips.
addAnimationAdd an animation clip to the model.
addAnimationsAdd multiple animation clips to the model.
playAnimationPlay the animation clip of the given name.
stopAnimationStop the animation clip of the given name.
updateAnimationUpdate the movable parts according to the current frame.
setLightmapSet a lightmap image for the model.
-

Constructors

-

GLTFModel()

-

GLTFModel()

-

Creates a new GLTFModel. Usually not created directly. Use GLTFLoader class to create an GLTFModel.

-

Properties

-

See the base Object3D class for common properties.

-

minPos

-

.minPos: Object

-

Read-only property for bounding box min-position.

-

maxPos

-

.maxPos: Object

-

Read-only property for bounding box max-position.

-

meshes

-

.meshes: Object

-

Read-only property for displaying the info of internal meshes.

-

animations

-

.animations: Array

-

Read-only property for displaying the info of internal animation clips.

-

Methods

-

See the base Object3D class for common methods.

-

setTexture()

-

.setTexture(name: String, image: Image): undefined

-

Replace the texture of name with image.

-

.setTexture(name: String, target: GLRenderTarget): undefined

-

Use the rendering result of target to replace the texture of name.

-

.setTexture(name: String, mmcamera: MMCamera): undefined

-

Usa a web-camera image source mmcamera to replace the texture of name.

-

.setTexture(name: String, mmlazyvideo: MMLazyVideo): undefined

-

Usa a video-file image source mmlazyvideo to replace the texture of name.

-

.setTexture(name: String, mmvideo: MMVideo): undefined

-

Usa a video-file player mmvideo to replace the texture of name.

-

batchPrimitives()

-

.batchPrimitives(): undefined

-

Batch together primitives of the same materials.

-

setAnimationFrame()

-

.setAnimationFrame(frame: Object): undefined

-

Assign the current stage of movable parts using a JS object.

-

The frame object should have the following properties:

-

frame.morphs: Array

-

Optional. Morph state for morphable meshes.

-

frame.morphs[i].name: String

-

Name of a morphable mesh.

-

frame.morphs[i].weights: Array

-

Weight for each morph target of the mesh.

-

frame.translations: Array

-

Optional. Translation states for nodes.

-

frame.translations[i].name: String

-

Name of the targeted node.

-

frame.translations[i].translation: Vector3

-

Translation state of the node.

-

frame.rotations: Array

-

Optional. Rotation states for nodes.

-

frame.rotations[i].name: String

-

Name of the targeted node.

-

frame.rotations[i].rotation: Quaternion

-

Rotation state of the node.

-

frame.scales: Array

-

Optional. Scale states for nodes.

-

frame.scales[i].name: String

-

Name of the targeted node.

-

frame.translations[i].scale: Vector3

-

Scale state of the node.

-

getAnimation()

-

.getAnimation(name: String): Object

-

Get a loaded animation clip by name.

-

The returned object has the following properties:

-

.name: String

-

Name of the animation clip.

-

.duration: Number

-

Duration of the animation clip in seconds.

-

.morphs: Array

-

Optional. Morph tracks.

-

.morphs[i].name: String

-

Name of the morphable mesh.

-

.morphs[i].targets: Number

-

Number of morph targets of the morphable mesh.

-

.morphs[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR" or "CUBICSPLINE"

-

.morphs[i].times: Float32Array

-

Time stamp of each frame.

-

.morphs[i].values: Float32Array

-

Weight values of each frame.

-

.translations: Array

-

Optional. Translation tracks.

-

.translations[i].name: String

-

Name of the targeted node.

-

.translations[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR" or "CUBICSPLINE"

-

.translations[i].times: Float32Array

-

Time stamp of each frame.

-

.translations[i].values: Float32Array

-

Translation values of each frame.

-

.rotations: Array

-

Optional. Rotation tracks.

-

.rotations[i].name: String

-

Name of the targeted node.

-

.rotations[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR"

-

.rotations[i].times: Float32Array

-

Time stamp of each frame.

-

.rotations[i].values: Float32Array

-

Rotation values of each frame.

-

.scales: Array

-

Optional. Scale tracks.

-

.scales[i].name: String

-

Name of the targeted node.

-

.scales[i].interpolation: String

-

Interpolation method: "STEP", "LINEAR" or "CUBICSPLINE"

-

.scales[i].times: Float32Array

-

Time stamp of each frame.

-

.scales[i].values: Float32Array

-

Scale values of each frame.

-

getAnimations()

-

.getAnimations(): Array

-

Get all loaded animation clips.

-

Each element of the returned array has the same structure as the return value of .getAnimation().

-

addAnimation()

-

.addAnimation(animation: Object): undefined

-

Add an animation clip to the model.

-

The animation object should have the same structure as the return value of .getAnimation().

-

addAnimations()

-

.addAnimations(animations: Array): undefined

-

Add multiple animation clips to the model.

-

Each element of the array should have the same structure as the return value of .getAnimation().

-

playAnimation()

-

.playAnimation(name: String): undefined

-

Play the animation clip of the given name.

-

stopAnimation()

-

.stopAnimation(name: String): undefined

-

Stop the animation clip of the given name.

-

updateAnimation()

-

.updateAnimation(): undefined

-

Update the movable parts according to the current frame. This function should be called from the render callback function.

-

setLightmap()

-

.setLightmap(img: HDRImage): undefined

-

Set a lightmap image for the model.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/GUI_Demo.png b/GameDev/bin/Release/help/api/GUI_Demo.png deleted file mode 100644 index c4d9fc99..00000000 Binary files a/GameDev/bin/Release/help/api/GUI_Demo.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/GamePlayer.html b/GameDev/bin/Release/help/api/GamePlayer.html deleted file mode 100644 index d92b10de..00000000 --- a/GameDev/bin/Release/help/api/GamePlayer.html +++ /dev/null @@ -1,1334 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class GamePlayer

-

Provides a few interfaces to access the host GamePlayer object.

-

No constructor, exposed as a global object gamePlayer.

-

class GamePlayer

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Properties
widthCurrent video width
heightCurrent video height
pickingWhether picking is enabled
Methods
message()Send a general message to the game player.
hasFont()Check if the font of name has been loaded.
createFontFromFile()Load font from local file.
createFontFromMemory()Load font from a memory buffer.
pickObject()Pick the object visible at screen location x,y.
-

Properties

-

width

-

.width: Number

-

Read-only value of current video width.

-

height

-

.height: Number

-

Read-only value of current video height.

-

picking

-

.picking: Boolean

-

Whether picking is enabled.

-

Methods

-

message()

-

.message(name: String, msg: String) : String

-

Send a general message to the game player.

-

Pointer capture/release messages are sent through this interface, using names "setPointerCapture" and "releasePointerCapture".

-

hasFont()

-

.hasFont(name: String) : Boolean

-

Check if the font of name has been loaded.

-

createFontFromFile()

-

.createFontFromFile(name: String, filename: String): undefined

-

Load font from local file.

-

Parameters

-

name: name of the font being loaded.

-

filename: file name of the TrueType font

-

createFontFromMemory()

-

.createFontFromMemory(name: String, data: ArrayBuffer): undefined

-

Load font from a memory buffer.

-

Parameters

-

name: name of the font being loaded.

-

data: memory buffer containing the binary data of the TrueType font.

-

pickObject()

-

.pickObject(x:Number, y:Number): Object

-

Pick the object visible at screen location x,y.

-

The returned object contains a "name" property.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/HDRCubeImage.html b/GameDev/bin/Release/help/api/HDRCubeImage.html deleted file mode 100644 index d4d50e66..00000000 --- a/GameDev/bin/Release/help/api/HDRCubeImage.html +++ /dev/null @@ -1,1306 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class HDRCubeImage

-

Class that represents a HDR cubemap image that resides in CPU memory.

-

A HDRCubeImage contains 6 images.

-

Usually not created directly. Use HDRImageLoader class to create a HDR cubemap image.

-

class HDRCubeImage

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
HDRCubeImage()Creates a HDR cube image.
Properties
widthWidth of the image.
heightHeight of the image.
Methods
dispose()Dispose the unmanaged resource.
-

Constructors

-

HDRCubeImage()

-

HDRCubeImage()

-

Note that this constructor is not intended to be called directly.

-

Properties

-

width

-

.width: Number

-

Width of the image.

-

Read-only.

-

height

-

.height: Number

-

Height of the image.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/HDRImage.html b/GameDev/bin/Release/help/api/HDRImage.html deleted file mode 100644 index a2b7fcad..00000000 --- a/GameDev/bin/Release/help/api/HDRImage.html +++ /dev/null @@ -1,1310 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class HDRImage

-

Class that represents a HDR image that resides in CPU memory.

-

Usually not created directly. Use HDRImageLoader class to create an HDR image.

-

class HDRImage

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
HDRImage()Creates a HDR image.
Properties
widthWidth of the image.
heightHeight of the image.
Methods
dispose()Dispose the unmanaged resource.
-

Constructors

-

HDRImage()

-

HDRImage()

-

Creates an empty HDR image.

-

HDRImage(width: Number, height: Number)

-

Create an HDR image of specified size.

-

Parameters

-

width: width of image

-

height: height of image

-

Properties

-

width

-

.width: Number

-

Width of the image.

-

Read-only.

-

height

-

.height: Number

-

Height of the image.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/HDRImageLoader.html b/GameDev/bin/Release/help/api/HDRImageLoader.html deleted file mode 100644 index 1307eec8..00000000 --- a/GameDev/bin/Release/help/api/HDRImageLoader.html +++ /dev/null @@ -1,1311 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class HDRImageLoader

-

Provides a few interfaces to load HDR images from local files or from memory.

-

No constructor, exposed as a global object HDRImageLoader.

-

class HDRImageLoader

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
loadFile()Load a HDR image from local file.
loadMemory()Load a HDR image from a memory buffer.
loadCubeFromFile()Load 6 HDR images from local files to form a HDR cubemap image.
loadCubeFromMemory()Load 6 HDR images from memory buffers to form a HDR cubemap image.
fromImages()Load a HDR image from a series of LDR images.
fromRGBM()Load a HDR image from a RGBM image(LDR).
-

Methods

-

loadFile()

-

.loadFile(name: String): HDRImage

-

Load a HDR (RGBE) image from local file.

-

loadMemory()

-

.loadMemory(buf: ArrayBuffer): HDRImage

-

Load a HDR (RGBE) image from a memory buffer.

-

loadCubeFromFile()

-

.loadCubeFromFile(name0: String, name1: String, name2: String, name3: String, name4: String, name5: String) : HDRCubeImage

-

Load 6 HDR (RGBE) images from local files to form a HDR cubemap image.

-

loadCubeFromMemory()

-

.loadCubeFromMemory(buf0: ArrayBuffer, buf1: ArrayBuffer, buf2: ArrayBuffer, buf3: ArrayBuffer, buf4: ArrayBuffer, buf5: ArrayBuffer) : HDRCubeImage

-

Load 6 HDR (RGBE) images from memory buffers to form a HDR cubemap image.

-

fromImages()

-

.fromImages(lst_images: Array, lst_ranges: Array) : HDRImage

-

Load a HDR image from a series of LDR images.

-

This is a decoding method for a HDR image compressed using cascaded residual encoding.

-

Parameters

-

lst_images: an array of Image objects.

-

lst_ranges: an array of objects containing a 'low' property and a 'high' property, each of which is a Vector3.

-

fromRGBM()

-

.fromRGBM(img: Image, rate: Number)

-

Load a HDR image from a RGBM image(LDR).

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/HemisphereBackground.html b/GameDev/bin/Release/help/api/HemisphereBackground.html deleted file mode 100644 index 4df3e9a5..00000000 --- a/GameDev/bin/Release/help/api/HemisphereBackground.html +++ /dev/null @@ -1,1314 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class HemisphereBackground

-

A background that has a sky color and a ground color.

-

class HemisphereBackground extends Background

-

Inheritance Background --> HemisphereBackground

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
HemisphereBackground()Creates a new HemisphereBackground.
Properties
setSkyColorSky color of the background.
groundColorGround color of the background.
Methods
getSkyColorGet the value of .skyColor
setSkyColorSet the value of .skyColor
-

Constructors

-

HemisphereBackground()

-

HemisphereBackground()

-

Creates a new HemisphereBackground.

-

Properties

-

skyColor

-

.skyColor: Object

-

The sky color of the background.

-

Read-only. Use the method .setSkyColor to modify this property.

-

groundColor

-

.groundColor: Object

-

The ground color of the background.

-

Read-only. Use the method .setGroundColor to modify this property.

-

Methods

-

getSkyColor()

-

.getSkyColor(color: Vector3) : Vector3

-

Copy the value of .skyColor into color.

-

setSkyColor()

-

.setSkyColor(color: Vector3): undefined

-

Set the value of .skyColor according to color.

-

.setSkyColor(r: Number, g: Number, b: Number ): undefined

-

Set the value of .skyColor according to the r, g, b values.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/HemisphereLight.html b/GameDev/bin/Release/help/api/HemisphereLight.html deleted file mode 100644 index da7f3125..00000000 --- a/GameDev/bin/Release/help/api/HemisphereLight.html +++ /dev/null @@ -1,1339 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class HemisphereLight

-

A light source positioned directly above the scene, with color fading from the sky color to the ground color.

-

This light cannot be used to cast shadows.

-

class HemisphereLight extends IndirectLight

-

Inheritance IndirectLight --> HemisphereLight

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
HemisphereLight()Creates a new HemisphereLight.
Properties
skyColorThe sky color of the hemisphere light.
groundColorThe ground color of the hemisphere light.
intensityThe intensity of the hemisphere light.
Methods
getSkyColorGet the value of .skyColor
setSkyColorSet the value of .skyColor
getGroundColorGet the value of .groundColor
setGroundColorSet the value of .groundColor
-

Constructors

-

HemisphereLight()

-

HemisphereLight()

-

Creates a new HemisphereLight.

-

Properties

-

skyColor

-

.skyColor: Object

-

The sky color of the hemisphere light.

-

Read-only. Use the method .setSkyColor to modify this property.

-

groundColor

-

.groundColor: Object

-

The ground color of the hemisphere light.

-

Read-only. Use the method .setGroundColor to modify this property.

-

intensity

-

.intensity: Number

-

The intensity of the hemisphere light.

-

Readable and writable.

-

Methods

-

getSkyColor()

-

.getSkyColor(color: Vector3) : Vector3

-

Copy the value of .skyColor into color.

-

setSkyColor()

-

.setSkyColor(color: Vector3): undefined

-

Set the value of .skyColor according to color.

-

.setSkyColor(r: Number, g: Number, b: Number ): undefined

-

Set the value of .skyColor according to the r, g, b values.

-

getGroundColor()

-

.getGroundColor(color: Vector3) : Vector3

-

Copy the value of .groundColor into color.

-

setGroundColor();

-

.setGroundColor(color: Vector3): undefined

-

Set the value of .groundColor according to color.

-

.setGroundColor(r: Number, g: Number, b: Number ): undefined

-

Set the value of .groundColor according to the r, g, b values.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/HttpClient.html b/GameDev/bin/Release/help/api/HttpClient.html deleted file mode 100644 index d58f5af5..00000000 --- a/GameDev/bin/Release/help/api/HttpClient.html +++ /dev/null @@ -1,1284 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class HttpClient

-

Provides a few interfaces to make HTTP requests.

-

No constructor, exposed as a global object http.

- - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
getMakes a synchronized HTTP Get Request.
getAsyncMakes an asynchronized HTTP Get Request.
-

Methods

-

get()

-

.get(url: String, is_string = False: Boolean): String/ArrayBuffer

-

Makes a synchronized HTTP Get Request.

-

Returns String when is_string == True.

-

Return ArrayBuffer when is_string == False.

-

getAsync()

-

.getAsync(url:String, is_string = False: Boolean, callback: Function) : undefined

-

Makes an asynchronized HTTP Get Request.

-

When is_string == True:

-

callback(result: Boolean, text: String): undefined

-

When is_string == False:

-

callback(result: Boolean, data: ArrayBuffer): undefined

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Image.html b/GameDev/bin/Release/help/api/Image.html deleted file mode 100644 index 86b59c05..00000000 --- a/GameDev/bin/Release/help/api/Image.html +++ /dev/null @@ -1,1310 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Image

-

Class that represents an image that resides in CPU memory.

-

Usually not created directly. Use ImageLoader class to create an image.

-

class Image

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
Image()Creates an image.
Properties
widthWidth of the image.
heightHeight of the image.
Methods
dispose()Dispose the unmanaged resource.
-

Constructors

-

Image()

-

Image()

-

Creates an empty image.

-

Image(width: Number, height: Number)

-

Create an image of specified size.

-

Parameters

-

width: width of image

-

height: height of image

-

Properties

-

width

-

.width: Number

-

Width of the image.

-

Read-only.

-

height

-

.height: Number

-

Height of the image.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/ImageLoader.html b/GameDev/bin/Release/help/api/ImageLoader.html deleted file mode 100644 index 55762fc6..00000000 --- a/GameDev/bin/Release/help/api/ImageLoader.html +++ /dev/null @@ -1,1293 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class ImageLoader

-

Provides a few interfaces to load images from local files or from memory.

-

No constructor, exposed as a global object imageLoader.

-

class ImageLoader

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
loadFile()Load an image from local file.
loadMemory()Load an image from a memory buffer.
loadCubeFromFile()Load 6 images from local files to form a cubemap image.
loadCubeFromMemory()Load 6 images from memory buffers to form a cubemap image.
-

Methods

-

loadFile()

-

.loadFile(name: String): Image

-

Load an image from local file.

-

loadMemory()

-

.loadMemory(buf: ArrayBuffer): Image

-

Load an image from a memory buffer.

-

loadCubeFromFile()

-

.loadCubeFromFile(name0: String, name1: String, name2: String, name3: String, name4: String, name5: String) : CubeImage

-

Load 6 images from local files to form a cubemap image.

-

loadCubeFromMemory()

-

.loadCubeFromMemory(buf0: ArrayBuffer, buf1: ArrayBuffer, buf2: ArrayBuffer, buf3: ArrayBuffer, buf4: ArrayBuffer, buf5: ArrayBuffer) : CubeImage

-

Load 6 images from memory buffers to form a cubemap image.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/IndirectLight.html b/GameDev/bin/Release/help/api/IndirectLight.html deleted file mode 100644 index 01d03ddb..00000000 --- a/GameDev/bin/Release/help/api/IndirectLight.html +++ /dev/null @@ -1,1272 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class IndirectLight

-

Abstract class for all indirect lights

-

No contructor, never used directly.

-

class IndirectLight

- - - - - - - - - - - - - - - -
NameDescription
Methods
disposeDispose the unmanaged resource.
-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/LODProbeGrid.html b/GameDev/bin/Release/help/api/LODProbeGrid.html deleted file mode 100644 index dfbed4e4..00000000 --- a/GameDev/bin/Release/help/api/LODProbeGrid.html +++ /dev/null @@ -1,1388 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class LODProbeGrid

-

A mixed resolution grid of light-probes.

-

class LODProbeGrid extends IndirectLight

-

Inheritance IndirectLight --> LODProbeGrid

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
LODProbeGrid()Creates a new LODProbeGrid.
Properties
coverageMinminimum position of the grid coverage
coverageMaxmaximum position of the grid coverage
baseDivisionsnumber of divisions of the base-level of the grid
subDivisionLevelnumber of sub-division levels
numberOfProbesnumber of probes in the grid
normalBiasbias used for sampling visibility information
perPrimitivewhether using per-primitive interpolation for better performance
Methods
getCoverageMinGet the minimum position of the grid coverage
setCoverageMinSet the minimum position of the grid coverage
getCoverageMaxGet the maximum position of the grid coverage
setCoverageMaxSet the maximum position of the grid coverage
getBaseDivisionsGet the number of divisions of the base-level of the grid
setBaseDivisionsSet the number of divisions of the base-level of the grid
toProbeGridConvert to uniform grid
-

Constructors

-

LODProbeGrid()

-

LODProbeGrid()

-

Creates a new LODProbeGrid.

-

Properties

-

coverageMin

-

.coverageMin: Object

-

The minimum position of the grid coverage.

-

Read-only. Use the method .setCoverageMin to modify this property.

-

coverageMax

-

.coverageMax: Object

-

The maximum position of the grid coverage.

-

Read-only. Use the method .setCoverageMax to modify this property.

-

baseDivisions

-

.baseDivisions: Object

-

The number of divisions of the base-level of the grid.

-

Read-only. Use the method .setBaseDivisions to modify this property.

-

subDivisionLevel

-

.subDivisionLevel: Number

-

Number of sub-division levels.

-

Readable and writable. Default value is 2.

-

numberOfProbes

-

.numberOfProbes: Number

-

Number of probes in the grid.

-

ReadOnly.

-

normalBias

-

.normalBias: Number

-

The bias used for sampling visibility information.

-

Readable and writable. Default value is 0.2.

-

perPrimitive

-

.perPrimitive: Boolean

-

Whether using per-primitive interpolation for better performance

-

Readable and writable. Default value is false.

-

Methods

-

getCoverageMin()

-

.getCoverageMin(coverage_min: Vector3) : Vector3

-

Copy the value of .coverageMin into coverage_min.

-

setCoverageMin()

-

.setCoverageMin(coverage_min: Vector3): undefined

-

Set the value of .coverageMin according to coverage_min.

-

getCoverageMax()

-

.getCoverageMax(coverage_max: Vector3) : Vector3

-

Copy the value of .coverageMax into coverage_max.

-

setCoverageMax()

-

.setCoverageMax(coverage_max: Vector3): undefined

-

Set the value of .coverageMax according to coverage_max.

-

getBaseDivisions()

-

.getBaseDivisions(divisions: Vector3) : Vector3

-

Copy the value of .baseDivisions into divisions.

-

setBaseDivisions()

-

.setBaseDivisions(divisions: Vector3): undefined

-

Set the value of .baseDivisions according to divisions.

-

toProbeGrid()

-

.toProbeGrid(scene: Scene) : ProbeGrid

-

Convert the mixed resoluion grid of light probes to an uniform grid of light probes.

-

Needs the scene paramter for reconstructing missing visibility information.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/LODProbeGridLoader.html b/GameDev/bin/Release/help/api/LODProbeGridLoader.html deleted file mode 100644 index 7f980bad..00000000 --- a/GameDev/bin/Release/help/api/LODProbeGridLoader.html +++ /dev/null @@ -1,1279 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class LODProbeGridLoader

-

Provides a few interfaces to load a LODProbeGrid from local files or from memory.

-

No constructor, exposed as a global object LODProbeGridLoader.

-

class LODProbeGridLoader

- - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
loadFile()Load a lod-probe-grid from a local file.
loadMemory()Load a lod-probe-grid from a memory buffer.
-

Methods

-

loadFile()

-

.loadFile(name: String): LODProbeGrid

-

Load a lod-probe-grid from a local file.

-

loadMemory()

-

.loadMemory(buf: ArrayBuffer): LODProbeGrid

-

Load a lod-probe-grid from a memory buffer.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Light.html b/GameDev/bin/Release/help/api/Light.html deleted file mode 100644 index 865960cb..00000000 --- a/GameDev/bin/Release/help/api/Light.html +++ /dev/null @@ -1,1304 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Light

-

Abstract class for all direct lights.

-

No contructor, never used directly.

-

class Light extends Object3D

-

Inheritance Object3D --> Light

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Properties
colorColor of the light object.
intensityIntensity of the light object.
Methods
getColorGet the value of .color
setColorSet the value of .color
-

Properties

-

See the base Object3D class for common properties.

-

color

-

.color: Object

-

Color of the light object.

-

Read-only. Use the method .setColor to modify this property.

-

intensity

-

Intensity of the light object.

-

Readable and writable.

-

Methods

-

See the base Object3D class for common methods.

-

getColor()

-

.getColor(color: Vector3) : Vector3

-

Copy the value of .color into color.

-

setColor()

-

.setColor(color: Vector3): undefined

-

Set the value of .color according to color.

-

.setColor(r: Number, g: Number, b: Number ): undefined

-

Set the value of .color according to the r, g, b values.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/MMAudio.html b/GameDev/bin/Release/help/api/MMAudio.html deleted file mode 100644 index d579f4f4..00000000 --- a/GameDev/bin/Release/help/api/MMAudio.html +++ /dev/null @@ -1,1352 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class MMAudio

-

Class that represents a background audio-file player.

-

class MMAudio

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
MMAudio()Creates a audio-file player.
Properties
loopingWhether loop the media when EOF met.
isPlayingWhether the media is currently being played.
durationDuration of the media in seconds.
positionPlayback position of the current media in seconds.
Methods
dispose()Dispose the unmanaged resource.
play()Start playback of the media.
pause()Pause playback of the media.
setPosition()Apply seeking.
setAudioDevice()Change the audio-out device.
-

Constructors

-

MMAudio()

-

MMAudio(filename: String, idx_audio_dev: Number, speed: Number)

-

Creates a audio-file player.

-

Parameters

-

filename: url to local or http video source.

-

idx_audio_dev: index of the audio-out device.

-

speed : playback speed. Default 1.0.

-

Properties

-

looping

-

.looping: Boolean

-

Whether loop the media when EOF met.

-

Readable and writable.

-

isPlaying

-

.isPlaying: Boolean

-

Whether the media is currently being played.

-

Read-only.

-

duration

-

.duration: Number

-

Duration of the media in seconds.

-

Read-only.

-

position

-

.position: Number

-

Playback position of the current media in seconds.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

play()

-

.play(): undefined

-

Start playback of the media.

-

pause()

-

.pause(): undefined

-

Pause playback of the media.

-

setPosition()

-

setPosition(position: Number): undefined

-

Apply seeking, set the current position (in secs) to position.

-

setAudioDevice()

-

.setAudioDevice(idx_audio_dev: Number): undefined

-

Change the audio-out device.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/MMCamera.html b/GameDev/bin/Release/help/api/MMCamera.html deleted file mode 100644 index 7f4b0fc8..00000000 --- a/GameDev/bin/Release/help/api/MMCamera.html +++ /dev/null @@ -1,1313 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class MMCamera

-

Class that represents an image source from a web-camera.

-

class MMCamera

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
MMCamera()Creates a web-camera source.
Properties
widthWidth of the image source.
heightHeight of the image source.
Methods
dispose()Dispose the unmanaged resource.
updateTexture()Attempt to read new frames and update the texture data.
-

Constructors

-

MMCamera()

-

MMCamera(idx: Number)

-

Creates a web-camera source.

-

Parameters

-

idx : index of the camera device.

-

Properties

-

width

-

.width: Number

-

Width of the image source.

-

Read-only.

-

height

-

.height: Number

-

Height of the image source.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

updateTexture()

-

.updateTexture(): undefined

-

Attempt to read new frames and update the texture data.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/MMLazyVideo.html b/GameDev/bin/Release/help/api/MMLazyVideo.html deleted file mode 100644 index 07b8bed2..00000000 --- a/GameDev/bin/Release/help/api/MMLazyVideo.html +++ /dev/null @@ -1,1366 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class MMLazyVideo

-

Class that represents an image source from a video-file.

-

class MMLazyVideo

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
MMLazyVideo()Creates a video-file source.
Properties
loopingWhether loop the media when EOF met.
widthWidth of the image source.
heightHeight of the image source.
isPlayingWhether the media is currently being played.
durationDuration of the media in seconds.
positionPlayback position of the current media in seconds.
Methods
dispose()Dispose the unmanaged resource.
updateTexture()Attempt to read new frames and update the texture data.
play()Start playback of the media.
pause()Pause playback of the media.
setPosition()Apply seeking.
-

Constructors

-

MMLazyVideo()

-

MMLazyVideo(filename: String, speed: Number)

-

Creates a video-file source.

-

Parameters

-

speed : playback speed. Default 1.0.

-

Properties

-

looping

-

.looping: Boolean

-

Whether loop the media when EOF met.

-

Readable and writable.

-

width

-

.width: Number

-

Width of the image source.

-

Read-only.

-

height

-

.height: Number

-

Height of the image source.

-

Read-only.

-

isPlaying

-

.isPlaying: Boolean

-

Whether the media is currently being played.

-

Read-only.

-

duration

-

.duration: Number

-

Duration of the media in seconds.

-

Read-only.

-

position

-

.position: Number

-

Playback position of the current media in seconds.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

updateTexture()

-

.updateTexture(): undefined

-

Attempt to read new frames and update the texture data.

-

play()

-

.play(): undefined

-

Start playback of the media.

-

pause()

-

.pause(): undefined

-

Pause playback of the media.

-

setPosition()

-

setPosition(position: Number): undefined

-

Apply seeking, set the current position (in secs) to position.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/MMVideo.html b/GameDev/bin/Release/help/api/MMVideo.html deleted file mode 100644 index f66e04da..00000000 --- a/GameDev/bin/Release/help/api/MMVideo.html +++ /dev/null @@ -1,1377 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class MMVideo

-

Class that represents a background video-file player.

-

Can be used as an image source.

-

class MMVideo

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
MMVideo()Creates a video-file player.
Properties
loopingWhether loop the media when EOF met.
widthWidth of the image source.
heightHeight of the image source.
isPlayingWhether the media is currently being played.
durationDuration of the media in seconds.
positionPlayback position of the current media in seconds.
Methods
dispose()Dispose the unmanaged resource.
updateTexture()Attempt to read new frames and update the texture data.
play()Start playback of the media.
pause()Pause playback of the media.
setPosition()Apply seeking.
setAudioDevice()Change the audio-out device.
-

Constructors

-

MMVideo()

-

MMVideo(filename: String, playAudio: Boolean, idx_audio_dev: Number, speed: Number)

-

Creates a video-file player.

-

Parameters

-

filename: url to local or http video source.

-

playAudio: whether to play audio. Default true.

-

idx_audio_dev: index of the audio-out device.

-

speed : playback speed. Default 1.0.

-

Properties

-

looping

-

.looping: Boolean

-

Whether loop the media when EOF met.

-

Readable and writable.

-

width

-

.width: Number

-

Width of the image source.

-

Read-only.

-

height

-

.height: Number

-

Height of the image source.

-

Read-only.

-

isPlaying

-

.isPlaying: Boolean

-

Whether the media is currently being played.

-

Read-only.

-

duration

-

.duration: Number

-

Duration of the media in seconds.

-

Read-only.

-

position

-

.position: Number

-

Playback position of the current media in seconds.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

updateTexture()

-

.updateTexture(): undefined

-

Attempt to read new frames and update the texture data.

-

play()

-

.play(): undefined

-

Start playback of the media.

-

pause()

-

.pause(): undefined

-

Pause playback of the media.

-

setPosition()

-

setPosition(position: Number): undefined

-

Apply seeking, set the current position (in secs) to position.

-

setAudioDevice()

-

.setAudioDevice(idx_audio_dev: Number): undefined

-

Change the audio-out device.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Object3D.html b/GameDev/bin/Release/help/api/Object3D.html deleted file mode 100644 index 1cb1e9cc..00000000 --- a/GameDev/bin/Release/help/api/Object3D.html +++ /dev/null @@ -1,1729 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Object3D

-

Base class of all 3D objects visible to user script.

-

class Object3D

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
Object3D()Base class of all 3D objects.
Properties
name
isBuidlingWhether this object is part of the buildings.
movedWhether this object is moved after last shadowmap update.
parent
children
upUp direction of object
positionPosition
rotationEuler angles in radians
quaternionRotation in quaternion
scaleScale
matrixThe local transform matrix.
matrixWorldThe global transform matrix.
Methods
dispose()Dispose the unmanaged resource.
getUp()Get the value of .up
setUp()Set the value of .up
getPosition()Get the value of .position
setPosition()Set the value of .position
getRotation()Get the value of .rotation
setRotation()Set the value of .rotation
getQuaternion()Get the value of .quaternion
setQuaternion()Set the value of .quaternion
getScale()Get the value of .scale
setScale()Set the value of .scale
getMatrix()Get the value of .matrix
getMatrixWorld()Get the value of .matrixWorld
updateMatrix()Updates the local transform.
updateWorldMatrix()Updates the global transform.
updateWorldMatrix()Updates the global transform.
applyMatrix4()Applies the matrix transform to the object.
applyQuaternion()Applies the rotation to the object.
setRotationFromAxisAngle()Set the rotation from axis and angle.
setRotationFromMatrix()Set the rotation from rotation matrix.
rotateOnAxis()Rotate an object along an axis.
rotateOnWorldAxis()Rotate an object along a world axis.
rotateX()Rotates the object around x axis.
rotateY()Rotates the object around y axis.
rotateZ()Rotates the object around z axis.
translateOnAxis()Translate an object by distance along an axis
translateX()Translates object along x axis
translateY()Translates object along y axis
translateZ()Translates object along z axis
localToWorld()Converts vector from local space to world space.
worldToLocal()Converts vector from world space to local space.
getWorldPosition()Get position in world space.
getWorldQuaternion()Get rotation in world space.
getWorldScale()Get scaling factors in world space.
getWorldDirection()Get positive z-axis in world space.
lookAt()Rotates the object to face a point in world space.
add()Adds an object as child of this object.
remove()Removes an object as child of this object.
removeFromParent()Removes this object from its current parent.
clear()Removes all child objects.
getObjectByName()Get the first child with a matching name.
traverse()Executes the callback on this object and all descendants.
-

Constructors

-

Object3D()

-

Object3D()

-

Can be created to group 3D objects together.

-

Properties

-

name

-

.name: String

-

Readable and writable. Default is an empty string.

-

isBuilding

-

.isBuilding: Boolean

-

The engine uses a separate shadow-map for buildings which updates at a lower rate.

-

isBuilding marks whether the object is part of the buildings.

-

Readable and writable. Default is false.

-

moved

-

.moved: Boolean

-

The engine uses a separate shadow-map for buildings which updates at a lower rate.

-

moved marks whether the object has been moved since last time the shadow-map is updated.

-

Readable and writable. Default is true.

-

parent

-

.parent: Object3D

-

Object's parent in the scene graph.

-

Readable and writable.

-

children

-

.children: Array

-

Array with object's children.

-

Read-only. Use methods like add(), remove() to modify this property.

-

up

-

.up: Object

-

This is used by the lookAt method, for example, to determine the orientation of the result.

-

Read-only. Use method setUp() to modify this property.

-

Default is {x: 0, y: 1, z: 0}.

-

position

-

.position: Object

-

A Vector3 representing the object's local position

-

Read-only. Use method setPosition() to modify this property.

-

Default is {x: 0, y: 0, z: 0}.

-

rotation

-

.rotation: Object

-

Object's local rotation, Euler angles in radians.

-

Read-only. Use method setRotation() to modify this property.

-

quaternion

-

.quaternion: Object

-

Object's local rotation as a Quaternion.

-

Read-only. Use method setQuaternion() to modify this property.

-

scale

-

.scale: Object

-

The object's local scale.

-

Default is {x: 1, y: 1, z: 1}.

-

Read-only. Use method setScale() to modify this property.

-

matrix

-

.matrix: Object

-

The local transform matrix.

-

Read-only.

-

matrixWorld

-

.matrixWorld: Object

-

The global transform of the object. If the Object3D has no parent, then it's identical to the local transform .matrix.

-

Read-only.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

getUp()

-

.getUp(vector: Vector3): Vector3

-

Copy the value of .up into vector.

-

setUp()

-

.setUp(vector: Vector3): undefined

-

Set the value of .up according to vector.

-

.setUp(x: Number, y: Number, z: Number ): undefined

-

Set the value of .up according to the x, y, z coordinates.

-

getPosition()

-

.getPosition(vector: Vector3): Vector3

-

Copy the value of .position into vector.

-

setPosition()

-

.setPosition(vector: Vector3): undefined

-

Set the value of .position according to vector.

-

.setPosition(x: Number, y: Number, z: Number ): undefined

-

Set the value of .position according to the x, y, z coordinates.

-

getRotation()

-

.getRotation(vector: Vector3): Vector3

-

Copy the value of .rotation into vector.

-

setRotation()

-

.setRotation(vector: Vector3): undefined

-

Set the value of .rotation according to vector.

-

.setRotation(x: Number, y: Number, z: Number ): undefined

-

Set the value of .rotation according to the x, y, z coordinates.

-

getQuaternion()

-

.getQuaternion(quaternion: Quaternion): Quaternion

-

Copy the value of .quaternion into quaternion.

-

setQuaternion()

-

.setQuaternion(quaternion: Quaternion): undefined

-

Set the value of.quaternion according to quaternion.

-

.setQuaternion(x: Number, y: Number, z: Number, w: Number ): undefined

-

Set the value of .quaternion according to the x, y, z, w coordinates.

-

getScale()

-

.getScale(vector: Vector3): Vector3

-

Copy the value of .scale into vector.

-

setScale()

-

.setScale(vector: Vector3): undefined

-

Set the value of .scale according to vector.

-

.setScale(x: Number, y: Number, z: Number ): undefined

-

Set the value of .scale according to the x, y, z coordinates.

-

getMatrix()

-

.getMatrix(matrix: Matrix4): Matrix4

-

Copy the value of .matrix into matrix.

-

getMatrixWorld()

-

.getMatrixWorld(matrix: Matrix4): Matrix4

-

Copy the value of .matrixWorld into matrix.

-

updateMatrix()

-

.updateMatrix(): undefined

-

Updates the local transform.

-

updateMatrixWorld()

-

.updateMatrixWorld(force : Boolean): undefined

-

Updates the global transform of the object and its descendants.

-

updateWorldMatrix()

-

.updateWorldMatrix(updateParents: Boolean, updateChildren: Boolean): undefined

-

Updates the global transform of the object and its descendants.

-

Parameters

-

updateParents: recursively updates global transform of ancestors.

-

updateChildren: recursively updates global transform of descendants.

-

applyMatrix4()

-

.applyMatrix4(matrix: Matrix4): this

-

Applies the matrix transform to the object and updates the object's position, rotation and scale.

-

applyQuaternion()

-

.applyQuaternion(quaternion: Quaternion): this

-

Applies the rotation represented by the quaternion to the object.

-

setRotationFromAxisAngle()

-

.setRotationFromAxisAngle(axis: Vector3, angle: Number ): undefined

-

Set the rotation from axis and angle.

-

Parameters

-

axis: A normalized vector in object space.

-

angle: angle in radians

-

setRotationFromMatrix()

-

.setRotationFromMatrix(m: Matrix4): undefined

-

Set the rotation from rotation matrix.

-

Parameters

-

m: rotate the quaternion by the rotation component of the matrix.

-

Note that this assumes that the upper 3x3 of m is a pure rotation matrix (i.e, unscaled).

-

rotateOnAxis()

-

.rotateOnAxis(axis: Vector3, angle: Number ) : this

-

Rotate an object along an axis in object space. The axis is assumed to be normalized.

-

Parameters

-

axis: A normalized vector in object space.

-

angle: The angle in radians.

-

rotateOnWorldAxis()

-

.rotateOnWorldAxis(axis: Vector3, angle: Number ) : this

-

Rotate an object along an axis in world space. The axis is assumed to be normalized. Method Assumes no rotated parent.

-

Parameters

-

axis: A normalized vector in object space.

-

angle: The angle in radians.

-

rotateX()

-

.rotateX(rad: Number ) : this

-

Rotates the object around x axis in local space.

-

Parameters

-

rad: the angle to rotate in radians.

-

rotateY()

-

.rotateY(rad: Number ) : this

-

Rotates the object around y axis in local space.

-

Parameters

-

rad: the angle to rotate in radians.

-

rotateZ()

-

.rotateZ(rad: Number ) : this

-

Rotates the object around z axis in local space.

-

Parameters

-

rad: the angle to rotate in radians.

-

translateOnAxis()

-

.translateOnAxis axis: Vector3, distance: Number ) : this

-

Translate an object by distance along an axis in object space. The axis is assumed to be normalized.

-

Parameters

-

axis: A normalized vector in object space.

-

distance: The distance to translate.

-

translateX()

-

.translateX(distance: Number ) : this

-

Translates object along x axis in object space by distance units.

-

translateY()

-

.translateY(distance: Number ) : this

-

Translates object along y axis in object space by distance units.

-

translateZ()

-

.translateZ(distance: Number ) : this

-

Translates object along z axis in object space by distance units.

-

localToWorld()

-

.localToWorld(vector: Vector3 ) : Vector3

-

Converts the vector from this object's local space to world space.

-

Parameters

-

vector: A vector representing a position in this object's local space.

-

worldToLocal()

-

.worldToLocal(vector: Vector3 ) : Vector3

-

Converts the vector from world space to this object's local space.

-

Parameters

-

vector: A vector representing a position in world space.

-

getWorldPosition

-

.getWorldPosition(target: Vector3 ) : Vector3

-

Returns a vector representing the position of the object in world space.

-

Parameters

-

target: the result will be copied into this Vector3.

-

getWorldQuaternion()

-

.getWorldQuaternion(target: Quaternion ) : Quaternion

-

Returns a quaternion representing the rotation of the object in world space.

-

Parameters

-

target: the result will be copied into this Quaternion.

-

getWorldScale()

-

.getWorldScale(target: Vector3 ) : Vector3

-

Returns a vector of the scaling factors applied to the object for each axis in world space.

-

Parameters

-

target: the result will be copied into this Vector3.

-

getWorldDirection()

-

.getWorldDirection(target: Vector3 ) : Vector3

-

Returns a vector representing the direction of object's positive z-axis in world space.

-

Parameters

-

target: the result will be copied into this Vector3.

-

lookAt()

-

Rotates the object to face a point in world space.

-

This method does not support objects having non-uniformly-scaled parent(s).

-

.lookAt(vector : Vector3 ) : undefined

-

World space position as a Vector3.

-

.lookAt(x: Number, y: Number, z: Number ) : undefined

-

World space position as x, y and z components.

-

add()

-

.add(object: Object3D) : this

-

Adds an object as child of this object. Any current parent on the object passed in here will be removed, since an object can have at most one parent.

-

remove()

-

.remove(object: Object3D) : this

-

Removes an object as child of this object.

-

removeFromParent()

-

.removeFromParent() : this

-

Removes this object from its current parent.

-

clear()

-

.clear() : this

-

Removes all child objects.

-

getObjectByName()

-

.getObjectByName(name: String ) : Object3D

-

Searches through an object and its children, starting with the object itself, and returns the first with a matching name. -Note that for most objects the name is an empty string by default. You will have to set it manually to make use of this method.

-

Parameters

-

name: String to match to the children's Object3D.name property.

-

traverse()

-

.traverse(callback: Function ) : undefined

-

Executes the callback on this object and all descendants. -Note: Modifying the scene graph inside the callback is discouraged.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/OpusPlayer.html b/GameDev/bin/Release/help/api/OpusPlayer.html deleted file mode 100644 index 99a36abe..00000000 --- a/GameDev/bin/Release/help/api/OpusPlayer.html +++ /dev/null @@ -1,1292 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class OpusPlayer

-

Play back a raw opus stream.

-

class OpusPlayer

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
OpusPlayer()Creates an opus-player.
Methods
dispose()Dispose the unmanaged resource.
addPacket()Add an opus packet to the play queue.
-

Constructors

-

OpusRecorder()

-

OpusPlayer(id_device: Number)

-

Creates an opus-player.

-

Parameters

-

id_device : index of the audio output device

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

addPacket()

-

.addPacket(data: ArrayBuffer): undefined

-

Add an opus packet to the play queue.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/OpusRecorder.html b/GameDev/bin/Release/help/api/OpusRecorder.html deleted file mode 100644 index 48b39ecc..00000000 --- a/GameDev/bin/Release/help/api/OpusRecorder.html +++ /dev/null @@ -1,1298 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class OpusRecorder

-

Record from an audio device and encode as a raw opus stream.

-

class OpusRecorder

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
OpusRecorder()Creates an opus-recorder.
Properties
callbackCallback function for recieving opus packets.
Methods
dispose()Dispose the unmanaged resource.
-

Constructors

-

OpusRecorder()

-

OpusRecorder(id_device: Number)

-

Creates an opus-recorder.

-

Parameters

-

id_device : index of the audio input device

-

Properties

-

callback

-

.callback: Function - .callback(data: ArrayBuffer): undefined

-

Callback function for recieving opus packets.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Parrot.png b/GameDev/bin/Release/help/api/Parrot.png deleted file mode 100644 index e57494be..00000000 Binary files a/GameDev/bin/Release/help/api/Parrot.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/PerspectiveCamera.html b/GameDev/bin/Release/help/api/PerspectiveCamera.html deleted file mode 100644 index 046e111d..00000000 --- a/GameDev/bin/Release/help/api/PerspectiveCamera.html +++ /dev/null @@ -1,1338 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class PerspectiveCamera

-

class PerspectiveCamera extends Camera

-

Inheritance Object3D --> Camera --> PerspectiveCamera

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
PerspectiveCamera()Creates a perspective Camera.
Properties
isPerspectiveCameraChecks if the object is PerspectiveCamera
fovCamera frustum vertical field of view
aspectCamera frustum aspect ratio
nearCamera frustum near plane
farCamera frustum far plane
Methods
updateProjectionMatrixUpdates the camera projection matrix.
-

Constructors

-

PerspectiveCamera()

-

PerspectiveCamera(fov: Number, aspect: Number, near: Number, far: Number)

-

Creates a perspective camera.

-

Parameters

-

fov: Camera frustum vertical field of view.

-

aspect: Camera frustum aspect ratio.

-

near: Camera frustum near plane.

-

far: Camera frustum far plane.

-

Together these define the camera's viewing frustum.

-

Properties

-

See the base Camera class for common properties. -Note that after making changes to most of these properties you will have to call .updateProjectionMatrix for the changes to take effect.

-

isPerspectiveCamera

-

.isPerspectiveCamera: Boolean

-

Read-only flag to check if a given object is of type PerspectiveCamera.

-

fov

-

.fov: Number

-

Camera frustum vertical field of view, from bottom to top of view, in degrees. Default is 50.

-

Readable and writable.

-

aspect

-

.aspect: Number

-

Camera frustum aspect ratio, usually the canvas width / canvas height. Default is 1 (square canvas).

-

Readable and writable.

-

near

-

.near: Number

-

Camera frustum near plane. Default is 0.1.

-

The valid range is greater than 0 and less than the current value of the far plane.

-

Readable and writable.

-

far

-

.far: Numbers

-

Camera frustum far plane. Default is 200.

-

Must be greater than the current value of near plane.

-

Readable and writable.

-

Methods

-

See the base Camera class for common methods.

-

updateProjectionMatrix()

-

.updateProjectionMatrix(): undefined

-

Updates the camera projection matrix. Must be called after any change of parameters.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/ProbeGrid.html b/GameDev/bin/Release/help/api/ProbeGrid.html deleted file mode 100644 index 38813326..00000000 --- a/GameDev/bin/Release/help/api/ProbeGrid.html +++ /dev/null @@ -1,1723 +0,0 @@ - - - - - - - - - - - - - - -

For a quick walkthrough of what can be done in a Three.V8 user script, see Features.

-

For details of the APIs that enable the features, see below.

-

Three.V8 User Script APIs

-

The user script APIs consist of

-
    -
  • Engine Classes: have properties and methods to communicate with engine objects.
  • -
  • Global Functions: can be called directly from user script.
  • -
  • Global Objects: are special engine objects which are preexisting in the context rather than created by the user script.
  • -
  • Callback Functions: are used by user script to recieve the event calls from the host program.
  • -
-

Engine Classes (3D)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Class NameDescription
ImageRepresents an image that resides in CPU memory.
CubeImageRepresents a cubemap image that resides in CPU memory.
DDSImageRepresents a dds-image that resides in CPU memory.
HDRImageRepresents a HDR image that resides in CPU memory.
HDRCubeImageRepresents a HDR cubemap image that resides in CPU memory.
Object3DBase class of all 3D objects visible to user script.
CameraBase class for cameras.
PerspectiveCameraPerspective camera
BackroundAbstract class for all backgrounds
ColorBackgroundA background that has a monotone color.
CubeBackgroundA background using a CubeMap.
HemisphereBackgroundA background that has a sky color and a ground color.
BackgroundSceneUse another scene as background.
LightAbstract class for all direct lights.
DirectionalLightA light that gets emitted in a specific direction.
IndirectLightAbstract class for all indirect lights
EnvironmentMapImage based indirect light
EnvironmentMapCreatorCube-map filter that generates environmaps
AmbientLightUniform indirect light
HemisphereLightGradient indirect light
ProbeGridAn uniform grid of light-probes
SimpleModelA Model containing a single simple geometry
GLTFModelA Model that has a GLTF style internal structure.
Scene3D Object collection for rendering
FogRepresents the particle substance in the air
GLRendererManages rendering routines, including shaders
GLRenderTargetAn off-screen render target.
CubeRenderTargetA cubemap render target.
BoundingVolumeHierarchyAcceleration structure for ray-casting.
GamePlayerWrapper for the host GamePlayer object.
FileLoaderProvides a few interfaces to loading local files.
ImageLoaderProvides a few interfaces to load images.
DDSImageLoaderProvides a few interfaces to load dds-images.
HDRImageLoaderProvides a few interfaces to load HDR images.
GLTFLoaderProvides a few interfaces to load GLTF models.
ImageSaverProvides a few interfaces to save images. (PC only)
-

Engine Classes (Network)

- - - - - - - - - - - -
Class NameDescription
HttpClientProvides a few interfaces to make HTTP requests.
-

Engine Classes (GUI)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Class NameDescription
UIManagerManages UIArea objects.
UIAreaManages UIElement objects and UI3DViewer objects.
UIElementAbstract base class of all ui-elements.
UIBlockBase class for all ui-elements containing other ui-elements.
UIPanelA visible ui-block.
UIButtonA clickable ui-block.
UIScrollViewerA scrollable ui-block.
UIImageImage element in a UI.
UITextNon-editable text element in a UI.
UITextBlockNon-editable multi-lined text element in a UI.
UILineEditEditable text box in a UI.
UI3DViewerObject for embedding a 3D view in a UI.
-

Engine Classes (Multimedia)

- - - - - - - - - - - - - - - - - - - - - - - -
Class NameDescription
MMCameraRepresents an image source from a web-camera.
MMLazyVideoRepresents an image source from a video-file.
MMVideoRepresents a background video-file player.
MMAudioRepresents a background audio-file player.
-

Global Functions

-

These are functions that can be called directly in user script.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function NameDescription
print()Print strings to stdout
setCallback()Register a callback function.
now()Current time in milliseconds.
getGLError()Get the last OpenGL error code for debugging.
getListOfCameras()Get a list of camera device names.
getListOfAudioPlaybackDevices()Get a list of audio playback device names.
-

print()

-

print(text1: String, text2: String, ...): undefined

-

Print strings to stdout separated by spaces. Objects are not stringified automatically. To do that you need JSON.stringify().

-

setCallback()

-

setCallback(name: String, callback: Function): undefined

-

Register a callback function.

-

Parameters

-

name: one of the names listed in Callback Functions.

-

callback: function accessable from script, or lambda.

-

now()

-

now(): Number

-

Current time in milliseconds.

-

getGLError()

-

getGLError(): Number

-

Get the last OpenGL error code for debugging.

-

getListOfCameras()

-

getListOfCameras(): Array

-

Get a list of camera device names.

-

getListOfAudioPlaybackDevices()

-

getListOfAudioPlaybackDevices(): Array

-

Get a list of audio playback device names.

-

Global Objects

-

These are engine class singletons that can be used directly in user script.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Object NameDescription
gamePlayerInstance of GamePlayer.
fileLoaderInstance of FileLoader.
imageLoaderInstance of ImageLoader.
DDSImageLoaderInstance of DDSImageLoader.
HDRImageLoaderInstance of HDRImageLoader.
gltfLoaderInstance of GLTFLoader.
imageSaverInstance of ImageSaver.
httpInstance of HttpClient.
UIManagerInstance of UIManager.
-

Callback Functions

-

User scripts are event driven programs. Callback functions need to be registered in the global scope by calling setCallback.

-

The host program calls these functions at specific events according to their names.

-

The following callback functions are called by the default "GamePlayer".

-

Mouse callbacks are specific to desktop while touch callbacks are specific to mobile devices.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Callback nameDescription
init()Called immediately after loading the script.
dispose()Called before unloading the script.
render()Called when rendering a video frame.
OnMouseDown()Called when mouse button is pressed down.
OnMouseUp()Called when mouse button is up.
OnMouseMove()Called when mouse pointer is moved.
OnMouseWheel()Called when mouse wheel is moved.
OnTouchDown()Called when user touches screen.
OnTouchUp()Called when user stops touching screen.
OnTouchMove()Called when user moves on touch screen.
-

init()

-

init(width: Number, height: Number): undefined

-

Called immediately after loading the script.

-

Parameters

-

width: width of the container window.

-

height: height of the container window.

-

dispose()

-

dispose(): undefined

-

Called before unloading the script.

-

render()

-

render(width: Number, height: Number, sizeChanged: Boolean): undefined

-

Called when rendering a video frame.

-

Parameters

-

width: width of the container window.

-

height: height of the container window.

-

sizeChanged: if size of windows has changed.

-

OnMouseDown()

-

OnMouseDown(e: Object): undefined

-

Called when mouse button is pressed down.

-

Parameters

-

e: has the following properties:

-

e.x: Number

-

x coordinate of mouse pointer

-

e.y: Number

-

y coordinate of mouse pointer

-

e.delta: Number

-

wheel delta

-

e.button: Number

-

0 = Left Button

-

1 = Middle Button

-

2 = Right Button

-

3 = XButton1

-

4 = XButton2

-

OnMouseUp()

-

OnMouseUp(e: Object): undefined

-

Called when mouse button is up.

-

The parameter e has the same structure as in OnMouseDown()

-

OnMouseMove()

-

OnMouseMove(e: Object): undefined

-

Called when mouse pointer is moved.

-

The parameter e has the same structure as in OnMouseDown()

-

OnMouseWheel()

-

OnMouseWheel(e: Object): undefined

-

Called when mouse wheel is moved.

-

The parameter e has the same structure as in OnMouseDown()

-

OnTouchDown()

-

OnTouchDown(e: Object): undefined

-

Called when user touches screen.

-

Parameters

-

e: has the following properties:

-

pointerId: Number

-

Identifier for distinguishing multiple touch points.

-

x: number

-

x coordinate of touch point.

-

y: number

-

y coordinate of touch point.

-

OnTouchUp()

-

OnTouchUp(e: Object): undefined

-

Called when user stops touching screen.

-

The parameter e has the same structure as in OnTouchDown()

-

OnTouchMove()

-

OnTouchMove(e: Object): undefined

-

Called when user moves on touch screen.

-

The parameter e has the same structure as in OnTouchDown()

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/ProbeGridLoader.html b/GameDev/bin/Release/help/api/ProbeGridLoader.html deleted file mode 100644 index 43b180c1..00000000 --- a/GameDev/bin/Release/help/api/ProbeGridLoader.html +++ /dev/null @@ -1,1279 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class ProbeGridLoader

-

Provides a few interfaces to load a ProbeGrid from local files or from memory.

-

No constructor, exposed as a global object probeGridLoader.

-

class ProbeGridLoader

- - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
loadFile()Load a probe-grid from a local file.
loadMemory()Load a probe-grid from a memory buffer.
-

Methods

-

loadFile()

-

.loadFile(name: String): ProbeGrid

-

Load a probe-grid from a local file.

-

loadMemory()

-

.loadMemory(buf: ArrayBuffer): ProbeGrid

-

Load a probe-grid from a memory buffer.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Scene.html b/GameDev/bin/Release/help/api/Scene.html deleted file mode 100644 index 0bbc38fc..00000000 --- a/GameDev/bin/Release/help/api/Scene.html +++ /dev/null @@ -1,1316 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Scene

-

Scenes allow you to set up what and where is to be rendered by Three.V8. This is where you place objects, lights and cameras.

-

class Scene extends Object3D

-

Inheritance Object3D --> Scene

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
Scene()Creates a new Scene.
Properties
backgroundObject used as background
indirectLightObject used as the indirect light-source.
fogObject representing the particle substance in the air.
Methods
getBoundingBoxGet the bounding-box of the whole scene
-

Constructors

-

Scene()

-

Scene()

-

Create a new scene object.

-

Properties

-

See the base Object3D class for common properties.

-

background

-

.background: Background

-

Object used as background.

-

Readable and writable.

-

indirectLight

-

.indirectLight: IndirectLight

-

Object used as the indirect light-source.

-

Readable and writable.

-

fog

-

.fog: Fog

-

Object representing the particle substance in the air.

-

Readable and writable.

-

Methods

-

See the base Object3D class for common methods.

-

getBoundingBox()

-

.getBoundingBox() : Object

-

Get the bounding-box of the whole scene.

-

The returned object contains a 'minPos' property and a 'maxPos' property, each of which is a Vector3.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/SimpleModel.html b/GameDev/bin/Release/help/api/SimpleModel.html deleted file mode 100644 index 83b7d3ef..00000000 --- a/GameDev/bin/Release/help/api/SimpleModel.html +++ /dev/null @@ -1,1370 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class SimpleModel

-

A Model containing a single simple geometry.

-

class SimpleModel extends Object3D

-

Inheritance Object3D --> SimpleModel

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
SimpleModel()Creates a new SimpleModel.
Properties
colorBase-color of the material of the model.
metalnessMetalness factor of the material of the model.
roughnessRoughness factor of the material of the model.
Methods
createBoxCreate a Box shaped geometry for the model.
createSphereCreate a Sphere shaped geometry for the model.
createPlaneCreate a Plane shaped geometry for the model.
getColorGet the value of .color.
setColorSet the value of .color.
setColorTextureSet a texture image as the base color map of the model.
-

Constructors

-

SimpleModel()

-

Creates a new SimpleModel.

-

Properties

-

See the base Object3D class for common properties.

-

color

-

.color: Object

-

Base-color of the material of the model.

-

Read-only. Use the method .setColor to modify this property.

-

metalness

-

.metalness: Number

-

Metalness factor of the material of the model.

-

Readable and writable.

-

roughness

-

.roughness: Number

-

Roughness factor of the material of the model.

-

Readable and writable.

-

Methods

-

See the base Object3D class for common methods.

-

createBox()

-

.createBox(width: Number, height: Number, depth: Number): undefined

-

Create a Box shaped geometry for the model.

-

Parameters

-

width: width of the Box

-

height: height of the Box

-

depth: depth of the Box

-

createSphere()

-

.createSphere(radius: Number, widthSegments: Number, heightSegments: Number): undefined

-

Create a Sphere shaped geometry for the model.

-

Parameters

-

radius: radius of the Sphere

-

widthSegments: number of width segments of the triangulated Sphere.

-

heightSegments: number of height segments of the triangulated Sphere.

-

createPlane()

-

.createPlane(width: Number, height: Number): undefined

-

Create a Plane shaped geometry for the model.

-

Parameters

-

width: width of the Plane

-

height: height of the Plane

-

getColor()

-

.getColor(color: Vector3) : Vector3

-

Copy the value of .color into color.

-

setColor()

-

.setColor(color: Vector3): undefined

-

Set the value of .color according to color.

-

.setColor(r: Number, g: Number, b: Number ): undefined

-

set the value of .color according to the r, g, b values.

-

setColorTexture()

-

.setColorTexture(image: Image): undefined

-

Set a texture image as the base color map of the model.

-

.setColorTexture(target: GLRenderTarget): undefined

-

Use a rendering result as the base color map of the model.

-

.setColorTexture(mmcamera: MMCamera): undefined

-

Usa a web-camera image source as the base color map of the model.

-

.setColorTexture(mmlazyvideo: MMLazyVideo): undefined

-

Usa a video-file image source as the base color map of the model.

-

.setColorTexture(mmvideo: MMVideo): undefined

-

Usa a video-file player as the base color map of the model.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/Text.html b/GameDev/bin/Release/help/api/Text.html deleted file mode 100644 index 32645bdc..00000000 --- a/GameDev/bin/Release/help/api/Text.html +++ /dev/null @@ -1,1279 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class Text

-

Provides a few interfaces for text conversion.

-

No constructor, exposed as a global object text.

-

class Text

- - - - - - - - - - - - - - - - - - - -
NameDescription
Methods
toUTF8Buffer()Convert string to ArrayBuffer of utf8 code.
fromUTF8Buffer()Convert ArrayBuffer of utf8 code to string.
-

Methods

-

toUTF8Buffer()

-

.toUTF8Buffer(text: String): ArrayBuffer

-

Convert string to ArrayBuffer of utf8 code.

-

fromUTF8Buffer()

-

.fromUTF8Buffer(buf: ArrayBuffer): String

-

Convert ArrayBuffer of utf8 code to string.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UI3DViewer.html b/GameDev/bin/Release/help/api/UI3DViewer.html deleted file mode 100644 index 0e0282e7..00000000 --- a/GameDev/bin/Release/help/api/UI3DViewer.html +++ /dev/null @@ -1,1430 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UI3DViewer

-

Object for embedding a 3D view in a UI.

-

class UI3DViewer

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UI3DViewer()Creates a new UI3DViewer.
Properties
blockThe block element to which this ui-3dviewer belongs.
originA Vector2 representing the ui-3dviewer's position.
sizeA Vector2 representing the ui-3dviewer's size.
onRenderCallback function triggered by UIManager during UI rendering.
onMouseDownCallback function passed by UIManager during UI input handling.
onMouseUpCallback function passed by UIManager during UI input handling.
onMouseMoveCallback function passed by UIManager during UI input handling.
onMouseWheelCallback function passed by UIManager during UI input handling.
onTouchDownCallback function passed by UIManager during UI input handling.
onTouchUpCallback function passed by UIManager during UI input handling.
onTouchMoveCallback function passed by UIManager during UI input handling.
Methods
dispose()Dispose the unmanaged resource.
getOrigin()Get the value of .origin
setOrigin()Set the value of .origin
getSize()Get the value of .size
setSize()Set the value of .size
-

Constructors

-

UI3DViewer()

-

UI3DViewer()

-

Creates a new UI3DViewer.

-

Properties

-

block

-

.block: UIBlock

-

The block element to which this ui-3dviewer belongs.

-

When there is a valid block element, this ui-3dviewer is translated and clipped according the its block element.

-

Readable and writable.

-

Default is null.

-

origin

-

.origin: Object

-

A Vector2 representing the ui-3dviewer's position.

-

Read-only. Use method setOrigin() to modify this property.

-

Default is {x: 0, y: 0}.

-

onRender

-

.onRender: Function

-

Callback function triggered by UIManager during UI rendering.

-

Signature: onRender(width: Number, height: Number, size_changed: Boolean):undefined

-

Readable and writable.

-

Default is null.

-

onMouseDown

-

.onMouseDown: Function

-

Callback function passed by UIManager during UI input handling.

-

Signature: onMouseDown(e: Object): undefined

-

The parameter e has the same structure as in the global callback OnMouseDown()

-

Readable and writable.

-

Default is null.

-

onMouseUp

-

.onMouseUp: Function

-

Callback function passed by UIManager during UI input handling.

-

Signature: onMouseUp(e: Object): undefined

-

The parameter e has the same structure as in the global callback OnMouseDown()

-

Readable and writable.

-

Default is null.

-

onMouseMove

-

.onMouseMove: Function

-

Callback function passed by UIManager during UI input handling.

-

Signature: onMouseMove(e: Object): undefined

-

The parameter e has the same structure as in the global callback OnMouseDown()

-

Readable and writable.

-

Default is null.

-

onMouseWheel

-

.onMouseWheel: Function

-

Callback function passed by UIManager during UI input handling.

-

Signature: onMouseWheel(e: Object): undefined

-

The parameter e has the same structure as in the global callback OnMouseDown()

-

Readable and writable.

-

Default is null.

-

onTouchDown

-

.onTouchDown: Function

-

Callback function passed by UIManager during UI input handling.

-

Signature: onTouchDown(e: Object): undefined

-

The parameter e has the same structure as in the global callback OnTouchDown()

-

Readable and writable.

-

Default is null.

-

onTouchUp

-

.onTouchUp: Function

-

Callback function passed by UIManager during UI input handling.

-

Signature: onTouchUp(e: Object): undefined

-

The parameter e has the same structure as in the global callback OnTouchDown()

-

Readable and writable.

-

Default is null.

-

onTouchMove

-

.onTouchMove: Function

-

Callback function passed by UIManager during UI input handling.

-

Signature: onTouchMove(e: Object): undefined

-

The parameter e has the same structure as in the global callback OnTouchDown()

-

Readable and writable.

-

Default is null.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

getOrigin()

-

.getOrigin(vector: Vector2): Vector2

-

Copy the value of .origin into vector.

-

setOrigin()

-

.setOrigin(vector: Vector2): undefined

-

Set the value of .origin according to vector.

-

.setOrigin(x: Number, y: Number ): undefined

-

Set the value of .origin according to the x, y coordinates.

-

getSize()

-

.getSize(vector: Vector2): Vector2

-

Copy the value of .size into vector.

-

setSize()

-

.setSize(vector: Vector2): undefined

-

Set the value of .size according to vector.

-

.setSize(x: Number, y: Number ): undefined

-

Set the value of .size according to the x, y coordinates.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIArea.html b/GameDev/bin/Release/help/api/UIArea.html deleted file mode 100644 index 2a25a823..00000000 --- a/GameDev/bin/Release/help/api/UIArea.html +++ /dev/null @@ -1,1409 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIArea

-

Manages UIElement objects and UI3DViewer objects.

-

Provides a framebuffer for rendering ui-elements. Also keeps a scaling record.

-

UIElement objects are rendered first, then UI3DViewer objects are rendered above all ui-elements at a higher-frequency.

-

class UIArea

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIArea()Creates an UIArea.
Properties
elementsArray of UIElement objects managed by this ui-area.
viewersArray of UI3DViewer objects managed by this ui-area.
originA Vector2 representing the ui-area's position.
sizeA Vector2 representing the ui-area's size.
scaleScale factor of the ui-area.
Methods
dispose()Dispose the unmanaged resource.
add()Adds an ui-element to this ui-area.
remove()Removes an ui-element from this ui-area.
clear()Removes all ui-elements from this ui-area.
addViewer()Adds an ui-3dviewer to this ui-area.
removeViewer()Removes an ui-3dviewer from this ui-area.
clearViewer()Removes all ui-3dviewers from this ui-area.
getOrigin()Get the value of .origin
setOrigin()Set the value of .origin
getSize()Get the value of .size
setSize()Set the value of .size
-

Constructors

-

UIArea()

-

UIArea()

-

Creates an UIArea.

-

Properties

-

elements

-

.elements: Array

-

Array of UIElement objects managed by the ui-area.

-

Read-only.

-

viewers

-

.viewers: Array

-

Array of UI3DViewer objects managed by the ui-area.

-

Read-only.

-

origin

-

.origin: Object

-

A Vector2 representing the ui-area's position.

-

Scaled by .scale.

-

Read-only. Use method setOrigin() to modify this property.

-

Default is {x: 0, y: 0}.

-

size

-

.size: Object

-

A Vector2 representing the ui-area's size.

-

Scaled by .scale.

-

Read-only. Use method setSize() to modify this property.

-

Default is {x: 0, y: 0}.

-

scale

-

.scale: Number

-

Scale factor of the ui-area.

-

Readable and writable.

-

Default is 1.0.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

add()

-

.add(elem: UIElement): this

-

Adds an ui-element to this ui-area.

-

remove()

-

.remove(elem: UIElement): this

-

Removes an ui-element from the ui-area.

-

clear()

-

.clear(): this

-

Removes all ui-elements from the ui-area.

-

addViewer()

-

.addViewer(viewer: UI3DViewer): this

-

Adds an ui-3dviewer to this ui-area.

-

removeViewer()

-

.removeViewer(viewer: UI3DViewer): this

-

Removes an ui-3dviewer from the ui-area.

-

clearViewer()

-

.clearViewer(): this

-

Removes all ui-3dviewers from the ui-area.

-

getOrigin()

-

.getOrigin(vector: Vector2): Vector2

-

Copy the value of .origin into vector.

-

setOrigin()

-

.setOrigin(vector: Vector2): undefined

-

Set the value of .origin according to vector.

-

.setOrigin(x: Number, y: Number ): undefined

-

Set the value of .origin according to the x, y coordinates.

-

getSize()

-

.getSize(vector: Vector2): Vector2

-

Copy the value of .size into vector.

-

setSize()

-

.setSize(vector: Vector2): undefined

-

Set the value of .size according to vector.

-

.setSize(x: Number, y: Number ): undefined

-

Set the value of .size according to the x, y coordinates.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIBlock.html b/GameDev/bin/Release/help/api/UIBlock.html deleted file mode 100644 index 9ba95f1b..00000000 --- a/GameDev/bin/Release/help/api/UIBlock.html +++ /dev/null @@ -1,1319 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIBlock

-

Base class for all ui-elements containing other ui-elements.

-

class UIBlock extends UIElement

-

Inheritance UIElement --> UIBlock

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIBlock()Creates a new UIBlock.
Properties
sizeA Vector2 representing the ui-block's size.
scissorEnabledIndicating whether the containing ui-elements are clipped .
Methods
getSize()Get the value of .size
setSize()Set the value of .size
-

Constructors

-

UIBlock()

-

UIBlock()

-

Creates a new UIBlock.

-

A UIBlock is not rendered by default. It only applies transformations and clipping to the ui-elements it contains.

-

Properties

-

See the base UIElement class for common properties.

-

size

-

.size: Object

-

A Vector2 representing the ui-block's size.

-

Read-only. Use method setSize() to modify this property.

-

Default is {x: 100, y: 40}.

-

scissorEnabled

-

.scissorEnabled: Boolean

-

Indicating whether the containing ui-elements are clipped by this ui-block.

-

Readable and writable.

-

Dafault is true.

-

Methods

-

See the base UIElement class for common methods.

-

getSize()

-

.getSize(vector: Vector2): Vector2

-

Copy the value of .size into vector.

-

setSize()

-

.setSize(vector: Vector2): undefined

-

Set the value of .size according to vector.

-

.setSize(x: Number, y: Number ): undefined

-

Set the value of .size according to the x, y coordinates.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIButton.html b/GameDev/bin/Release/help/api/UIButton.html deleted file mode 100644 index bd21a216..00000000 --- a/GameDev/bin/Release/help/api/UIButton.html +++ /dev/null @@ -1,1320 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIButton

-

A clickable ui-block

-

class UIButton extends UIBlock

-

Inheritance UIElement --> UIBlock --> UIButton

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIButton()Creates a new UIButton.
Properties
onClickCallback function triggered when the button is clicked.
onLongPressCallback function triggered when the button is long-pressed.
Methods
setStyle()Set the displaying style of the ui-button.
-

Constructors

-

UIButton()

-

UIButton()

-

Creates a new UIButton.

-

Properties

-

See the base UIBlock class for common properties.

-

onClick

-

.onClick: Function

-

Callback function triggered when the button is clicked.

-

Signature: onClick():undefined

-

Readable and writable.

-

Default is null.

-

onLongPress

-

.onLongPress: Function

-

Callback function triggered when the button is long-pressed.

-

Signature: onLongPress():undefined

-

Readable and writable.

-

Default is null.

-

Methods

-

See the base UIBlock class for common methods.

-

setStyle()

-

.setStyle(style: Object): undefined

-

Set the displaying style of the ui-button.

-

style may have the following properties:

-

style.cornerRadius: Number

-

Corner radius of the rounded rectangle.

-

style.strokeWidth: Number

-

Line-width of the stroke.

-

style.colorBg: String

-

Background color of the panel.

-

style.colorStroke: String

-

Stroke color of the panel.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIDraggable.html b/GameDev/bin/Release/help/api/UIDraggable.html deleted file mode 100644 index 3b4c378b..00000000 --- a/GameDev/bin/Release/help/api/UIDraggable.html +++ /dev/null @@ -1,1385 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIDraggable

-

A draggable ui-panel.

-

class UIDraggable extends UIPanel

-

Inheritance UIElement --> UIBlock --> UIPanel --> UIDraggable

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIDraggable()Creates a new UIDraggable.
Properties
draggableHorizontalIf the panel is draggable in horizontal direction.
draggableVerticalIf the panel is draggable in vertical direction.
originMinMinimum position for origin.
originMaxMaximum position for origin.
valueValue corresponding to current position.
onDragCallback functions called when the element is dragged.
Methods
getOriginMin()Get the value of .originMin
setOriginMin()Set the value of .originMin
getOriginMax()Get the value of .originMax
setOriginMax()Set the value of .originMax
getValue()Get the value of .value
setValue()Set the value of .value
-

Constructors

-

UIDraggable()

-

UIDraggable()

-

Creates a new UIDraggable.

-

Properties

-

See the base UIPanel class for common properties.

-

draggableHorizontal

-

.draggableHorizontal: Boolean

-

Indicating if the panel is draggable in horizontal direction

-

Readable and writable.

-

Dafault is true.

-

draggableVertical

-

.draggableVertical: Boolean

-

Indicating if the panel is draggable in vertical direction.

-

Readable and writable.

-

Dafault is false.

-

originMin

-

.originMin: Object

-

A Vector2 representing the minimum position for origin.

-

Read-only. Use method setOriginMin() to modify this property.

-

Default is {x: 0, y: 0}.

-

originMax

-

.originMax: Object

-

A Vector2 representing the maximum position for origin.

-

Read-only. Use method setOriginMax() to modify this property.

-

Default is {x: 0, y: 0}.

-

value

-

.value: Object

-

A Vector2 representing the value corresponding to current position.

-

Read-only. Use method setValue() to modify this property.

-

Default is {x: 0, y: 0}.

-

onDrag

-

.onDrag: Function - .onDrag(x: Number, y: Number): undefined

-

Callback functions called when the element is dragged.

-

Methods

-

See the base UIPanel class for common methods.

-

getOriginMin()

-

.getOriginMin(vector: Vector2): Vector2

-

Copy the value of .originMin into vector.

-

setOriginMin()

-

.setOriginMin(vector: Vector2): undefined

-

Set the value of .originMin according to vector.

-

.setOriginMin(x: Number, y: Number ): undefined

-

Set the value of .originMin according to the x, y coordinates.

-

getOriginMax()

-

.getOriginMax(vector: Vector2): Vector2

-

Copy the value of .originMax into vector.

-

setOriginMax()

-

.setOriginMax(vector: Vector2): undefined

-

Set the value of .originMax according to vector.

-

.setOriginMax(x: Number, y: Number ): undefined

-

Set the value of .originMax according to the x, y coordinates.

-

getValue()

-

.getValue(vector: Vector2): Vector2

-

Copy the value of .value into vector.

-

setValue()

-

.setValue(vector: Vector2): undefined

-

Set the value of .value according to vector.

-

.setValue(x: Number, y: Number ): undefined

-

Set the value of .value according to the x, y coordinates.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIElement.html b/GameDev/bin/Release/help/api/UIElement.html deleted file mode 100644 index 2d1f928e..00000000 --- a/GameDev/bin/Release/help/api/UIElement.html +++ /dev/null @@ -1,1336 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIElement

-

Abstract base class of all ui-elements.

-

No contructor, never used directly.

-

class UIElement

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Properties
blockThe block element to which this ui-element belongs.
originA Vector2 representing the ui-element's position.
onPointerDownCallback functions called when pointer is down on the element
onPointerUpCallback functions called when pointer is up on the element
onPointerMoveCallback functions called when pointer is moved on the element
Methods
dispose()Dispose the unmanaged resource.
getOrigin()Get the value of .origin
setOrigin()Set the value of .origin
-

Properties

-

block

-

.block: UIBlock

-

The block element to which this ui-element belongs.

-

When there is a valid block element, this element is translated and clipped according the its block element.

-

Readable and writable.

-

Default is null.

-

origin

-

.origin: Object

-

A Vector2 representing the ui-element's position.

-

Read-only. Use method setOrigin() to modify this property.

-

Default is {x: 0, y: 0}.

-

onPointerDown

-

.onPointerDown: Function - .onPointerDown(x: Number, y: Number): undefined

-

Callback functions called when pointer is down on the element.

-

onPointerUp

-

.onPointerUp: Function - .onPointerUp(x: Number, y: Number): undefined

-

Callback functions called when pointer is up on the element.

-

onPointerMove

-

.onPointerMove: Function - .onPointerMove(x: Number, y: Number): undefined

-

Callback functions called when pointer is moved on the element.

-

Methods

-

dispose()

-

.dispose(): undefined

-

Dispose the unmanaged resource.

-

getOrigin()

-

.getOrigin(vector: Vector2): Vector2

-

Copy the value of .origin into vector.

-

setOrigin()

-

.setOrigin(vector: Vector2): undefined

-

Set the value of .origin according to vector.

-

.setOrigin(x: Number, y: Number ): undefined

-

Set the value of .origin according to the x, y coordinates.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIElement.png b/GameDev/bin/Release/help/api/UIElement.png deleted file mode 100644 index 75c35865..00000000 Binary files a/GameDev/bin/Release/help/api/UIElement.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/UIImage.html b/GameDev/bin/Release/help/api/UIImage.html deleted file mode 100644 index 77862f1a..00000000 --- a/GameDev/bin/Release/help/api/UIImage.html +++ /dev/null @@ -1,1317 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIImage

-

Image element in a UI.

-

class UIImage extends UIElement

-

Inheritance UIElement --> UIImage

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIImage()Creates a new UIImage.
Properties
sizeA Vector2 representing the ui-image's size.
Methods
getSize()Get the value of .size
setSize()Set the value of .size
setImage()Set the content of the ui-image.
-

Constructors

-

UIImage()

-

UIImage()

-

Creates a new UIImage.

-

Properties

-

See the base UIElement class for common properties.

-

size

-

.size: Object

-

A Vector2 representing the ui-image's size.

-

Read-only. Use method setSize() to modify this property.

-

Default is {x: 100, y: 100}.

-

Methods

-

See the base UIElement class for common methods.

-

getSize()

-

.getSize(vector: Vector2): Vector2

-

Copy the value of .size into vector.

-

setSize()

-

.setSize(vector: Vector2): undefined

-

Set the value of .size according to vector.

-

.setSize(x: Number, y: Number ): undefined

-

Set the value of .size according to the x, y coordinates.

-

setImage()

-

.setImage(image: Image): undefined

-

Set the content of the ui-image using a Image object.

-

.size will be set according to the image contetnt.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UILineEdit.html b/GameDev/bin/Release/help/api/UILineEdit.html deleted file mode 100644 index cf98bde9..00000000 --- a/GameDev/bin/Release/help/api/UILineEdit.html +++ /dev/null @@ -1,1334 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UILineEdit

-

Editable text box in a UI.

-

class UILineEdit extends UIElement

-

Inheritance UIElement --> UILineEdit

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UILineEdit()Creates a new UILineEdit.
Properties
sizeA Vector2 representing the ui-lineedit's size.
textCurrent text content.
Methods
getSize()Get the value of .size
setSize()Set the value of .size
setStyle()Set the displaying style of the ui-text.
-

Constructors

-

UILineEdit()

-

UILineEdit()

-

Creates a new UILineEdit.

-

Properties

-

See the base UIElement class for common properties.

-

size

-

.size: Object

-

A Vector2 representing the ui-lineedit's size.

-

Read-only. Use method setSize() to modify this property.

-

Default is {x: 100, y: 40}.

-

text

-

.text: String

-

Current text content.

-

Readable and writable.

-

Default is "".

-

Methods

-

See the base UIElement class for common methods.

-

getSize()

-

.getSize(vector: Vector2): Vector2

-

Copy the value of .size into vector.

-

setSize()

-

.setSize(vector: Vector2): undefined

-

Set the value of .size according to vector.

-

.setSize(x: Number, y: Number ): undefined

-

Set the value of .size according to the x, y coordinates.

-

setStyle()

-

.setStyle(style: Object): undefined

-

Set the displaying style of the ui-text.

-

style may have the following properties:

-

style.fontSize: Number

-

Font size.

-

style.fontFace: String

-

Name of TypeTrue font face.

-

style.colorBg: String

-

Background color.

-

style.colorFg: String

-

Text color.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIManager.html b/GameDev/bin/Release/help/api/UIManager.html deleted file mode 100644 index 0c3f1812..00000000 --- a/GameDev/bin/Release/help/api/UIManager.html +++ /dev/null @@ -1,1299 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIManager

-

Manages UIArea objects.

-

Handles UI related Mouse/Touch/Keyboard inputs.

-

No constructor, exposed as a global object UIManager.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Properties
areasArray of UIArea objects managed by the ui-manager.
Methods
add()Adds an ui-area to the ui-manager.
remove()Removes an ui-area from the ui-manager.
clear()Removes all ui-areas from the ui-manager.
-

Properties

-

areas

-

.areas: Array

-

Array of UIArea objects managed by the ui-manager.

-

Read-only.

-

Methods

-

add()

-

.add(area: UIArea): this

-

Adds an ui-area to the ui-manager.

-

remove()

-

.remove(area: UIArea): this

-

Removes an ui-area from the ui-manager.

-

clear()

-

.clear(): this

-

Removes all ui-areas from the ui-manager.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIManager.png b/GameDev/bin/Release/help/api/UIManager.png deleted file mode 100644 index fba08ab1..00000000 Binary files a/GameDev/bin/Release/help/api/UIManager.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/UIPanel.html b/GameDev/bin/Release/help/api/UIPanel.html deleted file mode 100644 index 27b1b3f5..00000000 --- a/GameDev/bin/Release/help/api/UIPanel.html +++ /dev/null @@ -1,1296 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIPanel

-

A visible ui-block.

-

class UIPanel extends UIBlock

-

Inheritance UIElement --> UIBlock --> UIPanel

- - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIPanel()Creates a new UIPanel.
Methods
setStyle()Set the displaying style of the ui-panel.
-

Constructors

-

UIPanel()

-

UIPanel()

-

Creates a new UIPanel.

-

Properties

-

See the base UIBlock class for common properties.

-

Methods

-

See the base UIBlock class for common methods.

-

setStyle()

-

.setStyle(style: Object): undefined

-

Set the displaying style of the ui-panel.

-

style may have the following properties:

-

style.cornerRadius: Number

-

Corner radius of the rounded rectangle.

-

style.strokeWidth: Number

-

Line-width of the stroke.

-

style.colorBg: String

-

Background color of the panel.

-

style.colorStroke: String

-

Stroke color of the panel.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIScrollViewer.html b/GameDev/bin/Release/help/api/UIScrollViewer.html deleted file mode 100644 index 3f2c5fc4..00000000 --- a/GameDev/bin/Release/help/api/UIScrollViewer.html +++ /dev/null @@ -1,1368 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIScrollViewer

-

A scrollable ui-block.

-

class UIScrollViewer extends UIBlock

-

Inheritance UIElement --> UIBlock --> UIScrollViewer

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIScrollViewer()Creates a new UIScrollViewer.
Properties
scrollableVerticalIndicates whether the ui-scrollviewer is vertical-scrollable.
scrollableHorizontalIndicates whether the ui-scrollviewer is horizontal-scrollable.
scrollPositionCurrent scroll position.
contentSizeContent size.
Methods
setStyle()Set the displaying style of the ui-scrollviewer.
getScrollPosition()Get the value of .scrollPosition
setScrollPosition()Set the value of .scrollPosition
getContentSize()Get the value of .contentSize
setContentSize()Set the value of .contentSize
-

Constructors

-

UIScrollViewer()

-

UIScrollViewer()

-

Creates a new UIScrollViewer.

-

Properties

-

See the base UIBlock class for common properties.

-

scrollableVertical

-

.scrollableVertical: Boolean

-

Indicates whether the ui-scrollviewer is vertical-scrollable.

-

Readble and writable.

-

Default is true.

-

scrollableHorizontal

-

.scrollableHorizontal: Boolean

-

Indicates whether the ui-scrollviewer is horizontal-scrollable.

-

Readble and writable.

-

Default is false.

-

scrollPosition

-

.scrollPosition: Object

-

A Vector2 representing the ui-scrollviewer's current scroll position.

-

Read-only. Use method setScrollPosition() to modify this property.

-

Default is {x: 0, y: 0}.

-

contentSize

-

.contentSize: Object

-

A Vector2 representing the ui-scrollviewer's content size.

-

Read-only. Use method setContentSize() to modify this property.

-

Default is {x: 100, y: 100}.

-

Methods

-

See the base UIBlock class for common methods.

-

setStyle()

-

.setStyle(style: Object): undefined

-

Set the displaying style of the ui-panel.

-

style may have the following properties:

-

style.cornerRadius: Number

-

Corner radius of the rounded rectangle.

-

style.strokeWidth: Number

-

Line-width of the stroke.

-

style.colorBg: String

-

Background color of the panel.

-

style.colorStroke: String

-

Stroke color of the panel.

-

getScrollPosition()

-

.getScrollPosition(vector: Vector2): Vector2

-

Copy the value of .scrollPosition into vector.

-

setScrollPosition()

-

.setScrollPosition(vector: Vector2): undefined

-

Set the value of .scrollPosition according to vector.

-

.setScrollPosition(x: Number, y: Number): undefined

-

Set the value of .scrollPosition according to the x, y coordinates.

-

getContentSize()

-

.getContentSize(vector: Vector2): Vector2

-

Copy the value of .contentSize into vector.

-

setContentSize()

-

.setContentSize(vector: Vector2): undefined

-

Set the value of .contentSize according to vector.

-

.setContentSize(x: Number, y: Number): undefined

-

Set the value of .contentSize according to the x, y coordinates.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UIText.html b/GameDev/bin/Release/help/api/UIText.html deleted file mode 100644 index c4a03ee7..00000000 --- a/GameDev/bin/Release/help/api/UIText.html +++ /dev/null @@ -1,1317 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UIText

-

Non-editable text element in a UI.

-

class UIText extends UIElement

-

Inheritance UIElement --> UIText

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UIText()Creates a new UIText.
Properties
textText content.
Methods
setStyle()Set the displaying style of the ui-text.
-

Constructors

-

UIText()

-

UIText()

-

Creates a new UIText.

-

Properties

-

See the base UIElement class for common properties.

-

text

-

.text: String

-

Text content.

-

Readable and writable.

-

Default is "".

-

Methods

-

setStyle()

-

.setStyle(style: Object): undefined

-

Set the displaying style of the ui-text.

-

style may have the following properties:

-

style.fontSize: Number

-

Font size.

-

style.fontFace: String

-

Name of TypeTrue font face.

-

style.alignmentHorizontal: Number

-

Horizontal alignment mode.

-

1: left

-

2: center

-

3: right

-

style.alignmentVertical: Number

-

Vertial alignment mode.

-

1: top

-

2: center

-

3: bottom

-

4: baseline

-

style.colorFg: String

-

Text color.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/UITextBlock.html b/GameDev/bin/Release/help/api/UITextBlock.html deleted file mode 100644 index 54f10a7a..00000000 --- a/GameDev/bin/Release/help/api/UITextBlock.html +++ /dev/null @@ -1,1321 +0,0 @@ - - - - - - - - - - - - - - -

<--Home

-

class UITextBlock

-

Non-editable, mutli-lined text element in a UI.

-

class UITextBlock extends UIElement

-

Inheritance UIElement --> UITextBlock

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescription
Constructors
UITextBlock()Creates a new UITextBlock.
Properties
textText content.
Methods
setStyle()Set the displaying style of the ui-text.
-

Constructors

-

UITextBlock()

-

UITextBlock()

-

Creates a new UITextBlock.

-

Properties

-

See the base UIElement class for common properties.

-

text

-

.text: String

-

Text content.

-

Readable and writable.

-

Default is "".

-

Methods

-

setStyle()

-

.setStyle(style: Object): undefined

-

Set the displaying style of the ui-text.

-

style may have the following properties:

-

style.lineWidth: Number

-

Number of characters each line.

-

style.lineHeight: Number

-

Height of each line.

-

style.fontSize: Number

-

Font size.

-

style.fontFace: String

-

Name of TypeTrue font face.

-

style.alignmentHorizontal: Number

-

Horizontal alignment mode.

-

1: left

-

2: center

-

3: right

-

style.alignmentVertical: Number

-

Vertial alignment mode.

-

1: top

-

2: center

-

3: bottom

-

4: baseline

-

style.colorFg: String

-

Text color.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/background.png b/GameDev/bin/Release/help/api/background.png deleted file mode 100644 index 1cee13ec..00000000 Binary files a/GameDev/bin/Release/help/api/background.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/index.html b/GameDev/bin/Release/help/api/index.html deleted file mode 100644 index aa50fe60..00000000 --- a/GameDev/bin/Release/help/api/index.html +++ /dev/null @@ -1,1771 +0,0 @@ - - - - - - - - - - - - - - -

For a quick walkthrough of what can be done in a Three.V8 user script, see Features.

-

For details of the APIs that enable the features, see below.

-

Three.V8 User Script APIs

-

The user script APIs consist of

-
    -
  • Engine Classes: have properties and methods to communicate with engine objects.
  • -
  • Global Functions: can be called directly from user script.
  • -
  • Global Objects: are special engine objects which are preexisting in the context rather than created by the user script.
  • -
  • Callback Functions: are used by user script to recieve the event calls from the host program.
  • -
-

Engine Classes (3D)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Class NameDescription
ImageRepresents an image that resides in CPU memory.
CubeImageRepresents a cubemap image that resides in CPU memory.
DDSImageRepresents a dds-image that resides in CPU memory.
HDRImageRepresents a HDR image that resides in CPU memory.
HDRCubeImageRepresents a HDR cubemap image that resides in CPU memory.
Object3DBase class of all 3D objects visible to user script.
CameraBase class for cameras.
PerspectiveCameraPerspective camera
BackroundAbstract class for all backgrounds
ColorBackgroundA background that has a monotone color.
CubeBackgroundA background using a CubeMap.
HemisphereBackgroundA background that has a sky color and a ground color.
BackgroundSceneUse another scene as background.
LightAbstract class for all direct lights.
DirectionalLightA light that gets emitted in a specific direction.
IndirectLightAbstract class for all indirect lights
EnvironmentMapImage based indirect light
EnvironmentMapCreatorCube-map filter that generates environmaps
AmbientLightUniform indirect light
HemisphereLightGradient indirect light
ProbeGridAn uniform grid of light-probes
LODProbeGridA mixed resolution grid of light-probes
SimpleModelA Model containing a single simple geometry
GLTFModelA Model that has a GLTF style internal structure.
AnimationMixerUtility for linear blending of animation clips.
Scene3D Object collection for rendering
FogRepresents the particle substance in the air
GLRendererManages rendering routines, including shaders
GLRenderTargetAn off-screen render target.
CubeRenderTargetA cubemap render target.
BoundingVolumeHierarchyAcceleration structure for ray-casting.
GamePlayerWrapper for the host GamePlayer object.
FileLoaderProvides a few interfaces to loading local files.
ImageLoaderProvides a few interfaces to load images.
DDSImageLoaderProvides a few interfaces to load dds-images.
HDRImageLoaderProvides a few interfaces to load HDR images.
GLTFLoaderProvides a few interfaces to load GLTF models.
ProbeGridLoaderProvides a few interfaces to load probe-grids.
LODProbeGridLoaderProvides a few interfaces to load lod-probe-grids.
TextProvides a few interfaces for text conversion.
-

Engine Classes (Network)

- - - - - - - - - - - - - - - -
Class NameDescription
HttpClientProvides a few interfaces to make HTTP requests.
WSClientMaintains a websocket connection at the client side.
-

Engine Classes (GUI)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Class NameDescription
UIManagerManages UIArea objects.
UIAreaManages UIElement objects and UI3DViewer objects.
UIElementAbstract base class of all ui-elements.
UIBlockBase class for all ui-elements containing other ui-elements.
UIPanelA visible ui-block.
UIButtonA clickable ui-block.
UIScrollViewerA scrollable ui-block.
UIImageImage element in a UI.
UITextNon-editable text element in a UI.
UITextBlockNon-editable multi-lined text element in a UI.
UILineEditEditable text box in a UI.
UI3DViewerObject for embedding a 3D view in a UI.
UIDraggableA draggable ui-panel.
-

Engine Classes (Multimedia)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Class NameDescription
MMCameraRepresents an image source from a web-camera.
MMLazyVideoRepresents an image source from a video-file.
MMVideoRepresents a background video-file player.
MMAudioRepresents a background audio-file player.
OpusRecorderRecord from an audio device and encode as a raw opus stream.
OpusPlayerPlay back a raw opus stream.
AVCRecorderRecord from a video device and encode as a raw AVC stream.
AVCPlayerPlay back a raw AVC stream.
-

Global Functions

-

These are functions that can be called directly in user script.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function NameDescription
print()Print strings to stdout
setCallback()Register a callback function.
now()Current time in milliseconds.
getGLError()Get the last OpenGL error code for debugging.
getListOfCameras()Get a list of camera device names.
getListOfAudioPlaybackDevices()Get a list of audio playback device names.
-

print()

-

print(text1: String, text2: String, ...): undefined

-

Print strings to stdout separated by spaces. Objects are not stringified automatically. To do that you need JSON.stringify().

-

setCallback()

-

setCallback(name: String, callback: Function): undefined

-

Register a callback function.

-

Parameters

-

name: one of the names listed in Callback Functions.

-

callback: function accessable from script, or lambda.

-

now()

-

now(): Number

-

Current time in milliseconds.

-

getGLError()

-

getGLError(): Number

-

Get the last OpenGL error code for debugging.

-

getListOfCameras()

-

getListOfCameras(): Array

-

Get a list of camera device names.

-

getListOfAudioPlaybackDevices()

-

getListOfAudioPlaybackDevices(): Array

-

Get a list of audio playback device names.

-

Global Objects

-

These are engine class singletons that can be used directly in user script.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Object NameDescription
gamePlayerInstance of GamePlayer.
fileLoaderInstance of FileLoader.
imageLoaderInstance of ImageLoader.
DDSImageLoaderInstance of DDSImageLoader.
HDRImageLoaderInstance of HDRImageLoader.
gltfLoaderInstance of GLTFLoader.
probeGridLoaderInstance of ProbeGridLoader.
LODProbeGridLoaderInstance of LODProbeGridLoader.
textInstance of Text
httpInstance of HttpClient.
UIManagerInstance of UIManager.
-

Callback Functions

-

User scripts are event driven programs. Callback functions need to be registered in the global scope by calling setCallback.

-

The host program calls these functions at specific events according to their names.

-

The following callback functions are called by the default "GamePlayer".

-

Mouse callbacks are specific to desktop while touch callbacks are specific to mobile devices.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Callback nameDescription
init()Called immediately after loading the script.
dispose()Called before unloading the script.
render()Called when rendering a video frame.
OnMouseDown()Called when mouse button is pressed down.
OnMouseUp()Called when mouse button is up.
OnMouseMove()Called when mouse pointer is moved.
OnMouseWheel()Called when mouse wheel is moved.
OnTouchDown()Called when user touches screen.
OnTouchUp()Called when user stops touching screen.
OnTouchMove()Called when user moves on touch screen.
-

init()

-

init(width: Number, height: Number): undefined

-

Called immediately after loading the script.

-

Parameters

-

width: width of the container window.

-

height: height of the container window.

-

dispose()

-

dispose(): undefined

-

Called before unloading the script.

-

render()

-

render(width: Number, height: Number, sizeChanged: Boolean): undefined

-

Called when rendering a video frame.

-

Parameters

-

width: width of the container window.

-

height: height of the container window.

-

sizeChanged: if size of windows has changed.

-

OnMouseDown()

-

OnMouseDown(e: Object): undefined

-

Called when mouse button is pressed down.

-

Parameters

-

e: has the following properties:

-

e.x: Number

-

x coordinate of mouse pointer

-

e.y: Number

-

y coordinate of mouse pointer

-

e.delta: Number

-

wheel delta

-

e.button: Number

-

0 = Left Button

-

1 = Middle Button

-

2 = Right Button

-

3 = XButton1

-

4 = XButton2

-

OnMouseUp()

-

OnMouseUp(e: Object): undefined

-

Called when mouse button is up.

-

The parameter e has the same structure as in OnMouseDown()

-

OnMouseMove()

-

OnMouseMove(e: Object): undefined

-

Called when mouse pointer is moved.

-

The parameter e has the same structure as in OnMouseDown()

-

OnMouseWheel()

-

OnMouseWheel(e: Object): undefined

-

Called when mouse wheel is moved.

-

The parameter e has the same structure as in OnMouseDown()

-

OnTouchDown()

-

OnTouchDown(e: Object): undefined

-

Called when user touches screen.

-

Parameters

-

e: has the following properties:

-

pointerId: Number

-

Identifier for distinguishing multiple touch points.

-

x: number

-

x coordinate of touch point.

-

y: number

-

y coordinate of touch point.

-

OnTouchUp()

-

OnTouchUp(e: Object): undefined

-

Called when user stops touching screen.

-

The parameter e has the same structure as in OnTouchDown()

-

OnTouchMove()

-

OnTouchMove(e: Object): undefined

-

Called when user moves on touch screen.

-

The parameter e has the same structure as in OnTouchDown()

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/api/indirect_light.png b/GameDev/bin/Release/help/api/indirect_light.png deleted file mode 100644 index 2a6c56ec..00000000 Binary files a/GameDev/bin/Release/help/api/indirect_light.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/models.png b/GameDev/bin/Release/help/api/models.png deleted file mode 100644 index 2a4ea19f..00000000 Binary files a/GameDev/bin/Release/help/api/models.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/noshadow.png b/GameDev/bin/Release/help/api/noshadow.png deleted file mode 100644 index 74365608..00000000 Binary files a/GameDev/bin/Release/help/api/noshadow.png and /dev/null differ diff --git a/GameDev/bin/Release/help/api/screenshot.png b/GameDev/bin/Release/help/api/screenshot.png deleted file mode 100644 index 5efa71fa..00000000 Binary files a/GameDev/bin/Release/help/api/screenshot.png and /dev/null differ diff --git a/GameDev/bin/Release/help/background_scene.jpg b/GameDev/bin/Release/help/background_scene.jpg deleted file mode 100644 index a9b59481..00000000 Binary files a/GameDev/bin/Release/help/background_scene.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/background_scene1.jpg b/GameDev/bin/Release/help/background_scene1.jpg deleted file mode 100644 index ae1114cc..00000000 Binary files a/GameDev/bin/Release/help/background_scene1.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/box.jpg b/GameDev/bin/Release/help/box.jpg deleted file mode 100644 index 8f951a4d..00000000 Binary files a/GameDev/bin/Release/help/box.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/cube_sky.jpg b/GameDev/bin/Release/help/cube_sky.jpg deleted file mode 100644 index 10e99be0..00000000 Binary files a/GameDev/bin/Release/help/cube_sky.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/directional_light.jpg b/GameDev/bin/Release/help/directional_light.jpg deleted file mode 100644 index edceb51b..00000000 Binary files a/GameDev/bin/Release/help/directional_light.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/directional_light2.jpg b/GameDev/bin/Release/help/directional_light2.jpg deleted file mode 100644 index 49df66fb..00000000 Binary files a/GameDev/bin/Release/help/directional_light2.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/env_lights.jpg b/GameDev/bin/Release/help/env_lights.jpg deleted file mode 100644 index dfe0d5e3..00000000 Binary files a/GameDev/bin/Release/help/env_lights.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/env_map.jpg b/GameDev/bin/Release/help/env_map.jpg deleted file mode 100644 index ff96816a..00000000 Binary files a/GameDev/bin/Release/help/env_map.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/gameplayer.jpg b/GameDev/bin/Release/help/gameplayer.jpg deleted file mode 100644 index b9d8be58..00000000 Binary files a/GameDev/bin/Release/help/gameplayer.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/group.jpg b/GameDev/bin/Release/help/group.jpg deleted file mode 100644 index 0641b889..00000000 Binary files a/GameDev/bin/Release/help/group.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/hemisphere_light.jpg b/GameDev/bin/Release/help/hemisphere_light.jpg deleted file mode 100644 index 5ed05303..00000000 Binary files a/GameDev/bin/Release/help/hemisphere_light.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/hemisphere_sky.jpg b/GameDev/bin/Release/help/hemisphere_sky.jpg deleted file mode 100644 index 20b698e8..00000000 Binary files a/GameDev/bin/Release/help/hemisphere_sky.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/index.html b/GameDev/bin/Release/help/index.html deleted file mode 100644 index b26d61b3..00000000 --- a/GameDev/bin/Release/help/index.html +++ /dev/null @@ -1,1314 +0,0 @@ - - - - - - - - - - - - - - -

GameDev

-

GameDev is an IDE for Three.V8, the JavaScript based 3D application engine.

- -

See Scene Editor for details of the XML based scene-editor.

-

See Tutorial for a walk-through of creation of different type of Apps.

-

See Three.V8 User Script APIs for the detail of the APIs.

-

The Engine

-

Three.V8 is a cross-platform 3D application engine. -Developer can use the engine to develop their own cross-platform 3D applications in JavaScript. -Apps developed using Three.V8 can run in all supported platforms using the engine for the specific platform.

-

Three.V8 exposes its own set of engine APIs which can be called by the apps to implement their required functionalities. -There is a separate documentation about the detail of the APIs.

-

The design of the engine is similar to other script-based game engines. -However, as an application engine, Three.V8 also provides basic APIs for networking, multimedia and GUI apart from its 3D functionalities. -The GUI system is based on the built-in graphics library of the engine so that the appearance of the GUI is highly consistent across different platforms.

-

-GUI appearance in Windows

-

-GUI appearance in Android

-

Structure of an App

-

An app developed using Three.V8 is consisted of a code part and a data part. -The code part can be consisted of multiple JavaScript file during development. -However, all the code need to be bundled togather using Rollup.js or other bundlers -before it can be run with the engine. The bundling procedural is automated by the IDE.

-

The data part is consisted of multiple data files of arbitary formats. They should either be deployed together -with the bundled code inside the final App or placed at a remote server to be downloaded at run-time. -Those deployed inside the App can be referenced using paths relative to the bundled code.

-

The IDE

-

-

The GUI of the IDE is consisted of ① Menu bar ② Side bar ③ Editor area and ④ Log area.

-

External Dependencies

-
    -
  • Code editors are based on Microsoft WebView2. Make sure to get the runtime installed before starting the IDE.
  • -
  • Bundling is performed using Rollup.js. Make sure to install the npm package (globally) before trying to run any target.
  • -
- -

Use File-New-Project to create a new project. A project is a directory containing a "project.json" file. "project.json" marks the directory as a GameDev project, and maintains a list of bundle targets.

-

Use File-New-File to add files to the project directory. You can also right-click a directory item in the side-bar to create files at a specified position.

-

The editors does not reload automatically when a file is modified outside of the IDE. You can manually refresh using File-Reopen or by pressing F5.

- -

The "Files" tab provides a tree-view of the project directory. Use the context menus to create, open or delete files.

-

The "Targets" tab provides a list-view of the managed bundle targets.

-

-

Use buttons at ① to add/remove bundle targets or open the "Edit Target" window ③.

-

Right click the Target item at ② for context menu, where you get options to run the target or create a shortcut of the App on the desktop. To run the target, you can also just double click the item. A bundling process will be triggered by calling the external "rollup" tool if a JavaScript file is modified. A separate process will be started by launching GamePlayer.exe with the path of the bundled JavaScript file. Note the bundled JavaScript files are hidden in the "Files" tab, because you should never edit these files manually.

-

Editors

-

GameDev provides editors for file formats most commonly used in a Three.V8 project, which are JavaScript, XML and JSON.

-

In this IDE, we use specifically structured XML files to represent 3D Scenes and a dedicated scene editor is provided.

-

Logs

-

Currently the "Console" tab of the log areas mainly shows outputs from the bundling process and the scene editor.

-

Since that a running Target has its own process (GamePlayer.exe), their outputs can be seen in their own consoles.

-

-

The console of GamePlayer.exe is hidden by default, and can be shown by dragging.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/model.jpg b/GameDev/bin/Release/help/model.jpg deleted file mode 100644 index cfe20c39..00000000 Binary files a/GameDev/bin/Release/help/model.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/plane.jpg b/GameDev/bin/Release/help/plane.jpg deleted file mode 100644 index 294b5765..00000000 Binary files a/GameDev/bin/Release/help/plane.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/proxy.jpg b/GameDev/bin/Release/help/proxy.jpg deleted file mode 100644 index 0228af7d..00000000 Binary files a/GameDev/bin/Release/help/proxy.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/scene_editor.html b/GameDev/bin/Release/help/scene_editor.html deleted file mode 100644 index a609dde0..00000000 --- a/GameDev/bin/Release/help/scene_editor.html +++ /dev/null @@ -1,1340 +0,0 @@ - - - - - - - - - - - - - - -

Scene Editor

- -

-

Three.V8 does not specify how a scene is represented in external storage, which can be decided by each App (user script). However, the IDE has a built-in support for a specific XML format and provides a visualized interface to edit the scene, which is being described here. To support this XML format in your app, you can start with the "project_template" provided with GameDev.

-

The visualized scene editor is opened when you open a XML file in the IDE. -On the left side of the editor, you will see the scene preview ①. On the right side, the "Code" tab is activated by default, where you can edit the XML code directly. However, the "Scene" tab is of more interest, where you can tweak the content of the XML file by controls. The changes are synchronized between the tabs.

-

On the "Scene" tab, you can find the "Scene Graph" group ② where you can select the items currently present in the scene. To select an item, you can either click it in the tree-view or click the "Picking" button then pick it inside the left view. Once an item is selected, you can edit the properties of the item on the right side ④.

-

Using the tool buttons in the "Create..." group ③, you can add new items into the scene.

-

-

Basically, you first select an existing item as the parent item, then click a tool button to create an item. There are 2 kinds of items you can create this way, scene-items and 3D-items. Scene items are unique to a scene and the parent item must be "scene". 3D Items can be placed either under "scene" or under an existing 3D Item.

-

Fog Item

-

The fog item describes particle scattering material in the air across the scene. It can be used to obscure the objects at a far distance, and is all essential for generating the Tyndall effect. The Fog Item has 2 properties, density and color. The bigger the density is, the faster the light attenuates.

-

Sky Item

-

The sky item describes the background of the scene, which is shown when no there are no 3D objects. There are 4 types of skys you can select from the dropbox.

-

-

Uniform

-

Select uniform if you want a uniform color as the background.

-

-

The color will be the same no matter which direction you look at.

-

Hemisphere

-

The background has a gradual change of color from sky to ground.

-

-

Cube

-

The background is defined by a cube-map consisting of 6 images.

-

-

The 6 images must be in the same directory. You can specify the file name of each of the images, or you can click "Browse" to select all 6 images.

-

Scene

-

The background of current scene is defined using another scene.

-

-

For each frame, the background scene is rendered first using a camera located at the same position as the camera used for rendering the current scene, but with relatively large clipping plane values, which means that the objects in the background scene should be located much further away than objects in the current scene. Then the current scene is rendered on top of it.

-

-

Environment Light Item

-

The environment light item describes how objects in the scene should be lighted not by a direct light source but by random reflections from the scene its self. There are 3 types of environment lights you can select from the dropbox.

-

-

Uniform

-

Light recieved from every direction of the scene is the same.

-

-

Hemisphere

-

There is a gradual change of light from sky to ground.

-

-

Cube

-

The enviroment light is defined by a cube-map consisting of 6 images.

-

-

The 6 images must be in the same directory. You can specify the file name of each of the images, or you can click "Browse" to select all 6 images.

-

This kind of environment light can also be generated by an iterative process using a probe into the scene.

-

-

A proxy cube is created alongside with the environment light indicating where the probe is located. The position of the probe can be adjusted using the "Probe Position" tuners. When you have decided where to place the probe, click "Generate Images" and the cube-map will be generated in a few iterations.

-

Group Item

-

A group item is a 3D object you can put into scene-graph as a common parent of several child objects. The group object itself does not contain any geometry, so only its transformations are taking effect.

-

-

These transformation properties are common to all 3D objects, you can also find them when another 3D object is selected.

-

Plane/Box/Sphere Items

-

These are simple geometry objects.

-

-

-

-

There property pages share many in common. -For each of them, the geometry options come first, followed by the transformation properties, then material properties(Color/Texture/Metalness/Roughness).

-

Check the "is building" option if the object is part of building and should be hit-tested at run time.

-

Model Item

-

A model item is defined by a model file. It also has an "is building" option, check it when the model defines part of the building.

-

-

Directional Light Item

-

A directional light is a light source located far away from the scene, such as the sunlight.

-

-

The "Position" property of the light source defines the origin coordinate of the light.

-

"Target", when it is set, defines which object the light goes towards. It must be the name of an 3D object within the scene.

-

When "Cast Shadow" is not checked. The light comes from infinitely far away from the direction of normalize(light.position - Target.position).

-

When "Cast Shadow" is checked, a shadow will be used, which covers the areas defined by the Left/Right/Bottom/Top/Near/Far properties.

-

-

The shadow-map covered area is visualized by the wires.

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/scene_editor.jpg b/GameDev/bin/Release/help/scene_editor.jpg deleted file mode 100644 index fbbcc742..00000000 Binary files a/GameDev/bin/Release/help/scene_editor.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/sky_types.jpg b/GameDev/bin/Release/help/sky_types.jpg deleted file mode 100644 index 9903c53a..00000000 Binary files a/GameDev/bin/Release/help/sky_types.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/sphere.jpg b/GameDev/bin/Release/help/sphere.jpg deleted file mode 100644 index 2a589587..00000000 Binary files a/GameDev/bin/Release/help/sphere.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/tools.jpg b/GameDev/bin/Release/help/tools.jpg deleted file mode 100644 index 1646562a..00000000 Binary files a/GameDev/bin/Release/help/tools.jpg and /dev/null differ diff --git a/GameDev/bin/Release/help/tutorials.html b/GameDev/bin/Release/help/tutorials.html deleted file mode 100644 index 49c19604..00000000 --- a/GameDev/bin/Release/help/tutorials.html +++ /dev/null @@ -1,1248 +0,0 @@ - - - - - - - - - - - - - - -

Tutorial

-
- - \ No newline at end of file diff --git a/GameDev/bin/Release/help/uniform_sky.jpg b/GameDev/bin/Release/help/uniform_sky.jpg deleted file mode 100644 index 1779664f..00000000 Binary files a/GameDev/bin/Release/help/uniform_sky.jpg and /dev/null differ diff --git a/GameDev/bin/Release/icudtl.dat b/GameDev/bin/Release/icudtl.dat deleted file mode 100644 index 0e35d1da..00000000 Binary files a/GameDev/bin/Release/icudtl.dat and /dev/null differ diff --git a/GameDev/bin/Release/icui18n.dll b/GameDev/bin/Release/icui18n.dll deleted file mode 100644 index ea9a114b..00000000 Binary files a/GameDev/bin/Release/icui18n.dll and /dev/null differ diff --git a/GameDev/bin/Release/icuuc.dll b/GameDev/bin/Release/icuuc.dll deleted file mode 100644 index 6be4c8f0..00000000 Binary files a/GameDev/bin/Release/icuuc.dll and /dev/null differ diff --git a/GameDev/bin/Release/postproc-55.dll b/GameDev/bin/Release/postproc-55.dll deleted file mode 100644 index e51df89e..00000000 Binary files a/GameDev/bin/Release/postproc-55.dll and /dev/null differ diff --git a/GameDev/bin/Release/project_template/controls/EventDispatcher.js b/GameDev/bin/Release/project_template/controls/EventDispatcher.js deleted file mode 100644 index 0a40a60e..00000000 --- a/GameDev/bin/Release/project_template/controls/EventDispatcher.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * https://github.com/mrdoob/eventdispatcher.js/ - */ - -class EventDispatcher { - - addEventListener( type, listener ) { - - if ( this._listeners === undefined ) this._listeners = {}; - - const listeners = this._listeners; - - if ( listeners[ type ] === undefined ) { - - listeners[ type ] = []; - - } - - if ( listeners[ type ].indexOf( listener ) === - 1 ) { - - listeners[ type ].push( listener ); - - } - - } - - hasEventListener( type, listener ) { - - if ( this._listeners === undefined ) return false; - - const listeners = this._listeners; - - return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; - - } - - removeEventListener( type, listener ) { - - if ( this._listeners === undefined ) return; - - const listeners = this._listeners; - const listenerArray = listeners[ type ]; - - if ( listenerArray !== undefined ) { - - const index = listenerArray.indexOf( listener ); - - if ( index !== - 1 ) { - - listenerArray.splice( index, 1 ); - - } - - } - - } - - dispatchEvent( event ) { - if ( this._listeners === undefined ) return; - - const listeners = this._listeners; - const listenerArray = listeners[event.type]; - - if ( listenerArray !== undefined ) { - - event.target = this; - - // Make a copy, in case listeners are removed while iterating. - const array = listenerArray.slice( 0 ); - - for ( let i = 0, l = array.length; i < l; i ++ ) { - - array[ i ].call( this, event ); - - } - - event.target = null; - - } - - } - -} - - -export { EventDispatcher }; diff --git a/GameDev/bin/Release/project_template/controls/OrbitControls.js b/GameDev/bin/Release/project_template/controls/OrbitControls.js deleted file mode 100644 index 74a34db6..00000000 --- a/GameDev/bin/Release/project_template/controls/OrbitControls.js +++ /dev/null @@ -1,1261 +0,0 @@ -import { EventDispatcher } from "./EventDispatcher.js"; -import { MOUSE, TOUCH } from "./constants.js"; -import { Quaternion } from "../math/Quaternion.js"; -import { Spherical } from "../math/Spherical.js"; -import { Vector2 } from "../math/Vector2.js"; -import { Vector3 } from "../math/Vector3.js"; -import { Matrix4 } from "../math/Matrix4.js"; - - -// This set of controls performs orbiting, dollying (zooming), and panning. -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// -// Orbit - left mouse / touch: one-finger move -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move - -const _changeEvent = { type: 'change' }; -const _startEvent = { type: 'start' }; -const _endEvent = { type: 'end' }; - -class OrbitControls extends EventDispatcher { - - constructor( object, domElement ) { - - super(); - - if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); - - this.object = object; - this.domElement = domElement; - - // Set to false to disable this control - this.enabled = true; - - // "target" sets the location of focus, where the object orbits around - this.target = new Vector3(); - - // How far you can dolly in and out ( PerspectiveCamera only ) - this.minDistance = 0; - this.maxDistance = Infinity; - - // How far you can zoom in and out ( OrthographicCamera only ) - this.minZoom = 0; - this.maxZoom = Infinity; - - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - this.minPolarAngle = 0; // radians - this.maxPolarAngle = Math.PI; // radians - - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - this.minAzimuthAngle = - Infinity; // radians - this.maxAzimuthAngle = Infinity; // radians - - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - this.enableDamping = false; - this.dampingFactor = 0.05; - - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - this.enableZoom = true; - this.zoomSpeed = 1.0; - - // Set to false to disable rotating - this.enableRotate = true; - this.rotateSpeed = 1.0; - - // Set to false to disable panning - this.enablePan = true; - this.panSpeed = 1.0; - this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up - this.keyPanSpeed = 7.0; // pixels moved per arrow key push - - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - this.autoRotate = false; - this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 - - // The four arrow keys - this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; - - // Mouse buttons - this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; - - // Touch fingers - this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; - - // for reset - this.target0 = this.target.clone(); - this.position0 = this.object.getPosition(new Vector3()); - - // this.zoom0 = this.object.zoom; - this.zoom0 = 1.0; - - // the target DOM element for key events - this._domElementKeyEvents = null; - - // - // public methods - // - - this.getPolarAngle = function () { - - return spherical.phi; - - }; - - this.getAzimuthalAngle = function () { - - return spherical.theta; - - }; - - this.getDistance = function () { - let position = this.object.getPosition(new Vector3()); - return position.distanceTo( this.target ); - - }; - - this.listenToKeyEvents = function ( domElement ) { - - domElement.addEventListener( 'keydown', onKeyDown ); - this._domElementKeyEvents = domElement; - - }; - - this.saveState = function () { - - scope.target0.copy(scope.target); - this.object.getPosition(scope.position0); - - // scope.zoom0 = scope.object.zoom; - scope.zoom0 = 1.0; - - }; - - this.reset = function () { - - scope.target.copy(scope.target0); - - this.object.getPosition(scope.position0); - - // scope.object.zoom = scope.zoom0; - - scope.object.updateProjectionMatrix(); - scope.dispatchEvent( _changeEvent ); - - scope.update(); - - state = STATE.NONE; - - }; - - // this method is exposed, but perhaps it would be better if we can make it private... - this.update = function () { - - const offset = new Vector3(); - - // so camera.up is the orbit axis - let camera_up = object.getUp(new Vector3()); - const quat = new Quaternion().setFromUnitVectors(camera_up, new Vector3(0, 1, 0)); - const quatInverse = quat.clone().invert(); - - const lastPosition = new Vector3(); - const lastQuaternion = new Quaternion(); - - const twoPI = 2 * Math.PI; - - return function update() { - - const position = scope.object.getPosition(new Vector3()); - - offset.copy( position ).sub( scope.target ); - - // rotate offset to "y-axis-is-up" space - offset.applyQuaternion( quat ); - - // angle from z-axis around y-axis - spherical.setFromVector3( offset ); - - if ( scope.autoRotate && state === STATE.NONE ) { - - rotateLeft( getAutoRotationAngle() ); - - } - - if ( scope.enableDamping ) { - - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; - - } else { - - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; - - } - - // restrict theta to be between desired limits - - let min = scope.minAzimuthAngle; - let max = scope.maxAzimuthAngle; - - if ( isFinite( min ) && isFinite( max ) ) { - - if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; - - if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; - - if ( min <= max ) { - - spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); - - } else { - - spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? - Math.max( min, spherical.theta ) : - Math.min( max, spherical.theta ); - - } - - } - - // restrict phi to be between desired limits - spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); - - spherical.makeSafe(); - - - spherical.radius *= scale; - - // restrict radius to be between desired limits - spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); - - // move target to panned location - - if ( scope.enableDamping === true ) { - - scope.target.addScaledVector( panOffset, scope.dampingFactor ); - - } else { - - scope.target.add( panOffset ); - - } - - offset.setFromSpherical( spherical ); - - // rotate offset back to "camera-up-vector-is-up" space - offset.applyQuaternion( quatInverse ); - - position.copy(scope.target).add(offset); - scope.object.setPosition(position) - - scope.object.lookAt( scope.target ); - - if ( scope.enableDamping === true ) { - - sphericalDelta.theta *= ( 1 - scope.dampingFactor ); - sphericalDelta.phi *= ( 1 - scope.dampingFactor ); - - panOffset.multiplyScalar( 1 - scope.dampingFactor ); - - } else { - - sphericalDelta.set( 0, 0, 0 ); - - panOffset.set( 0, 0, 0 ); - - } - - scale = 1; - - // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 - - const quaternion = scope.object.getQuaternion(new Quaternion()); - - if ( zoomChanged || - lastPosition.distanceToSquared(position) > EPS || - 8 * (1 - lastQuaternion.dot(quaternion) ) > EPS ) { - - scope.dispatchEvent( _changeEvent ); - - lastPosition.copy(position ); - lastQuaternion.copy(quaternion); - zoomChanged = false; - - return true; - - } - - return false; - - }; - - }(); - - this.dispose = function () { - - scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); - - scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); - scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); - scope.domElement.removeEventListener( 'wheel', onMouseWheel ); - - scope.domElement.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - - - if ( scope._domElementKeyEvents !== null ) { - - scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); - - } - - //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? - - }; - - // - // internals - // - - const scope = this; - - const STATE = { - NONE: - 1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; - - let state = STATE.NONE; - - const EPS = 0.000001; - - // current position in spherical coordinates - const spherical = new Spherical(); - const sphericalDelta = new Spherical(); - - let scale = 1; - const panOffset = new Vector3(); - let zoomChanged = false; - - const rotateStart = new Vector2(); - const rotateEnd = new Vector2(); - const rotateDelta = new Vector2(); - - const panStart = new Vector2(); - const panEnd = new Vector2(); - const panDelta = new Vector2(); - - const dollyStart = new Vector2(); - const dollyEnd = new Vector2(); - const dollyDelta = new Vector2(); - - const pointers = []; - const pointerPositions = {}; - - function getAutoRotationAngle() { - - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - - } - - function getZoomScale() { - - return Math.pow( 0.95, scope.zoomSpeed ); - - } - - function rotateLeft( angle ) { - - sphericalDelta.theta -= angle; - - } - - function rotateUp( angle ) { - - sphericalDelta.phi -= angle; - - } - - const panLeft = function () { - - const v = new Vector3(); - - return function panLeft( distance, objectMatrix ) { - - v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix - v.multiplyScalar( - distance ); - - panOffset.add( v ); - - }; - - }(); - - const panUp = function () { - - const v = new Vector3(); - - return function panUp( distance, objectMatrix ) { - - if ( scope.screenSpacePanning === true ) { - - v.setFromMatrixColumn( objectMatrix, 1 ); - - } else { - let up = scope.object.getUp(new Vector3()); - v.setFromMatrixColumn( objectMatrix, 0 ); - v.crossVectors(up, v ); - - } - - v.multiplyScalar( distance ); - - panOffset.add( v ); - - }; - - }(); - - // deltaX and deltaY are in pixels; right and down are positive - const pan = function () { - - const offset = new Vector3(); - - return function pan( deltaX, deltaY ) { - - const element = scope.domElement; - - if ( scope.object.isPerspectiveCamera ) { - - // perspective - const position = scope.object.getPosition(new Vector3()); - offset.copy( position ).sub( scope.target ); - let targetDistance = offset.length(); - - // half of the fov is center to top of screen - targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); - - const matrix = scope.object.getMatrix(new Matrix4()); - // we use only clientHeight here so aspect ratio does not distort speed - panLeft(2 * deltaX * targetDistance / element.clientHeight, matrix ); - panUp(2 * deltaY * targetDistance / element.clientHeight, matrix ); - - } else if (scope.object.isOrthographicCamera) { - - const matrix = scope.object.getMatrix(new Matrix4()); - // orthographic - panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, matrix ); - panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, matrix ); - - } else { - - // camera neither orthographic nor perspective - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); - scope.enablePan = false; - - } - - }; - - }(); - - function dollyOut( dollyScale ) { - - if ( scope.object.isPerspectiveCamera ) { - - scale /= dollyScale; - - } else if ( scope.object.isOrthographicCamera ) { - - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - - } else { - - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; - - } - - } - - function dollyIn( dollyScale ) { - - if ( scope.object.isPerspectiveCamera ) { - - scale *= dollyScale; - - } else if ( scope.object.isOrthographicCamera ) { - - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - - } else { - - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; - - } - - } - - // - // event callbacks - update the object state - // - - function handleMouseDownRotate( event ) { - - rotateStart.set( event.clientX, event.clientY ); - - } - - function handleMouseDownDolly( event ) { - - dollyStart.set( event.clientX, event.clientY ); - - } - - function handleMouseDownPan( event ) { - - panStart.set( event.clientX, event.clientY ); - - } - - function handleMouseMoveRotate( event ) { - - rotateEnd.set( event.clientX, event.clientY ); - - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - - const element = scope.domElement; - - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - - rotateStart.copy( rotateEnd ); - - scope.update(); - - } - - function handleMouseMoveDolly( event ) { - - dollyEnd.set( event.clientX, event.clientY ); - - dollyDelta.subVectors( dollyEnd, dollyStart ); - - if ( dollyDelta.y > 0 ) { - - dollyOut( getZoomScale() ); - - } else if ( dollyDelta.y < 0 ) { - - dollyIn( getZoomScale() ); - - } - - dollyStart.copy( dollyEnd ); - - scope.update(); - - } - - function handleMouseMovePan( event ) { - - panEnd.set( event.clientX, event.clientY ); - - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - - pan( panDelta.x, panDelta.y ); - - panStart.copy( panEnd ); - - scope.update(); - - } - - function handleMouseWheel( event ) { - - if ( event.deltaY < 0 ) { - - dollyIn( getZoomScale() ); - - } else if ( event.deltaY > 0 ) { - - dollyOut( getZoomScale() ); - - } - - scope.update(); - - } - - function handleKeyDown( event ) { - - let needsUpdate = false; - - switch ( event.code ) { - - case scope.keys.UP: - pan( 0, scope.keyPanSpeed ); - needsUpdate = true; - break; - - case scope.keys.BOTTOM: - pan( 0, - scope.keyPanSpeed ); - needsUpdate = true; - break; - - case scope.keys.LEFT: - pan( scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; - - case scope.keys.RIGHT: - pan( - scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; - - } - - if ( needsUpdate ) { - - // prevent the browser from scrolling on cursor keys - // event.preventDefault(); - - scope.update(); - - } - - - } - - function handleTouchStartRotate() { - - if ( pointers.length === 1 ) { - - rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - - } else { - - const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); - const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - - rotateStart.set( x, y ); - - } - - } - - function handleTouchStartPan() { - - if ( pointers.length === 1 ) { - - panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - - } else { - - const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); - const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - - panStart.set( x, y ); - - } - - } - - function handleTouchStartDolly() { - - const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX; - const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY; - - const distance = Math.sqrt( dx * dx + dy * dy ); - - dollyStart.set( 0, distance ); - - } - - function handleTouchStartDollyPan() { - - if ( scope.enableZoom ) handleTouchStartDolly(); - - if ( scope.enablePan ) handleTouchStartPan(); - - } - - function handleTouchStartDollyRotate() { - - if ( scope.enableZoom ) handleTouchStartDolly(); - - if ( scope.enableRotate ) handleTouchStartRotate(); - - } - - function handleTouchMoveRotate( event ) { - - if ( pointers.length == 1 ) { - - rotateEnd.set( event.pageX, event.pageY ); - - } else { - - const position = getSecondPointerPosition( event ); - - const x = 0.5 * ( event.pageX + position.x ); - const y = 0.5 * ( event.pageY + position.y ); - - rotateEnd.set( x, y ); - - } - - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - - const element = scope.domElement; - - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - - rotateStart.copy( rotateEnd ); - - } - - function handleTouchMovePan( event ) { - - if ( pointers.length === 1 ) { - - panEnd.set( event.pageX, event.pageY ); - - } else { - - const position = getSecondPointerPosition( event ); - - const x = 0.5 * ( event.pageX + position.x ); - const y = 0.5 * ( event.pageY + position.y ); - - panEnd.set( x, y ); - - } - - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - - pan( panDelta.x, panDelta.y ); - - panStart.copy( panEnd ); - - } - - function handleTouchMoveDolly( event ) { - - const position = getSecondPointerPosition( event ); - - const dx = event.pageX - position.x; - const dy = event.pageY - position.y; - - const distance = Math.sqrt( dx * dx + dy * dy ); - - dollyEnd.set( 0, distance ); - - dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); - - dollyOut( dollyDelta.y ); - - dollyStart.copy( dollyEnd ); - - } - - function handleTouchMoveDollyPan( event ) { - - if ( scope.enableZoom ) handleTouchMoveDolly( event ); - - if ( scope.enablePan ) handleTouchMovePan( event ); - - } - - function handleTouchMoveDollyRotate( event ) { - - if ( scope.enableZoom ) handleTouchMoveDolly( event ); - - if ( scope.enableRotate ) handleTouchMoveRotate( event ); - - } - - // - // event handlers - FSM: listen for events and reset state - // - - function onPointerDown( event ) { - - if ( scope.enabled === false ) return; - - if ( pointers.length === 0 ) { - - scope.domElement.setPointerCapture(); - - scope.domElement.addEventListener( 'pointermove', onPointerMove ); - scope.domElement.addEventListener( 'pointerup', onPointerUp ); - - } - - // - - addPointer( event ); - - if ( event.pointerType === 'touch' ) { - - onTouchStart( event ); - - } else { - - onMouseDown( event ); - - } - - } - - function onPointerMove( event ) { - - if ( scope.enabled === false ) return; - - if ( event.pointerType === 'touch' ) { - - onTouchMove( event ); - - } else { - - onMouseMove( event ); - - } - - } - - function onPointerUp( event ) { - - removePointer( event ); - - if ( pointers.length === 0 ) { - - scope.domElement.releasePointerCapture(); - - scope.domElement.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - - } - - scope.dispatchEvent( _endEvent ); - - state = STATE.NONE; - - } - - function onPointerCancel( event ) { - - removePointer( event ); - - } - - function onMouseDown( event ) { - - let mouseAction; - - switch ( event.button ) { - - case 0: - - mouseAction = scope.mouseButtons.LEFT; - break; - - case 1: - - mouseAction = scope.mouseButtons.MIDDLE; - break; - - case 2: - - mouseAction = scope.mouseButtons.RIGHT; - break; - - default: - - mouseAction = - 1; - - } - - switch ( mouseAction ) { - - case MOUSE.DOLLY: - - if ( scope.enableZoom === false ) return; - - handleMouseDownDolly( event ); - - state = STATE.DOLLY; - - break; - - case MOUSE.ROTATE: - - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - - if ( scope.enablePan === false ) return; - - handleMouseDownPan( event ); - - state = STATE.PAN; - - } else { - - if ( scope.enableRotate === false ) return; - - handleMouseDownRotate( event ); - - state = STATE.ROTATE; - - } - - break; - - case MOUSE.PAN: - - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - - if ( scope.enableRotate === false ) return; - - handleMouseDownRotate( event ); - - state = STATE.ROTATE; - - } else { - - if ( scope.enablePan === false ) return; - - handleMouseDownPan( event ); - - state = STATE.PAN; - - } - - break; - - default: - - state = STATE.NONE; - - } - - if ( state !== STATE.NONE ) { - - scope.dispatchEvent( _startEvent ); - - } - - } - - function onMouseMove( event ) { - - if ( scope.enabled === false ) return; - - switch ( state ) { - - case STATE.ROTATE: - - if ( scope.enableRotate === false ) return; - - handleMouseMoveRotate( event ); - - break; - - case STATE.DOLLY: - - if ( scope.enableZoom === false ) return; - - handleMouseMoveDolly( event ); - - break; - - case STATE.PAN: - - if ( scope.enablePan === false ) return; - - handleMouseMovePan( event ); - - break; - - } - - } - - function onMouseWheel( event ) { - - if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return; - - // event.preventDefault(); - - scope.dispatchEvent( _startEvent ); - - handleMouseWheel( event ); - - scope.dispatchEvent( _endEvent ); - - } - - function onKeyDown( event ) { - - if ( scope.enabled === false || scope.enablePan === false ) return; - - handleKeyDown( event ); - - } - - function onTouchStart( event ) { - - trackPointer( event ); - - switch ( pointers.length ) { - - case 1: - - switch ( scope.touches.ONE ) { - - case TOUCH.ROTATE: - - if ( scope.enableRotate === false ) return; - - handleTouchStartRotate(); - - state = STATE.TOUCH_ROTATE; - - break; - - case TOUCH.PAN: - - if ( scope.enablePan === false ) return; - - handleTouchStartPan(); - - state = STATE.TOUCH_PAN; - - break; - - default: - - state = STATE.NONE; - - } - - break; - - case 2: - - switch ( scope.touches.TWO ) { - - case TOUCH.DOLLY_PAN: - - if ( scope.enableZoom === false && scope.enablePan === false ) return; - - handleTouchStartDollyPan(); - - state = STATE.TOUCH_DOLLY_PAN; - - break; - - case TOUCH.DOLLY_ROTATE: - - if ( scope.enableZoom === false && scope.enableRotate === false ) return; - - handleTouchStartDollyRotate(); - - state = STATE.TOUCH_DOLLY_ROTATE; - - break; - - default: - - state = STATE.NONE; - - } - - break; - - default: - - state = STATE.NONE; - - } - - if ( state !== STATE.NONE ) { - - scope.dispatchEvent( _startEvent ); - - } - - } - - function onTouchMove( event ) { - - trackPointer( event ); - - switch ( state ) { - - case STATE.TOUCH_ROTATE: - - if ( scope.enableRotate === false ) return; - - handleTouchMoveRotate( event ); - - scope.update(); - - break; - - case STATE.TOUCH_PAN: - - if ( scope.enablePan === false ) return; - - handleTouchMovePan( event ); - - scope.update(); - - break; - - case STATE.TOUCH_DOLLY_PAN: - - if ( scope.enableZoom === false && scope.enablePan === false ) return; - - handleTouchMoveDollyPan( event ); - - scope.update(); - - break; - - case STATE.TOUCH_DOLLY_ROTATE: - - if ( scope.enableZoom === false && scope.enableRotate === false ) return; - - handleTouchMoveDollyRotate( event ); - - scope.update(); - - break; - - default: - - state = STATE.NONE; - - } - - } - - function onContextMenu( event ) { - - if ( scope.enabled === false ) return; - - // event.preventDefault(); - - } - - function addPointer( event ) { - - pointers.push( event ); - - } - - function removePointer( event ) { - - delete pointerPositions[ event.pointerId ]; - - for ( let i = 0; i < pointers.length; i ++ ) { - - if ( pointers[ i ].pointerId == event.pointerId ) { - - pointers.splice( i, 1 ); - return; - - } - - } - - } - - function trackPointer( event ) { - - let position = pointerPositions[ event.pointerId ]; - - if ( position === undefined ) { - - position = new Vector2(); - pointerPositions[ event.pointerId ] = position; - - } - - position.set( event.pageX, event.pageY ); - - } - - function getSecondPointerPosition( event ) { - - const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ]; - - return pointerPositions[ pointer.pointerId ]; - - } - - // - - scope.domElement.addEventListener( 'contextmenu', onContextMenu ); - - scope.domElement.addEventListener( 'pointerdown', onPointerDown ); - scope.domElement.addEventListener( 'pointercancel', onPointerCancel ); - scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); - - // force an update at start - - this.update(); - - } - -} - - -// This set of controls performs orbiting, dollying (zooming), and panning. -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// This is very similar to OrbitControls, another set of touch behavior -// -// Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - left mouse, or arrow keys / touch: one-finger move - -class MapControls extends OrbitControls { - - constructor( object, domElement ) { - - super( object, domElement ); - - this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up - - this.mouseButtons.LEFT = MOUSE.PAN; - this.mouseButtons.RIGHT = MOUSE.ROTATE; - - this.touches.ONE = TOUCH.PAN; - this.touches.TWO = TOUCH.DOLLY_ROTATE; - - } - -} - -export { OrbitControls, MapControls }; diff --git a/GameDev/bin/Release/project_template/controls/constants.js b/GameDev/bin/Release/project_template/controls/constants.js deleted file mode 100644 index ef811450..00000000 --- a/GameDev/bin/Release/project_template/controls/constants.js +++ /dev/null @@ -1,2 +0,0 @@ -export const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; -export const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; diff --git a/GameDev/bin/Release/project_template/document.js b/GameDev/bin/Release/project_template/document.js deleted file mode 100644 index 1cc002dc..00000000 --- a/GameDev/bin/Release/project_template/document.js +++ /dev/null @@ -1,1719 +0,0 @@ -import { OrbitControls } from "./controls/OrbitControls.js"; -import { Vector3 } from "./math/Vector3.js"; -import { view, UIViewDispatcher } from "./view.js"; - -import * as txml from "./txml.js"; - -function string_to_boolean(string) { - switch (string.toLowerCase().trim()) { - case "true": - case "yes": - case "1": - return true; - - case "false": - case "no": - case "0": - case null: - return false; - - default: - return Boolean(string); - } -} - - -class JoyStick -{ - constructor(options) - { - let width = options.width; - let height = options.height; - this.center_x = width * 0.5; - this.center_y = height - 75.0; - - this.ui_area = new UIArea(); - this.ui_area.setOrigin(this.center_x-60.0, this.center_y - 60.0); - this.ui_area.setSize(120.0, 120.0); - UIManager.add(this.ui_area); - - this.circle = new UIPanel(); - this.circle.setOrigin(20.0, 20.0); - this.circle.setSize(80.0, 80.0); - this.circle.setStyle({cornerRadius:40.0, colorBg: "#7E7E7E7E"}); - this.ui_area.add(this.circle); - - this.thumb = new UIPanel(); - this.thumb.setOrigin(40.0, 40.0); - this.thumb.setSize(40.0, 40.0); - this.thumb.setStyle({cornerRadius:20.0, colorBg: "#FFFFFFFF", shadowOffset:0.0}); - this.ui_area.add(this.thumb); - - this.maxRadius = options.maxRadius || 40; - this.maxRadiusSquared = this.maxRadius * this.maxRadius; - this.onMove = options.onMove; - - const move = (x, y)=> - { - let delta_x = x - this.offset.x; - let delta_y = y - this.offset.y; - - const run_status = Math.abs(delta_x) - 50 >= 0 || Math.abs(delta_y) - 50 >= 0; - const sqMag = delta_x * delta_x + delta_y * delta_y; - if (sqMag > this.maxRadiusSquared) { - const magnitude = Math.sqrt(sqMag); - delta_x /= magnitude; - delta_y /= magnitude; - delta_x *= this.maxRadius; - delta_y *= this.maxRadius; - } - - this.thumb.setOrigin(40.0 + delta_x, 40.0 + delta_y); - - const forward = -delta_y / this.maxRadius; - const turn = delta_x / this.maxRadius; - - if (this.onMove != undefined) this.onMove(forward, turn, run_status); - } - - const up = (x, y) => - { - this.thumb.onPointerMove = null; - this.thumb.onPointerUp = null; - this.thumb.setOrigin(40.0, 40.0); - if (this.onMove != undefined) this.onMove(0,0,false); - gamePlayer.message("releasePointerCapture", ""); - } - - const tap = (x, y) => - { - this.offset = { x, y }; - this.thumb.onPointerMove = move; - this.thumb.onPointerUp = up; - gamePlayer.message("setPointerCapture", ""); - }; - - this.thumb.onPointerDown = tap; - - - } - - onResize(width, height) - { - let center_x = width * 0.5; - let center_y = height - 75.0; - if (center_x!=this.center_x || center_y!= this.center_y) - { - this.center_x = center_x; - this.center_y = center_y; - this.ui_area.setOrigin(this.center_x-60.0, this.center_y - 60.0); - } - } - - -} - -class AnimCrossFader -{ - constructor(fade_time) - { - this.mixer = new AnimationMixer(); - this.fade_time = fade_time || 0.5; - } - - add_clips(clips) - { - this.mixer.addAnimations(clips); - } - - set_current(clip_name) - { - this.start_time = now(); - this.mixer.startAnimation(clip_name); - } - - update_weights(weight_cur) - { - let lst_active = this.mixer.currentPlaying; - let weight_last = lst_active[lst_active.length - 1].weight; - let k = (1.0 - weight_cur)/(1.0-weight_last); - let weights = []; - for (let i=0; i< lst_active.length-1; i++) - { - let w = lst_active[i].weight * k; - weights.push(w); - } - weights.push(weight_cur); - this.mixer.setWeights(weights); - } - - get_frame() - { - let lst_active = this.mixer.currentPlaying; - if (lst_active.length<1) return; - if (lst_active.length>1) - { - let cur_time = now(); - let delta = cur_time - this.start_time; - let weight = 1.0; - if (delta0) - { - let i = getRandomInt(this.update_queue.length); - let idx = this.update_queue[i]; - this.update_queue.splice(i,1); - this.update_set.delete(idx); - - let x = idx; - let y = x / divisions.x; - let z = y / divisions.y; - y = y % divisions.y; - x = x % divisions.x; - let v_idx = new Vector3(x,y,z); - - renderer.updateProbe(this.doc.scene, this.cube_target, this.probe_grid, v_idx, 0.1, 100.0, 0.2); - } - } - -} - - -// Tags -const create_default_controls = (doc)=>{ - if (doc.controls) - doc.controls.dispose(); - doc.controls = new OrbitControls(doc.camera, doc.view); - doc.controls.enableDamping = true; - doc.controls.target.set(0, 1.5, 0); -} - - -const create_default_sky = (doc)=>{ - let bg = new HemisphereBackground(); - bg.setSkyColor(0.318, 0.318, 0.318); - bg.setGroundColor(0.01, 0.025, 0.025); - doc.scene.background = bg; -} - -const create_default_env_light = (doc) =>{ - let envLight = new HemisphereLight(); - envLight.setSkyColor(0.318, 0.318, 0.318); - envLight.setGroundColor(0.01, 0.025, 0.025); - doc.scene.indirectLight = envLight; -} - - -const scene = { - reset: (doc) => { - doc.scene = new Scene(); - }, - create: async (doc, props, mode, parent) => { - doc.scene = new Scene(); - create_default_sky(doc); - create_default_env_light(doc); - return doc.scene; - } -} - - -const camera = { - reset: (doc) => { - doc.camera = new PerspectiveCamera(45, doc.width / doc.height, 0.1, 100); - doc.camera.setPosition(0, 1.5, 5.0); - }, - - create: async (doc, props, mode, parent) => { - let fov = 50.0; - let near = 0.1; - let far = 200.0; - if (props.hasOwnProperty("fov")) - { - fov = parseFloat(props.fov); - } - if (props.hasOwnProperty("near")) - { - near = parseFloat(props.near); - } - if (props.hasOwnProperty("far")) - { - far = parseFloat(props.far); - } - doc.camera = new PerspectiveCamera(fov, doc.width / doc.height, near, far); - create_default_controls(doc); - return doc.camera; - } -} - -const control = { - reset: (doc) => { - create_default_controls(doc); - }, - create: async (doc, props, mode, parent) =>{ - let type = 'orbit'; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == 'orbit') - { - let from_x = 0.0; - let from_y = 1.5; - let from_z = 5.0; - if (props.hasOwnProperty("look_from")) - { - let look_from = props.look_from.split(','); - from_x = parseFloat(look_from[0]); - from_y = parseFloat(look_from[1]); - from_z = parseFloat(look_from[2]); - } - - let to_x = 0.0; - let to_y = 1.5; - let to_z = 0.0; - if (props.hasOwnProperty("look_at")) - { - let look_at = props.look_at.split(','); - to_x = parseFloat(look_at[0]); - to_y = parseFloat(look_at[1]); - to_z = parseFloat(look_at[2]); - } - - doc.camera.setPosition(from_x, from_y, from_z); - if (doc.controls != null) - doc.controls.dispose(); - doc.controls = new OrbitControls(doc.camera, doc.view); - doc.controls.enableDamping = true; - doc.controls.target.set(to_x, to_y, to_z); - } - } -} - -const fog = { - create: async (doc, props, mode, parent) =>{ - doc.scene.fog = new Fog(); - if (props.hasOwnProperty("density")) - { - doc.scene.fog.density = parseFloat(props.density); - } - return doc.scene.fog; - } -} - -const sky = { - reset: (doc) => { - create_default_sky(doc); - }, - create: async (doc, props, mode, parent) => { - let type = "hemisphere" - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == "uniform") - { - let bg = new ColorBackground(); - let envLight = null; - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setColor(r,g,b); - } - doc.scene.background = bg; - } - else if (type == "hemisphere") - { - let bg = new HemisphereBackground(); - - if (props.hasOwnProperty('skyColor')) - { - const color = props.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setSkyColor(r,g,b); - } - - if (props.hasOwnProperty('groundColor')) - { - const color = props.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setGroundColor(r,g,b); - } - doc.scene.background = bg; - - } - else if (type == "cube") - { - let bg = new CubeBackground(); - - let url = "assets/textures"; - let posx = "face0.jpg"; - let negx = "face1.jpg"; - let posy = "face2.jpg"; - let negy = "face3.jpg"; - let posz = "face4.jpg"; - let negz = "face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - if (cube_img!=null) - { - bg.setCubemap(cube_img); - } - doc.scene.background = bg; - } - else if (type == "scene") - { - let path_scene = "terrain.xml"; - if (props.hasOwnProperty('scene')) - { - path_scene = props.scene; - } - - let near = 10.0; - let far = 10000.0; - if (props.hasOwnProperty('near')) - { - near = parseFloat(props.near); - } - if (props.hasOwnProperty('far')) - { - far = parseFloat(props.far); - } - - let bg_doc = new BackgroundDocument(near, far); - await bg_doc.load_local_xml(path_scene); - doc.scene.background = bg_doc; - } - return doc.scene.background; - }, - remove: (doc, obj) => { - create_default_sky(doc); - } -} - -const env_light = { - reset: (doc) => { - create_default_env_light(doc); - doc.probeUpdater = null; - }, - create: async (doc, props, mode, parent) => { - let type = "hemisphere" - if (props.hasOwnProperty("type")) - { - type = props.type; - } - - if (type == "uniform") - { - let envLight = new AmbientLight(); - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setColor(r,g,b); - } - doc.scene.indirectLight = envLight; - } - else if (type == "hemisphere") - { - let envLight = new HemisphereLight(); - - if (props.hasOwnProperty('skyColor')) - { - const color = props.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setSkyColor(r,g,b); - } - - if (props.hasOwnProperty('groundColor')) - { - const color = props.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setGroundColor(r,g,b); - } - doc.scene.indirectLight = envLight; - } - else if (type == "cube") - { - let irradiance_only = false; - if (props.hasOwnProperty('irradiance_only')) - { - irradiance_only = string_to_boolean(props.irradiance_only); - } - - if (irradiance_only) - { - let path_sh = "assets/sh.json"; - if (props.hasOwnProperty('path_sh')) - { - path_sh = props.path_sh; - } - - let envLight = new EnvironmentMap(); - let text = fileLoader.loadTextFile(path_sh); - if (text!=null) - { - envLight.shCoefficients = JSON.parse(text); - } - doc.scene.indirectLight = envLight; - } - else - { - let url = "assets/textures"; - let posx = "env_face0.jpg"; - let negx = "env_face1.jpg"; - let posy = "env_face2.jpg"; - let negy = "env_face3.jpg"; - let posz = "env_face4.jpg"; - let negz = "env_face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - if (posx.split('.').pop()=="hdr") - { - let cube_img = HDRImageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - - doc.scene.indirectLight = envLight; - } - else - { - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - - doc.scene.indirectLight = envLight; - } - } - } - else if (type == "probe_grid") - { - let probe_data = "assets/probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let probe_grid = probeGridLoader.loadFile(probe_data); - if (probe_grid == null) - { - probe_grid = new ProbeGrid(); - - if (props.hasOwnProperty('divisions')) - { - const divisions = props.divisions.split(','); - probe_grid.setDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - if (props.hasOwnProperty('coverage_min')) - { - const coverage_min = props.coverage_min.split(','); - probe_grid.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - if (props.hasOwnProperty('coverage_max')) - { - const coverage_max = props.coverage_max.split(','); - probe_grid.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - if (props.hasOwnProperty('ypower')) - { - probe_grid.ypower = parseFloat(props.ypower); - } - } - - if (props.hasOwnProperty('normal_bias')) - { - probe_grid.normalBias = parseFloat(props.normal_bias); - } - - if (props.hasOwnProperty('per_primitive')) - { - probe_grid.perPrimitive =string_to_boolean(props.per_primitive); - } - - if (props.hasOwnProperty('auto_update') ) - { - doc.probeUpdater = new ProbeUpdater(doc, probe_grid); - } - - doc.scene.indirectLight = probe_grid; - } - else if (type == "lod_probe_grid") - { - let probe_data = "assets/lod_probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let probe_grid = LODProbeGridLoader.loadFile(probe_data); - if (probe_grid == null) - { - probe_grid = new LODProbeGrid(); - if (props.hasOwnProperty('base_divisions')) - { - const divisions = props.base_divisions.split(','); - probe_grid.setBaseDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - if (props.hasOwnProperty('coverage_min')) - { - const coverage_min = props.coverage_min.split(','); - probe_grid.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - if (props.hasOwnProperty('coverage_max')) - { - const coverage_max = props.coverage_max.split(','); - probe_grid.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - if (props.hasOwnProperty('sub_division_level')) - { - probe_grid.subDivisionLevel = parseFloat(props.sub_division_level); - } - } - - if (props.hasOwnProperty('normal_bias')) - { - probe_grid.normalBias = parseFloat(props.normal_bias); - } - - if (props.hasOwnProperty('per_primitive')) - { - probe_grid.perPrimitive =string_to_boolean(props.per_primitive); - } - doc.scene.indirectLight = probe_grid; - } - - if (props.hasOwnProperty('dynamic_map')) - { - doc.scene.indirectLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - - return doc.scene.indirectLight; - }, - remove: (doc, obj) => { - create_default_env_light(doc); - doc.probeUpdater = null; - }, -} - -const group = { - create: async (doc, props, mode, parent) => { - const group = new Object3D(); - if (parent != null) { - parent.add(group); - } - else { - doc.scene.add(group); - } - return group; - } -} - -const plane = { - create: async (doc, props, mode, parent) => { - let width = 1.0; - let height = 1.0; - if (props.hasOwnProperty('size')) - { - let size = props.size.split(','); - width = parseFloat(size[0]); - height = parseFloat(size[1]); - } - - const plane = new SimpleModel(); - plane.createPlane(width, height); - - if (parent != null) { - parent.add(plane); - } - else { - doc.scene.add(plane); - } - return plane; - } -} - - -const box = { - create: async (doc, props, mode, parent) => { - let width = 1.0; - let height = 1.0; - let depth = 1.0; - if (props.hasOwnProperty('size')) - { - let size = props.size.split(','); - width = parseFloat(size[0]); - height = parseFloat(size[1]); - depth = parseFloat(size[2]); - } - - const box = new SimpleModel(); - box.createBox(width, height, depth); - - if (parent != null) { - parent.add(box); - } - else { - doc.scene.add(box); - } - return box; - } -} - -const sphere = { - create: async (doc, props, mode, parent) => { - let radius = 1.0; - if (props.hasOwnProperty('radius')) - { - radius = parseFloat(props.radius); - } - let widthSegments = 32; - if (props.hasOwnProperty('widthSegments')) - { - widthSegments = parseInt(props.widthSegments); - } - let heightSegments = 16; - if (props.hasOwnProperty('heightSegments')) - { - heightSegments = parseInt(props.heightSegments); - } - - const sphere = new SimpleModel(); - sphere.createSphere(radius, widthSegments, heightSegments); - - if (parent != null) { - parent.add(sphere); - } - else { - doc.scene.add(sphere); - } - return sphere; - } -} - -const model = { - create: async (doc, props, mode, parent) => { - let url = "assets/models/model.glb"; - if (props.hasOwnProperty('src')) - { - url = props.src; - } - let model = gltfLoader.loadModelFromFile(url); - if (model == null) - { - model= new SimpleModel(); - model.createBox(0.5, 1.5, 0.5); - model.setColor(0.7,0.0,0.7); - } - else - { - if (props.hasOwnProperty('is_building') && string_to_boolean(props.is_building)) - { - model.batchPrimitives(); - } - - if (model.isBakable) - { - if (props.hasOwnProperty('lightmap')) - { - let filename = props.lightmap; - let ext = filename.split('.').pop().toLowerCase(); - if (ext=="hdr") - { - let hdr_img = HDRImageLoader.loadFile(filename); - if (hdr_img!=null) - { - model.setLightmap(hdr_img); - } - } - else if (ext=="dds") - { - let dds_img = DDSImageLoader.loadFile(filename); - if (dds_img!=null) - { - model.setLightmap(dds_img); - } - } - else if (ext=="png" || ext == "webp") - { - let img = imageLoader.loadFile(filename); - if (img!=null) - { - let hdr_img = HDRImageLoader.fromRGBM(img); - model.setLightmap(hdr_img); - } - } - else if (ext=="csv") - { - let text = fileLoader.loadTextFile(filename); - if (text!=null) - { - let path = filename.match(/(.*)[\/\\]/)[1]||''; - let images = []; - let ranges = []; - let lines = text.split(/\r?\n/); - for(let line of lines) - { - let fields = line.split(","); - if (fields.length<7) continue; - let fn_img = fields[0]; - let img = imageLoader.loadFile(path + "/" + fn_img); - if (img == null) continue; - let low = new Vector3(parseFloat(fields[1]), parseFloat(fields[2]), parseFloat(fields[3])); - let high = new Vector3(parseFloat(fields[4]), parseFloat(fields[5]), parseFloat(fields[6])); - images.push(img); - ranges.push({low, high}); - } - let hdr_img = HDRImageLoader.fromImages(images, ranges); - model.setLightmap(hdr_img); - } - } - } - } - } - - if (parent != null) { - parent.add(model); - } - else { - doc.scene.add(model); - } - return model; - } -} - -const avatar = { - create: async (doc, props, mode, parent) => { - let avatar = await model.create(doc, props, mode, parent); - doc.avatar = avatar; - if (!props.hasOwnProperty('lookat_height')) { - props.lookat_height = '1'; - } - - let lookat_height = parseFloat(props.lookat_height); - avatar.state = "idle"; - avatar.move = null; - - const name_idle = props.name_idle; - const name_forward = props.name_forward; - const name_backward = props.name_backward; - - cam = new Object3D(); - const camera_position = props.camera_position.split(','); - const [camx, camy, camz] = camera_position; - cam.setPosition(+camx, +camy, +camz); - avatar.add(cam); - - const anims = gltfLoader.loadAnimationsFromFile(props.url_anim); - if (props.hasOwnProperty('fix_anims')) { - doc.loaded_module[props.fix_anims](anims); - } - - let mixer = new AnimCrossFader(); - mixer.add_clips(anims); - mixer.set_current(name_idle); - avatar.cur_action = name_idle; - avatar.mixer = mixer; - - const onMove = (forward, turn, run_status)=> - { - avatar.move = { forward, turn}; - let action_changed = false; - let new_action = null; - - if (forward > 0) - { - if (avatar.state != "forward") - { - new_action = name_forward; - action_changed = true; - avatar.state = "forward"; - } - } - else if (forward < 0) - { - if (avatar.state != "backward") - { - new_action = name_backward; - action_changed = true; - avatar.state = "backward"; - } - } - else - { - if (avatar.state != "idle") - { - new_action = name_idle; - action_changed = true; - avatar.state = "idle"; - } - } - - if (action_changed) - { - mixer.set_current(new_action); - avatar.cur_action = new_action; - } - } - - const joystick = new JoyStick({ width: doc.width, height: doc.height, onMove: onMove}); - - if (doc.controls != null) { - doc.controls.dispose(); - doc.controls = null; - } - - const update_avatar = (doc, mixer, delta) => { - let frame = mixer.get_frame(); - avatar.setAnimationFrame(frame); - - joystick.onResize(doc.width, doc.height); - - if (avatar.move) - { - if (avatar.move.forward !=0) - { - let threshold = 0.4; - let movement = delta * avatar.move.forward * 2.0; - let pos = avatar.getPosition(new Vector3()); - pos.y += threshold; - - if (doc.building.length > 0 && movement !=0) - { - // cast front - { - let negated = false; - let dir = avatar.getWorldDirection(new Vector3()); - if (avatar.move.forward < 0) - { - dir.negate(); - negated = true; - } - - const intersect = doc.bvh.intersect({origin: pos, direction: dir}); - if (intersect!==null) - { - if (!negated) - { - if (movement > intersect.distance - 0.3) - { - movement = intersect.distance - 0.3; - } - } - else - { - if (-movement > intersect.distance - 0.3) - { - movement = 0.3 - intersect.distance; - } - } - } - } - } - - avatar.translateZ(movement); - pos = avatar.getPosition(new Vector3()); - pos.y += threshold; - - if (doc.building.length > 0) - { - if (movement !=0) - { - // cast up - { - let dir = new Vector3(0,1,0); - const intersect = doc.bvh.intersect({origin: pos, direction: dir}); - if (intersect!==null) - { - const targetY = threshold + intersect.distance; - if (targetY < 2.0) - { - avatar.translateZ(-movement); - pos = avatar.getPosition(new Vector3()); - pos.y += threshold; - } - } - } - - // cast left - { - let cast_from = avatar.localToWorld(new Vector3(0,0,0)); - let cast_to = avatar.localToWorld(new Vector3(1,0,0)); - let dir = new Vector3(); - dir.subVectors(cast_to, cast_from); - const intersect = doc.bvh.intersect({origin: pos, direction: dir}); - if (intersect!==null) - { - if (intersect.distance < 0.3) - { - avatar.translateX(intersect.distance - 0.3); - pos = avatar.getPosition(new Vector3()); - pos.y += threshold; - } - } - } - - // cast right - { - let cast_from = avatar.localToWorld(new Vector3(0,0,0)); - let cast_to = avatar.localToWorld(new Vector3(-1,0,0)); - let dir = new Vector3(); - dir.subVectors(cast_to, cast_from); - const intersect = doc.bvh.intersect({origin: pos, direction: dir}); - if (intersect!==null) - { - if (intersect.distance < 0.3) - { - avatar.translateX(0.3 - intersect.distance); - pos = avatar.getPosition(new Vector3()); - pos.y += threshold; - } - } - } - } - - - // cast down - { - let dir = new Vector3(0, -1, 0); - pos.y += 0.2; - const intersect = doc.bvh.intersect({origin: pos, direction: dir}); - - const gravity = 0.3; - if (intersect!==null) - { - const targetY = pos.y - intersect.distance; - if (targetY > avatar.position.y) { - //Going up - avatar.translateY(0.2 * (targetY - avatar.position.y)); - avatar.velocityY = 0; - } - else if (targetY < avatar.position.y){ - // Falling - if (avatar.velocityY == undefined) avatar.velocityY = 0; - avatar.velocityY += delta * gravity; - avatar.translateY(-avatar.velocityY); - if (avatar.position.y < targetY) { - avatar.velocityY = 0; - avatar.translateY(targetY - avatar.position.y); - } - } - } - } - } - } - if (avatar.move.turn != 0) - { - avatar.rotateY(-avatar.move.turn * delta); - } - } - let look_from = cam.getWorldPosition(new Vector3()); - let look_at = avatar.getWorldPosition(new Vector3()); - look_at.y += lookat_height; - - let dir = new Vector3(); - dir.subVectors(look_from, look_at); - let dis = dir.length(); - dir.normalize(); - const intersect = doc.bvh.intersect({origin: look_at, direction: dir}); - if (intersect!==null) - { - let max_dis = intersect.distance * 0.9 + doc.camera.near; - if (dis > max_dis) - { - dir.multiplyScalar(max_dis); - look_from.addVectors(look_at, dir); - } - } - let cam_pos = doc.camera.getPosition(new Vector3()); - cam_pos.lerp(look_from, 0.1); - doc.camera.setPosition(cam_pos); - doc.camera.lookAt(look_at); - - } - doc.set_tick(mixer, update_avatar); - - return avatar; - - }, - - remove: (doc, avatar) => - { - doc.remove_tick(avatar.mixer); - doc.avatar = null; - } -} - -const character = { - create: async (doc, props, mode, parent) => { - let character = await model.create(doc, props, mode, parent); - character.state = "idle"; - character.move = null; - character.name_idle = props.name_idle; - character.name_forward = props.name_forward; - character.name_backward = props.name_backward; - - const anims = gltfLoader.loadAnimationsFromFile(props.url_anim); - if (props.hasOwnProperty('fix_anims')) { - doc.loaded_module[props.fix_anims](anims); - } - - let mixer = new AnimCrossFader(); - mixer.add_clips(anims); - mixer.set_current(character.name_idle); - character.cur_action = character.name_idle; - character.mixer = mixer; - - const update_character = (doc, mixer, delta) => { - let frame = mixer.get_frame(); - character.setAnimationFrame(frame); - }; - doc.set_tick(mixer, update_character); - - return character; - }, - - remove: (doc, character) => - { - doc.remove_tick(character.mixer); - }, - - set_state: (doc, character, state) => { - let new_action = null; - if (state == 'idle') { - new_action = character.name_idle; - } - else if (state == 'forward') { - new_action = character.name_forward; - } - else if (state == 'backward') { - new_action = character.name_backward; - } - character.mixer.set_current(new_action); - character.state = state; - } -} - -const directional_light = { - create: async (doc, props, mode, parent) => { - const light = new DirectionalLight(); - - if (props.hasOwnProperty('intensity')) { - light.intensity = parseFloat(props.intensity); - } - - if (props.hasOwnProperty('target')){ - let target = doc.scene.getObjectByName(props.target); - light.target = target; - } - - if (props.hasOwnProperty('castShadow') && string_to_boolean(props.castShadow)) - { - let width = 512; - let height = 512; - if (props.hasOwnProperty('size')) { - const size = props.size.split(','); - width = parseInt(size[0]); - height = parseInt(size[1]); - } - light.setShadow(true, width, height); - - if (props.hasOwnProperty('area')) { - const area = props.area.split(','); - let left = parseFloat(area[0]); - let right = parseFloat(area[1]); - let top = parseFloat(area[2]); - let bottom = parseFloat(area[3]); - let near = parseFloat(area[4]); - let far = parseFloat(area[5]); - light.setShadowProjection(left, right, top, bottom, near, far); - } - - if (props.hasOwnProperty('radius')) - { - let radius = parseFloat(props.radius); - light.setShadowRadius(radius); - } - - if (props.hasOwnProperty('bias')) - { - light.bias = parseFloat(props.bias); - } - - if (props.hasOwnProperty('force_cull')) - { - light.forceCull = string_to_boolean(props.force_cull); - } - } - - if (parent != null) { - parent.add(light); - } - else { - doc.scene.add(light); - } - return light; - } -} - -class BackgroundDocument extends BackgroundScene -{ - constructor(near, far) - { - super(null, near, far); - - this.Tags = { scene, sky, env_light, group, plane, box, sphere, model, directional_light }; - this.reset(); - } - - reset() - { - for (let tag in this.Tags) - { - if (this.Tags[tag].hasOwnProperty('reset')) - { - this.Tags[tag].reset(this); - } - } - } - - async create(tag, props, mode, parent = null) - { - if (!(tag in this.Tags)) return null; - - const obj = await this.Tags[tag].create(this, props, mode, parent); - if (obj == null) return null; - - if (Object.isExtensible(obj)) - { - obj.tag = tag; - } - - if (props.hasOwnProperty('name')) - { - obj.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if (props.hasOwnProperty('texture')) - { - let img = imageLoader.loadFile(props.texture); - if (img!=null) - { - obj.setColorTexture(img); - } - } - - if (props.hasOwnProperty('metalness')) - { - obj.metalness = parseFloat(props.metalness); - } - - if (props.hasOwnProperty('roughness')) - { - obj.roughness = parseFloat(props.roughness); - } - - return obj; - } - - async load_xml_node(xmlNode, mode, parent = null) - { - if (parent == null) { - parent = this; - } - for (let child of xmlNode.children) { - const obj = await this.create(child.tagName, child.attributes, mode, parent); - if (obj===null) continue; - await this.load_xml_node(child, mode, obj); - } - - } - - async load_xml(xmlText, mode) - { - const parsed = txml.parse(xmlText); - let root = null; - for (let top of parsed) - { - if (top.tagName == 'document') - { - root = top; - break; - } - } - if (root) - { - await this.load_xml_node(root, mode); - } - } - - async load_local_xml(filename) - { - const xmlText = fileLoader.loadTextFile(filename); - if (xmlText!=null) - { - await this.load_xml(xmlText, "local"); - } - } -} - - -export class Document -{ - constructor(view) - { - this.view = view; - this.width = view.clientWidth; - this.height = view.clientHeight; - this.Tags = { scene, camera, fog, sky, env_light, control, group, plane, box, sphere, model, avatar, character, directional_light }; - this.reset(); - } - - setSize(width, height) - { - this.width = width; - this.height = height; - - if (this.camera) - { - this.camera.aspect = width / height; - this.camera.updateProjectionMatrix(); - } - } - - reset() - { - if (this.unloadables) - { - for (const object of this.unloadables) - { - object.unload(this, object); - } - } - - this.unloadables = []; - this.updatables = []; - this.building = []; - - for (let tag in this.Tags) - { - if (this.Tags[tag].hasOwnProperty('reset')) - { - this.Tags[tag].reset(this); - } - } - - this.loaded_module = null; - } - - tick(delta) - { - if (this.controls) - { - if (this.controls.hasOwnProperty('update')) - { - this.controls.update(); - } - } - - for (const object of this.updatables) - { - if (object.tick) - { - object.tick(this, object, delta); - } - } - } - - render(renderer) - { - if (this.scene && this.camera) - { - renderer.render(this.scene, this.camera); - } - - if (this.probeUpdater!=null) - { - this.probeUpdater.render(renderer); - } - } - - set_unload(obj, func) - { - obj.unload = func; - this.unloadables.push(obj); - } - - remove_unload(obj) - { - for (let i = 0; i < this.unloadables.length; i++) - { - if (this.unloadables[i] == obj) - { - this.unloadables.splice(i, 1); - i--; - } - } - } - - set_tick(obj, func) - { - obj.tick = func; - this.updatables.push(obj); - } - - remove_tick(obj) - { - for (let i = 0; i < this.updatables.length; i++) - { - if (this.updatables[i] == obj) - { - this.updatables.splice(i, 1); - i--; - } - } - } - - add_building_object(obj) { - this.building.push(obj); - } - - remove_building_object(obj) { - for (let i = 0; i < this.building.length; i++) { - if (this.building[i] == obj) { - this.building.splice(i, 1); - i--; - } - } - } - - async create(tag, props, mode, parent = null) - { - if (!(tag in this.Tags)) return null; - - const obj = await this.Tags[tag].create(this, props, mode, parent); - if (obj == null) return null; - - if (Object.isExtensible(obj)) - { - obj.tag = tag; - } - - if (props.hasOwnProperty('name')) - { - obj.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if (props.hasOwnProperty('texture')) - { - let img = imageLoader.loadFile(props.texture); - if (img!=null) - { - obj.setColorTexture(img); - } - } - - if (props.hasOwnProperty('metalness')) - { - obj.metalness = parseFloat(props.metalness); - } - - if (props.hasOwnProperty('roughness')) - { - obj.roughness = parseFloat(props.roughness); - } - - if (props.hasOwnProperty('is_building') && string_to_boolean(props.is_building)) - { - obj.isBuilding = true; - this.add_building_object(obj); - } - - if (props.hasOwnProperty('ontick')) - { - this.set_tick(obj, this.loaded_module[props.ontick]); - } - - if (props.hasOwnProperty('onload')) - { - obj.load = this.loaded_module[props.onload]; - } - - if (props.hasOwnProperty('onunload')) - { - this.set_unload(obj, this.loaded_module[props.onunload]); - } - - return obj; - } - - remove(obj) - { - const doc = this; - obj.traverse((child) => { - this.remove_unload(child); - this.remove_tick(child); - this.remove_building_object(child); - if (child.hasOwnProperty('tag')) { - const tag = this.Tags[child.tag]; - if (tag.hasOwnProperty('remove')) { - tag.remove(this, obj); - } - } - }); - if (obj.parent) - { - obj.parent.remove(obj); - } - } - - async load_xml_node(xmlNode, mode, parent = null) - { - if (parent == null) { - parent = this; - } - for (let child of xmlNode.children) { - const obj = await this.create(child.tagName, child.attributes, mode, parent); - if (obj===null) continue; - await this.load_xml_node(child, mode, obj); - if (obj.load) { - obj.load(this, obj); - } - } - - } - - async load_xml(xmlText, mode) - { - const parsed = txml.parse(xmlText); - let root = null; - for (let top of parsed) - { - if (top.tagName == 'document') - { - root = top; - break; - } - } - if (root) - { - await this.load_xml_node(root, mode); - } - - if (this.building.length>0) - { - this.bvh = new BoundingVolumeHierarchy(this.building); - } - else - { - this.bvh = null; - } - } - - async load_local_xml(filename) - { - const xmlText = fileLoader.loadTextFile(filename); - await this.load_xml(xmlText, "local"); - } - - async load(module) - { - this.reset(); - this.loaded_module = module; - await module.load(this); - } - -} diff --git a/GameDev/bin/Release/project_template/index.js b/GameDev/bin/Release/project_template/index.js deleted file mode 100644 index 6b4d6aca..00000000 --- a/GameDev/bin/Release/project_template/index.js +++ /dev/null @@ -1,27 +0,0 @@ -import { Document } from "./document.js"; -import { Clock } from "./utils/Clock.js"; -import { view } from "./view.js"; - -import * as module from "./scene.js"; - -async function init(width, height) { - renderer = new GLRenderer(); - doc = new Document(view); - clock = new Clock(); - - await doc.load(module); -} - -function render(width, height, size_changed) { - if (size_changed) - { - doc.setSize(width, height); - } - let delta = clock.getDelta(); - doc.tick(delta); - doc.render(renderer); -} - -setCallback('init', init); -setCallback('render', render); - diff --git a/GameDev/bin/Release/project_template/math/Box2.js b/GameDev/bin/Release/project_template/math/Box2.js deleted file mode 100644 index 02dcaa92..00000000 --- a/GameDev/bin/Release/project_template/math/Box2.js +++ /dev/null @@ -1,203 +0,0 @@ -import { Vector2 } from './Vector2.js'; - -const _vector = /*@__PURE__*/ new Vector2(); - -class Box2 { - - constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { - - this.min = min; - this.max = max; - - } - - set( min, max ) { - - this.min.copy( min ); - this.max.copy( max ); - - return this; - - } - - setFromPoints( points ) { - - this.makeEmpty(); - - for ( let i = 0, il = points.length; i < il; i ++ ) { - - this.expandByPoint( points[ i ] ); - - } - - return this; - - } - - setFromCenterAndSize( center, size ) { - - const halfSize = _vector.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - } - - makeEmpty() { - - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; - - return this; - - } - - isEmpty() { - - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - - } - - getCenter( target ) { - - return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - - } - - getSize( target ) { - - return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); - - } - - expandByPoint( point ) { - - this.min.min( point ); - this.max.max( point ); - - return this; - - } - - expandByVector( vector ) { - - this.min.sub( vector ); - this.max.add( vector ); - - return this; - - } - - expandByScalar( scalar ) { - - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); - - return this; - - } - - containsPoint( point ) { - - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ? false : true; - - } - - containsBox( box ) { - - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y; - - } - - getParameter( point, target ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - - return target.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); - - } - - intersectsBox( box ) { - - // using 4 splitting planes to rule out intersections - - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ? false : true; - - } - - clampPoint( point, target ) { - - return target.copy( point ).clamp( this.min, this.max ); - - } - - distanceToPoint( point ) { - - const clampedPoint = _vector.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); - - } - - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); - - return this; - - } - - union( box ) { - - this.min.min( box.min ); - this.max.max( box.max ); - - return this; - - } - - translate( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; - - } - - equals( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - } - -} - -Box2.prototype.isBox2 = true; - -export { Box2 }; diff --git a/GameDev/bin/Release/project_template/math/Box3.js b/GameDev/bin/Release/project_template/math/Box3.js deleted file mode 100644 index 1a5e4ffd..00000000 --- a/GameDev/bin/Release/project_template/math/Box3.js +++ /dev/null @@ -1,518 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -class Box3 { - - constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { - - this.min = min; - this.max = max; - - } - - set( min, max ) { - - this.min.copy( min ); - this.max.copy( max ); - - return this; - - } - - setFromArray( array ) { - - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; - - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; - - for ( let i = 0, l = array.length; i < l; i += 3 ) { - - const x = array[ i ]; - const y = array[ i + 1 ]; - const z = array[ i + 2 ]; - - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; - - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; - - } - - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); - - return this; - - } - - setFromBufferAttribute( attribute ) { - - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; - - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; - - for ( let i = 0, l = attribute.count; i < l; i ++ ) { - - const x = attribute.getX( i ); - const y = attribute.getY( i ); - const z = attribute.getZ( i ); - - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; - - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; - - } - - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); - - return this; - - } - - setFromPoints( points ) { - - this.makeEmpty(); - - for ( let i = 0, il = points.length; i < il; i ++ ) { - - this.expandByPoint( points[ i ] ); - - } - - return this; - - } - - setFromCenterAndSize( center, size ) { - - const halfSize = _vector.copy( size ).multiplyScalar( 0.5 ); - - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - - return this; - - } - - setFromObject( object ) { - - this.makeEmpty(); - - return this.expandByObject( object ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - } - - makeEmpty() { - - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; - - return this; - - } - - isEmpty() { - - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - - } - - getCenter( target ) { - - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - - } - - getSize( target ) { - - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); - - } - - expandByPoint( point ) { - - this.min.min( point ); - this.max.max( point ); - - return this; - - } - - expandByVector( vector ) { - - this.min.sub( vector ); - this.max.add( vector ); - - return this; - - } - - expandByScalar( scalar ) { - - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); - - return this; - - } - - expandByObject( object ) { - - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms - - object.updateWorldMatrix( false, false ); - - const geometry = object.geometry; - - if ( geometry !== undefined ) { - - if ( geometry.boundingBox === null ) { - - geometry.computeBoundingBox(); - - } - - _box.copy( geometry.boundingBox ); - _box.applyMatrix4( object.matrixWorld ); - - this.union( _box ); - - } - - const children = object.children; - - for ( let i = 0, l = children.length; i < l; i ++ ) { - - this.expandByObject( children[ i ] ); - - } - - return this; - - } - - containsPoint( point ) { - - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ? false : true; - - } - - containsBox( box ) { - - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y && - this.min.z <= box.min.z && box.max.z <= this.max.z; - - } - - getParameter( point, target ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - - return target.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ), - ( point.z - this.min.z ) / ( this.max.z - this.min.z ) - ); - - } - - intersectsBox( box ) { - - // using 6 splitting planes to rule out intersections. - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y || - box.max.z < this.min.z || box.min.z > this.max.z ? false : true; - - } - - intersectsSphere( sphere ) { - - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, _vector ); - - // If that point is inside the sphere, the AABB and sphere intersect. - return _vector.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - - } - - intersectsPlane( plane ) { - - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. - - let min, max; - - if ( plane.normal.x > 0 ) { - - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; - - } else { - - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; - - } - - if ( plane.normal.y > 0 ) { - - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; - - } else { - - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; - - } - - if ( plane.normal.z > 0 ) { - - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; - - } else { - - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; - - } - - return ( min <= - plane.constant && max >= - plane.constant ); - - } - - intersectsTriangle( triangle ) { - - if ( this.isEmpty() ) { - - return false; - - } - - // compute box center and extents - this.getCenter( _center ); - _extents.subVectors( this.max, _center ); - - // translate triangle to aabb origin - _v0.subVectors( triangle.a, _center ); - _v1.subVectors( triangle.b, _center ); - _v2.subVectors( triangle.c, _center ); - - // compute edge vectors for triangle - _f0.subVectors( _v1, _v0 ); - _f1.subVectors( _v2, _v1 ); - _f2.subVectors( _v0, _v2 ); - - // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb - // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation - // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) - let axes = [ - 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, - _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, - - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 - ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { - - return false; - - } - - // test 3 face normals from the aabb - axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { - - return false; - - } - - // finally testing the face normal of the triangle - // use already existing triangle edge vectors here - _triangleNormal.crossVectors( _f0, _f1 ); - axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; - - return satForAxes( axes, _v0, _v1, _v2, _extents ); - - } - - clampPoint( point, target ) { - - return target.copy( point ).clamp( this.min, this.max ); - - } - - distanceToPoint( point ) { - - const clampedPoint = _vector.copy( point ).clamp( this.min, this.max ); - - return clampedPoint.sub( point ).length(); - - } - - getBoundingSphere( target ) { - - this.getCenter( target.center ); - - target.radius = this.getSize( _vector ).length() * 0.5; - - return target; - - } - - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); - - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if ( this.isEmpty() ) this.makeEmpty(); - - return this; - - } - - union( box ) { - - this.min.min( box.min ); - this.max.max( box.max ); - - return this; - - } - - applyMatrix4( matrix ) { - - // transform of empty box is an empty box. - if ( this.isEmpty() ) return this; - - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - - this.setFromPoints( _points ); - - return this; - - } - - translate( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; - - } - - equals( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - } - -} - -Box3.prototype.isBox3 = true; - -const _points = [ - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3() -]; - -const _vector = /*@__PURE__*/ new Vector3(); - -const _box = /*@__PURE__*/ new Box3(); - -// triangle centered vertices - -const _v0 = /*@__PURE__*/ new Vector3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _v2 = /*@__PURE__*/ new Vector3(); - -// triangle edge vectors - -const _f0 = /*@__PURE__*/ new Vector3(); -const _f1 = /*@__PURE__*/ new Vector3(); -const _f2 = /*@__PURE__*/ new Vector3(); - -const _center = /*@__PURE__*/ new Vector3(); -const _extents = /*@__PURE__*/ new Vector3(); -const _triangleNormal = /*@__PURE__*/ new Vector3(); -const _testAxis = /*@__PURE__*/ new Vector3(); - -function satForAxes( axes, v0, v1, v2, extents ) { - - for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { - - _testAxis.fromArray( axes, i ); - // project the aabb onto the seperating axis - const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); - // project all 3 vertices of the triangle onto the seperating axis - const p0 = v0.dot( _testAxis ); - const p1 = v1.dot( _testAxis ); - const p2 = v2.dot( _testAxis ); - // actual test, basically see if either of the most extreme of the triangle points intersects r - if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { - - // points of the projected triangle are outside the projected half-length of the aabb - // the axis is seperating and we can exit - return false; - - } - - } - - return true; - -} - -export { Box3 }; diff --git a/GameDev/bin/Release/project_template/math/Color.js b/GameDev/bin/Release/project_template/math/Color.js deleted file mode 100644 index 295c60e1..00000000 --- a/GameDev/bin/Release/project_template/math/Color.js +++ /dev/null @@ -1,604 +0,0 @@ -import * as MathUtils from './MathUtils.js'; - -const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, - 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, - 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, - 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, - 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, - 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, - 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, - 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, - 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, - 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, - 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, - 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, - 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, - 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, - 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, - 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, - 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, - 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, - 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, - 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, - 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, - 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, - 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, - 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - -const _hslA = { h: 0, s: 0, l: 0 }; -const _hslB = { h: 0, s: 0, l: 0 }; - -function hue2rgb( p, q, t ) { - - if ( t < 0 ) t += 1; - if ( t > 1 ) t -= 1; - if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; - if ( t < 1 / 2 ) return q; - if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); - return p; - -} - -function SRGBToLinear( c ) { - - return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); - -} - -function LinearToSRGB( c ) { - - return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; - -} - -class Color { - - constructor( r, g, b ) { - - if ( g === undefined && b === undefined ) { - - // r is THREE.Color, hex or string - return this.set( r ); - - } - - return this.setRGB( r, g, b ); - - } - - set( value ) { - - if ( value && value.isColor ) { - - this.copy( value ); - - } else if ( typeof value === 'number' ) { - - this.setHex( value ); - - } else if ( typeof value === 'string' ) { - - this.setStyle( value ); - - } - - return this; - - } - - setScalar( scalar ) { - - this.r = scalar; - this.g = scalar; - this.b = scalar; - - return this; - - } - - setHex( hex ) { - - hex = Math.floor( hex ); - - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; - - return this; - - } - - setRGB( r, g, b ) { - - this.r = r; - this.g = g; - this.b = b; - - return this; - - } - - setHSL( h, s, l ) { - - // h,s,l ranges are in 0.0 - 1.0 - h = MathUtils.euclideanModulo( h, 1 ); - s = MathUtils.clamp( s, 0, 1 ); - l = MathUtils.clamp( l, 0, 1 ); - - if ( s === 0 ) { - - this.r = this.g = this.b = l; - - } else { - - const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - const q = ( 2 * l ) - p; - - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); - - } - - return this; - - } - - setStyle( style ) { - - function handleAlpha( string ) { - - if ( string === undefined ) return; - - if ( parseFloat( string ) < 1 ) { - - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - - } - - } - - - let m; - - if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { - - // rgb / hsl - - let color; - const name = m[ 1 ]; - const components = m[ 2 ]; - - switch ( name ) { - - case 'rgb': - case 'rgba': - - if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - - // rgb(255,0,0) rgba(255,0,0,0.5) - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - - handleAlpha( color[ 4 ] ); - - return this; - - } - - if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - - handleAlpha( color[ 4 ] ); - - return this; - - } - - break; - - case 'hsl': - case 'hsla': - - if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - const h = parseFloat( color[ 1 ] ) / 360; - const s = parseInt( color[ 2 ], 10 ) / 100; - const l = parseInt( color[ 3 ], 10 ) / 100; - - handleAlpha( color[ 4 ] ); - - return this.setHSL( h, s, l ); - - } - - break; - - } - - } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { - - // hex color - - const hex = m[ 1 ]; - const size = hex.length; - - if ( size === 3 ) { - - // #ff0 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; - - return this; - - } else if ( size === 6 ) { - - // #ff0000 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - - return this; - - } - - } - - if ( style && style.length > 0 ) { - - return this.setColorName( style ); - - } - - return this; - - } - - setColorName( style ) { - - // color keywords - const hex = _colorKeywords[ style.toLowerCase() ]; - - if ( hex !== undefined ) { - - // red - this.setHex( hex ); - - } else { - - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); - - } - - return this; - - } - - clone() { - - return new this.constructor( this.r, this.g, this.b ); - - } - - copy( color ) { - - this.r = color.r; - this.g = color.g; - this.b = color.b; - - return this; - - } - - copyGammaToLinear( color, gammaFactor = 2.0 ) { - - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); - - return this; - - } - - copyLinearToGamma( color, gammaFactor = 2.0 ) { - - const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); - - return this; - - } - - convertGammaToLinear( gammaFactor ) { - - this.copyGammaToLinear( this, gammaFactor ); - - return this; - - } - - convertLinearToGamma( gammaFactor ) { - - this.copyLinearToGamma( this, gammaFactor ); - - return this; - - } - - copySRGBToLinear( color ) { - - this.r = SRGBToLinear( color.r ); - this.g = SRGBToLinear( color.g ); - this.b = SRGBToLinear( color.b ); - - return this; - - } - - copyLinearToSRGB( color ) { - - this.r = LinearToSRGB( color.r ); - this.g = LinearToSRGB( color.g ); - this.b = LinearToSRGB( color.b ); - - return this; - - } - - convertSRGBToLinear() { - - this.copySRGBToLinear( this ); - - return this; - - } - - convertLinearToSRGB() { - - this.copyLinearToSRGB( this ); - - return this; - - } - - getHex() { - - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - - } - - getHexString() { - - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - - } - - getHSL( target ) { - - // h,s,l ranges are in 0.0 - 1.0 - - const r = this.r, g = this.g, b = this.b; - - const max = Math.max( r, g, b ); - const min = Math.min( r, g, b ); - - let hue, saturation; - const lightness = ( min + max ) / 2.0; - - if ( min === max ) { - - hue = 0; - saturation = 0; - - } else { - - const delta = max - min; - - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - - switch ( max ) { - - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; - - } - - hue /= 6; - - } - - target.h = hue; - target.s = saturation; - target.l = lightness; - - return target; - - } - - getStyle() { - - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - - } - - offsetHSL( h, s, l ) { - - this.getHSL( _hslA ); - - _hslA.h += h; _hslA.s += s; _hslA.l += l; - - this.setHSL( _hslA.h, _hslA.s, _hslA.l ); - - return this; - - } - - add( color ) { - - this.r += color.r; - this.g += color.g; - this.b += color.b; - - return this; - - } - - addColors( color1, color2 ) { - - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; - - return this; - - } - - addScalar( s ) { - - this.r += s; - this.g += s; - this.b += s; - - return this; - - } - - sub( color ) { - - this.r = Math.max( 0, this.r - color.r ); - this.g = Math.max( 0, this.g - color.g ); - this.b = Math.max( 0, this.b - color.b ); - - return this; - - } - - multiply( color ) { - - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; - - return this; - - } - - multiplyScalar( s ) { - - this.r *= s; - this.g *= s; - this.b *= s; - - return this; - - } - - lerp( color, alpha ) { - - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; - - return this; - - } - - lerpColors( color1, color2, alpha ) { - - this.r = color1.r + ( color2.r - color1.r ) * alpha; - this.g = color1.g + ( color2.g - color1.g ) * alpha; - this.b = color1.b + ( color2.b - color1.b ) * alpha; - - return this; - - } - - lerpHSL( color, alpha ) { - - this.getHSL( _hslA ); - color.getHSL( _hslB ); - - const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha ); - const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha ); - const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha ); - - this.setHSL( h, s, l ); - - return this; - - } - - equals( c ) { - - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - - } - - fromArray( array, offset = 0 ) { - - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; - - return array; - - } - - fromBufferAttribute( attribute, index ) { - - this.r = attribute.getX( index ); - this.g = attribute.getY( index ); - this.b = attribute.getZ( index ); - - if ( attribute.normalized === true ) { - - // assuming Uint8Array - - this.r /= 255; - this.g /= 255; - this.b /= 255; - - } - - return this; - - } - - toJSON() { - - return this.getHex(); - - } - -} - -Color.NAMES = _colorKeywords; - -Color.prototype.isColor = true; -Color.prototype.r = 1; -Color.prototype.g = 1; -Color.prototype.b = 1; - -export { Color }; diff --git a/GameDev/bin/Release/project_template/math/Cylindrical.js b/GameDev/bin/Release/project_template/math/Cylindrical.js deleted file mode 100644 index d1288244..00000000 --- a/GameDev/bin/Release/project_template/math/Cylindrical.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system - */ - -class Cylindrical { - - constructor( radius = 1, theta = 0, y = 0 ) { - - this.radius = radius; // distance from the origin to a point in the x-z plane - this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis - this.y = y; // height above the x-z plane - - return this; - - } - - set( radius, theta, y ) { - - this.radius = radius; - this.theta = theta; - this.y = y; - - return this; - - } - - copy( other ) { - - this.radius = other.radius; - this.theta = other.theta; - this.y = other.y; - - return this; - - } - - setFromVector3( v ) { - - return this.setFromCartesianCoords( v.x, v.y, v.z ); - - } - - setFromCartesianCoords( x, y, z ) { - - this.radius = Math.sqrt( x * x + z * z ); - this.theta = Math.atan2( x, z ); - this.y = y; - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Cylindrical }; diff --git a/GameDev/bin/Release/project_template/math/Euler.js b/GameDev/bin/Release/project_template/math/Euler.js deleted file mode 100644 index 74c93a8a..00000000 --- a/GameDev/bin/Release/project_template/math/Euler.js +++ /dev/null @@ -1,322 +0,0 @@ -import { Quaternion } from './Quaternion.js'; -import { Vector3 } from './Vector3.js'; -import { Matrix4 } from './Matrix4.js'; -import { clamp } from './MathUtils.js'; - -const _matrix = /*@__PURE__*/ new Matrix4(); -const _quaternion = /*@__PURE__*/ new Quaternion(); - -class Euler { - - constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { - - this._x = x; - this._y = y; - this._z = z; - this._order = order; - - } - - get x() { - - return this._x; - - } - - set x( value ) { - - this._x = value; - this._onChangeCallback(); - - } - - get y() { - - return this._y; - - } - - set y( value ) { - - this._y = value; - this._onChangeCallback(); - - } - - get z() { - - return this._z; - - } - - set z( value ) { - - this._z = value; - this._onChangeCallback(); - - } - - get order() { - - return this._order; - - } - - set order( value ) { - - this._order = value; - this._onChangeCallback(); - - } - - set( x, y, z, order = this._order ) { - - this._x = x; - this._y = y; - this._z = z; - this._order = order; - - this._onChangeCallback(); - - return this; - - } - - clone() { - - return new this.constructor( this._x, this._y, this._z, this._order ); - - } - - copy( euler ) { - - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; - - this._onChangeCallback(); - - return this; - - } - - setFromRotationMatrix( m, order = this._order, update = true ) { - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - const te = m.elements; - const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - - switch ( order ) { - - case 'XYZ': - - this._y = Math.asin( clamp( m13, - 1, 1 ) ); - - if ( Math.abs( m13 ) < 0.9999999 ) { - - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); - - } else { - - this._x = Math.atan2( m32, m22 ); - this._z = 0; - - } - - break; - - case 'YXZ': - - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - - if ( Math.abs( m23 ) < 0.9999999 ) { - - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); - - } else { - - this._y = Math.atan2( - m31, m11 ); - this._z = 0; - - } - - break; - - case 'ZXY': - - this._x = Math.asin( clamp( m32, - 1, 1 ) ); - - if ( Math.abs( m32 ) < 0.9999999 ) { - - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); - - } else { - - this._y = 0; - this._z = Math.atan2( m21, m11 ); - - } - - break; - - case 'ZYX': - - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - - if ( Math.abs( m31 ) < 0.9999999 ) { - - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); - - } else { - - this._x = 0; - this._z = Math.atan2( - m12, m22 ); - - } - - break; - - case 'YZX': - - this._z = Math.asin( clamp( m21, - 1, 1 ) ); - - if ( Math.abs( m21 ) < 0.9999999 ) { - - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); - - } else { - - this._x = 0; - this._y = Math.atan2( m13, m33 ); - - } - - break; - - case 'XZY': - - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - - if ( Math.abs( m12 ) < 0.9999999 ) { - - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); - - } else { - - this._x = Math.atan2( - m23, m33 ); - this._y = 0; - - } - - break; - - default: - - console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); - - } - - this._order = order; - - if ( update === true ) this._onChangeCallback(); - - return this; - - } - - setFromQuaternion( q, order, update ) { - - _matrix.makeRotationFromQuaternion( q ); - - return this.setFromRotationMatrix( _matrix, order, update ); - - } - - setFromVector3( v, order = this._order ) { - - return this.set( v.x, v.y, v.z, order ); - - } - - reorder( newOrder ) { - - // WARNING: this discards revolution information -bhouston - - _quaternion.setFromEuler( this ); - - return this.setFromQuaternion( _quaternion, newOrder ); - - } - - equals( euler ) { - - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - - } - - fromArray( array ) { - - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - - this._onChangeCallback(); - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; - - return array; - - } - - toVector3( optionalResult ) { - - if ( optionalResult ) { - - return optionalResult.set( this._x, this._y, this._z ); - - } else { - - return new Vector3( this._x, this._y, this._z ); - - } - - } - - _onChange( callback ) { - - this._onChangeCallback = callback; - - return this; - - } - - _onChangeCallback() {} - -} - -Euler.prototype.isEuler = true; - -Euler.DefaultOrder = 'XYZ'; -Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - -export { Euler }; diff --git a/GameDev/bin/Release/project_template/math/Frustum.js b/GameDev/bin/Release/project_template/math/Frustum.js deleted file mode 100644 index fc6b928a..00000000 --- a/GameDev/bin/Release/project_template/math/Frustum.js +++ /dev/null @@ -1,162 +0,0 @@ -import { Vector3 } from './Vector3.js'; -import { Sphere } from './Sphere.js'; -import { Plane } from './Plane.js'; - -const _sphere = /*@__PURE__*/ new Sphere(); -const _vector = /*@__PURE__*/ new Vector3(); - -class Frustum { - - constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { - - this.planes = [ p0, p1, p2, p3, p4, p5 ]; - - } - - set( p0, p1, p2, p3, p4, p5 ) { - - const planes = this.planes; - - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); - - return this; - - } - - copy( frustum ) { - - const planes = this.planes; - - for ( let i = 0; i < 6; i ++ ) { - - planes[ i ].copy( frustum.planes[ i ] ); - - } - - return this; - - } - - setFromProjectionMatrix( m ) { - - const planes = this.planes; - const me = m.elements; - const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; - const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; - const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; - const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; - - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - - return this; - - } - - intersectsObject( object ) { - - const geometry = object.geometry; - - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - - _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); - - return this.intersectsSphere( _sphere ); - - } - - intersectsSprite( sprite ) { - - _sphere.center.set( 0, 0, 0 ); - _sphere.radius = 0.7071067811865476; - _sphere.applyMatrix4( sprite.matrixWorld ); - - return this.intersectsSphere( _sphere ); - - } - - intersectsSphere( sphere ) { - - const planes = this.planes; - const center = sphere.center; - const negRadius = - sphere.radius; - - for ( let i = 0; i < 6; i ++ ) { - - const distance = planes[ i ].distanceToPoint( center ); - - if ( distance < negRadius ) { - - return false; - - } - - } - - return true; - - } - - intersectsBox( box ) { - - const planes = this.planes; - - for ( let i = 0; i < 6; i ++ ) { - - const plane = planes[ i ]; - - // corner at max distance - - _vector.x = plane.normal.x > 0 ? box.max.x : box.min.x; - _vector.y = plane.normal.y > 0 ? box.max.y : box.min.y; - _vector.z = plane.normal.z > 0 ? box.max.z : box.min.z; - - if ( plane.distanceToPoint( _vector ) < 0 ) { - - return false; - - } - - } - - return true; - - } - - containsPoint( point ) { - - const planes = this.planes; - - for ( let i = 0; i < 6; i ++ ) { - - if ( planes[ i ].distanceToPoint( point ) < 0 ) { - - return false; - - } - - } - - return true; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - - -export { Frustum }; diff --git a/GameDev/bin/Release/project_template/math/Interpolant.js b/GameDev/bin/Release/project_template/math/Interpolant.js deleted file mode 100644 index dcc550f5..00000000 --- a/GameDev/bin/Release/project_template/math/Interpolant.js +++ /dev/null @@ -1,246 +0,0 @@ -/** - * Abstract base class of interpolants over parametric samples. - * - * The parameter domain is one dimensional, typically the time or a path - * along a curve defined by the data. - * - * The sample values can have any dimensionality and derived classes may - * apply special interpretations to the data. - * - * This class provides the interval seek in a Template Method, deferring - * the actual interpolation to derived classes. - * - * Time complexity is O(1) for linear access crossing at most two points - * and O(log N) for random access, where N is the number of positions. - * - * References: - * - * http://www.oodesign.com/template-method-pattern.html - * - */ - -class Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; - - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; - - this.settings = null; - this.DefaultSettings_ = {}; - - } - - evaluate( t ) { - - const pp = this.parameterPositions; - let i1 = this._cachedIndex, - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; - - validate_interval: { - - seek: { - - let right; - - linear_scan: { - - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { - - for ( let giveUpAt = i1 + 2; ; ) { - - if ( t1 === undefined ) { - - if ( t < t0 ) break forward_scan; - - // after end - - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); - - } - - if ( i1 === giveUpAt ) break; // this loop - - t0 = t1; - t1 = pp[ ++ i1 ]; - - if ( t < t1 ) { - - // we have arrived at the sought interval - break seek; - - } - - } - - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; - - } - - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { - - // looping? - - const t1global = pp[ 1 ]; - - if ( t < t1global ) { - - i1 = 2; // + 1, using the scan for the details - t0 = t1global; - - } - - // linear reverse scan - - for ( let giveUpAt = i1 - 2; ; ) { - - if ( t0 === undefined ) { - - // before start - - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); - - } - - if ( i1 === giveUpAt ) break; // this loop - - t1 = t0; - t0 = pp[ -- i1 - 1 ]; - - if ( t >= t0 ) { - - // we have arrived at the sought interval - break seek; - - } - - } - - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; - - } - - // the interval is valid - - break validate_interval; - - } // linear scan - - // binary search - - while ( i1 < right ) { - - const mid = ( i1 + right ) >>> 1; - - if ( t < pp[ mid ] ) { - - right = mid; - - } else { - - i1 = mid + 1; - - } - - } - - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; - - // check boundary cases, again - - if ( t0 === undefined ) { - - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); - - } - - if ( t1 === undefined ) { - - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); - - } - - } // seek - - this._cachedIndex = i1; - - this.intervalChanged_( i1, t0, t1 ); - - } // validate_interval - - return this.interpolate_( i1, t0, t, t1 ); - - } - - getSettings_() { - - return this.settings || this.DefaultSettings_; - - } - - copySampleValue_( index ) { - - // copies a sample value to the result buffer - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; - - for ( let i = 0; i !== stride; ++ i ) { - - result[ i ] = values[ offset + i ]; - - } - - return result; - - } - - // Template methods for derived classes: - - interpolate_( /* i1, t0, t, t1 */ ) { - - throw new Error( 'call to abstract method' ); - // implementations shall return this.resultBuffer - - } - - intervalChanged_( /* i1, t0, t1 */ ) { - - // empty - - } - -} - -// ALIAS DEFINITIONS - -Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_; -Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_; - -export { Interpolant }; diff --git a/GameDev/bin/Release/project_template/math/Line3.js b/GameDev/bin/Release/project_template/math/Line3.js deleted file mode 100644 index bd41206e..00000000 --- a/GameDev/bin/Release/project_template/math/Line3.js +++ /dev/null @@ -1,115 +0,0 @@ -import { Vector3 } from './Vector3.js'; -import * as MathUtils from './MathUtils.js'; - -const _startP = /*@__PURE__*/ new Vector3(); -const _startEnd = /*@__PURE__*/ new Vector3(); - -class Line3 { - - constructor( start = new Vector3(), end = new Vector3() ) { - - this.start = start; - this.end = end; - - } - - set( start, end ) { - - this.start.copy( start ); - this.end.copy( end ); - - return this; - - } - - copy( line ) { - - this.start.copy( line.start ); - this.end.copy( line.end ); - - return this; - - } - - getCenter( target ) { - - return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - - } - - delta( target ) { - - return target.subVectors( this.end, this.start ); - - } - - distanceSq() { - - return this.start.distanceToSquared( this.end ); - - } - - distance() { - - return this.start.distanceTo( this.end ); - - } - - at( t, target ) { - - return this.delta( target ).multiplyScalar( t ).add( this.start ); - - } - - closestPointToPointParameter( point, clampToLine ) { - - _startP.subVectors( point, this.start ); - _startEnd.subVectors( this.end, this.start ); - - const startEnd2 = _startEnd.dot( _startEnd ); - const startEnd_startP = _startEnd.dot( _startP ); - - let t = startEnd_startP / startEnd2; - - if ( clampToLine ) { - - t = MathUtils.clamp( t, 0, 1 ); - - } - - return t; - - } - - closestPointToPoint( point, clampToLine, target ) { - - const t = this.closestPointToPointParameter( point, clampToLine ); - - return this.delta( target ).multiplyScalar( t ).add( this.start ); - - } - - applyMatrix4( matrix ) { - - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); - - return this; - - } - - equals( line ) { - - return line.start.equals( this.start ) && line.end.equals( this.end ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Line3 }; diff --git a/GameDev/bin/Release/project_template/math/MathUtils.js b/GameDev/bin/Release/project_template/math/MathUtils.js deleted file mode 100644 index 3de8f5ff..00000000 --- a/GameDev/bin/Release/project_template/math/MathUtils.js +++ /dev/null @@ -1,258 +0,0 @@ -const _lut = []; - -for ( let i = 0; i < 256; i ++ ) { - - _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); - -} - -let _seed = 1234567; - - -const DEG2RAD = Math.PI / 180; -const RAD2DEG = 180 / Math.PI; - -// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 -function generateUUID() { - - const d0 = Math.random() * 0xffffffff | 0; - const d1 = Math.random() * 0xffffffff | 0; - const d2 = Math.random() * 0xffffffff | 0; - const d3 = Math.random() * 0xffffffff | 0; - const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + - _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + - _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + - _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; - - // .toUpperCase() here flattens concatenated strings to save heap memory space. - return uuid.toUpperCase(); - -} - -function clamp( value, min, max ) { - - return Math.max( min, Math.min( max, value ) ); - -} - -// compute euclidian modulo of m % n -// https://en.wikipedia.org/wiki/Modulo_operation -function euclideanModulo( n, m ) { - - return ( ( n % m ) + m ) % m; - -} - -// Linear mapping from range to range -function mapLinear( x, a1, a2, b1, b2 ) { - - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - -} - -// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ -function inverseLerp( x, y, value ) { - - if ( x !== y ) { - - return ( value - x ) / ( y - x ); - - } else { - - return 0; - - } - -} - -// https://en.wikipedia.org/wiki/Linear_interpolation -function lerp( x, y, t ) { - - return ( 1 - t ) * x + t * y; - -} - -// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ -function damp( x, y, lambda, dt ) { - - return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); - -} - -// https://www.desmos.com/calculator/vcsjnyz7x4 -function pingpong( x, length = 1 ) { - - return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); - -} - -// http://en.wikipedia.org/wiki/Smoothstep -function smoothstep( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min ) / ( max - min ); - - return x * x * ( 3 - 2 * x ); - -} - -function smootherstep( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min ) / ( max - min ); - - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - -} - -// Random integer from interval -function randInt( low, high ) { - - return low + Math.floor( Math.random() * ( high - low + 1 ) ); - -} - -// Random float from interval -function randFloat( low, high ) { - - return low + Math.random() * ( high - low ); - -} - -// Random float from <-range/2, range/2> interval -function randFloatSpread( range ) { - - return range * ( 0.5 - Math.random() ); - -} - -// Deterministic pseudo-random float in the interval [ 0, 1 ] -function seededRandom( s ) { - - if ( s !== undefined ) _seed = s % 2147483647; - - // Park-Miller algorithm - - _seed = _seed * 16807 % 2147483647; - - return ( _seed - 1 ) / 2147483646; - -} - -function degToRad( degrees ) { - - return degrees * DEG2RAD; - -} - -function radToDeg( radians ) { - - return radians * RAD2DEG; - -} - -function isPowerOfTwo( value ) { - - return ( value & ( value - 1 ) ) === 0 && value !== 0; - -} - -function ceilPowerOfTwo( value ) { - - return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); - -} - -function floorPowerOfTwo( value ) { - - return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); - -} - -function setQuaternionFromProperEuler( q, a, b, c, order ) { - - // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles - - // rotations are applied to the axes in the order specified by 'order' - // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' - // angles are in radians - - const cos = Math.cos; - const sin = Math.sin; - - const c2 = cos( b / 2 ); - const s2 = sin( b / 2 ); - - const c13 = cos( ( a + c ) / 2 ); - const s13 = sin( ( a + c ) / 2 ); - - const c1_3 = cos( ( a - c ) / 2 ); - const s1_3 = sin( ( a - c ) / 2 ); - - const c3_1 = cos( ( c - a ) / 2 ); - const s3_1 = sin( ( c - a ) / 2 ); - - switch ( order ) { - - case 'XYX': - q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); - break; - - case 'YZY': - q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); - break; - - case 'ZXZ': - q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); - break; - - case 'XZX': - q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); - break; - - case 'YXY': - q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); - break; - - case 'ZYZ': - q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); - break; - - default: - console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); - - } - -} - - - - -export { - DEG2RAD, - RAD2DEG, - generateUUID, - clamp, - euclideanModulo, - mapLinear, - inverseLerp, - lerp, - damp, - pingpong, - smoothstep, - smootherstep, - randInt, - randFloat, - randFloatSpread, - seededRandom, - degToRad, - radToDeg, - isPowerOfTwo, - ceilPowerOfTwo, - floorPowerOfTwo, - setQuaternionFromProperEuler, -}; diff --git a/GameDev/bin/Release/project_template/math/Matrix3.js b/GameDev/bin/Release/project_template/math/Matrix3.js deleted file mode 100644 index 9005740e..00000000 --- a/GameDev/bin/Release/project_template/math/Matrix3.js +++ /dev/null @@ -1,339 +0,0 @@ -class Matrix3 { - - constructor() { - - this.elements = [ - - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - - ]; - - if ( arguments.length > 0 ) { - - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - - } - - } - - set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - - const te = this.elements; - - te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; - te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; - te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; - - return this; - - } - - identity() { - - this.set( - - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - - ); - - return this; - - } - - copy( m ) { - - const te = this.elements; - const me = m.elements; - - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; - te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; - te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; - - return this; - - } - - extractBasis( xAxis, yAxis, zAxis ) { - - xAxis.setFromMatrix3Column( this, 0 ); - yAxis.setFromMatrix3Column( this, 1 ); - zAxis.setFromMatrix3Column( this, 2 ); - - return this; - - } - - setFromMatrix4( m ) { - - const me = m.elements; - - this.set( - - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] - - ); - - return this; - - } - - multiply( m ) { - - return this.multiplyMatrices( this, m ); - - } - - premultiply( m ) { - - return this.multiplyMatrices( m, this ); - - } - - multiplyMatrices( a, b ) { - - const ae = a.elements; - const be = b.elements; - const te = this.elements; - - const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; - const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; - const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; - - const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; - const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; - const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; - - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; - te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; - te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; - - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; - te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; - te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; - - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; - te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; - te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; - - return this; - - } - - multiplyScalar( s ) { - - const te = this.elements; - - te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; - te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; - te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; - - return this; - - } - - determinant() { - - const te = this.elements; - - const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], - d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], - g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - - } - - invert() { - - const te = this.elements, - - n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], - n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ], - n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ], - - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, - - det = n11 * t11 + n21 * t12 + n31 * t13; - - if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - const detInv = 1 / det; - - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; - - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; - - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - - return this; - - } - - transpose() { - - let tmp; - const m = this.elements; - - tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; - tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; - tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; - - return this; - - } - - getNormalMatrix( matrix4 ) { - - return this.setFromMatrix4( matrix4 ).invert().transpose(); - - } - - transposeIntoArray( r ) { - - const m = this.elements; - - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; - - return this; - - } - - setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) { - - const c = Math.cos( rotation ); - const s = Math.sin( rotation ); - - this.set( - sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, - - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, - 0, 0, 1 - ); - - return this; - - } - - scale( sx, sy ) { - - const te = this.elements; - - te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx; - te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy; - - return this; - - } - - rotate( theta ) { - - const c = Math.cos( theta ); - const s = Math.sin( theta ); - - const te = this.elements; - - const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ]; - const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ]; - - te[ 0 ] = c * a11 + s * a21; - te[ 3 ] = c * a12 + s * a22; - te[ 6 ] = c * a13 + s * a23; - - te[ 1 ] = - s * a11 + c * a21; - te[ 4 ] = - s * a12 + c * a22; - te[ 7 ] = - s * a13 + c * a23; - - return this; - - } - - translate( tx, ty ) { - - const te = this.elements; - - te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ]; - te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ]; - - return this; - - } - - equals( matrix ) { - - const te = this.elements; - const me = matrix.elements; - - for ( let i = 0; i < 9; i ++ ) { - - if ( te[ i ] !== me[ i ] ) return false; - - } - - return true; - - } - - fromArray( array, offset = 0 ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.elements[ i ] = array[ i + offset ]; - - } - - return this; - - } - - toArray( array = [], offset = 0 ) { - - const te = this.elements; - - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; - - return array; - - } - - clone() { - - return new this.constructor().fromArray( this.elements ); - - } - -} - -Matrix3.prototype.isMatrix3 = true; - -export { Matrix3 }; diff --git a/GameDev/bin/Release/project_template/math/Matrix4.js b/GameDev/bin/Release/project_template/math/Matrix4.js deleted file mode 100644 index 5383e24c..00000000 --- a/GameDev/bin/Release/project_template/math/Matrix4.js +++ /dev/null @@ -1,885 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -class Matrix4 { - - constructor() { - - this.elements = [ - - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ]; - - if ( arguments.length > 0 ) { - - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - - } - - } - - set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - - const te = this.elements; - - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - - return this; - - } - - identity() { - - this.set( - - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - clone() { - - return new Matrix4().fromArray( this.elements ); - - } - - copy( m ) { - - const te = this.elements; - const me = m.elements; - - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; - te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; - te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; - te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; - - return this; - - } - - copyPosition( m ) { - - const te = this.elements, me = m.elements; - - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; - - return this; - - } - - setFromMatrix3( m ) { - - const me = m.elements; - - this.set( - - me[ 0 ], me[ 3 ], me[ 6 ], 0, - me[ 1 ], me[ 4 ], me[ 7 ], 0, - me[ 2 ], me[ 5 ], me[ 8 ], 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - extractBasis( xAxis, yAxis, zAxis ) { - - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); - - return this; - - } - - makeBasis( xAxis, yAxis, zAxis ) { - - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 - ); - - return this; - - } - - extractRotation( m ) { - - // this method does not support reflection matrices - - const te = this.elements; - const me = m.elements; - - const scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length(); - const scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length(); - const scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length(); - - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; - te[ 3 ] = 0; - - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; - te[ 7 ] = 0; - - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; - te[ 11 ] = 0; - - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; - - return this; - - } - - makeRotationFromEuler( euler ) { - - if ( ! ( euler && euler.isEuler ) ) { - - console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - - } - - const te = this.elements; - - const x = euler.x, y = euler.y, z = euler.z; - const a = Math.cos( x ), b = Math.sin( x ); - const c = Math.cos( y ), d = Math.sin( y ); - const e = Math.cos( z ), f = Math.sin( z ); - - if ( euler.order === 'XYZ' ) { - - const ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; - - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; - - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; - - } else if ( euler.order === 'YXZ' ) { - - const ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; - - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; - - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; - - } else if ( euler.order === 'ZXY' ) { - - const ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; - - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; - - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; - - } else if ( euler.order === 'ZYX' ) { - - const ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; - - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; - - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; - - } else if ( euler.order === 'YZX' ) { - - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; - - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; - - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; - - } else if ( euler.order === 'XZY' ) { - - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; - - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; - - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; - - } - - // bottom row - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; - - // last column - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; - - return this; - - } - - makeRotationFromQuaternion( q ) { - - return this.compose( _zero, q, _one ); - - } - - lookAt( eye, target, up ) { - - const te = this.elements; - - _z.subVectors( eye, target ); - - if ( _z.lengthSq() === 0 ) { - - // eye and target are in the same position - - _z.z = 1; - - } - - _z.normalize(); - _x.crossVectors( up, _z ); - - if ( _x.lengthSq() === 0 ) { - - // up and z are parallel - - if ( Math.abs( up.z ) === 1 ) { - - _z.x += 0.0001; - - } else { - - _z.z += 0.0001; - - } - - _z.normalize(); - _x.crossVectors( up, _z ); - - } - - _x.normalize(); - _y.crossVectors( _z, _x ); - - te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; - te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; - te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; - - return this; - - } - - multiply( m, n ) { - - if ( n !== undefined ) { - - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); - - } - - return this.multiplyMatrices( this, m ); - - } - - premultiply( m ) { - - return this.multiplyMatrices( m, this ); - - } - - multiplyMatrices( a, b ) { - - const ae = a.elements; - const be = b.elements; - const te = this.elements; - - const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - - const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - - return this; - - } - - multiplyScalar( s ) { - - const te = this.elements; - - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; - - return this; - - } - - determinant() { - - const te = this.elements; - - const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) - - ); - - } - - transpose() { - - const te = this.elements; - let tmp; - - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - - return this; - - } - - setPosition( x, y, z ) { - - const te = this.elements; - - if ( x.isVector3 ) { - - te[ 12 ] = x.x; - te[ 13 ] = x.y; - te[ 14 ] = x.z; - - } else { - - te[ 12 ] = x; - te[ 13 ] = y; - te[ 14 ] = z; - - } - - return this; - - } - - invert() { - - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - const te = this.elements, - - n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], - n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], - n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], - n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], - - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - - const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - - if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - const detInv = 1 / det; - - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; - - return this; - - } - - scale( v ) { - - const te = this.elements; - const x = v.x, y = v.y, z = v.z; - - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; - - return this; - - } - - getMaxScaleOnAxis() { - - const te = this.elements; - - const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; - - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - - } - - makeTranslation( x, y, z ) { - - this.set( - - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationX( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationY( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationZ( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationAxis( axis, angle ) { - - // Based on http://www.gamedev.net/reference/articles/article1199.asp - - const c = Math.cos( angle ); - const s = Math.sin( angle ); - const t = 1 - c; - const x = axis.x, y = axis.y, z = axis.z; - const tx = t * x, ty = t * y; - - this.set( - - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeScale( x, y, z ) { - - this.set( - - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeShear( xy, xz, yx, yz, zx, zy ) { - - this.set( - - 1, yx, zx, 0, - xy, 1, zy, 0, - xz, yz, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - compose( position, quaternion, scale ) { - - const te = this.elements; - - const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; - const x2 = x + x, y2 = y + y, z2 = z + z; - const xx = x * x2, xy = x * y2, xz = x * z2; - const yy = y * y2, yz = y * z2, zz = z * z2; - const wx = w * x2, wy = w * y2, wz = w * z2; - - const sx = scale.x, sy = scale.y, sz = scale.z; - - te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; - te[ 1 ] = ( xy + wz ) * sx; - te[ 2 ] = ( xz - wy ) * sx; - te[ 3 ] = 0; - - te[ 4 ] = ( xy - wz ) * sy; - te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; - te[ 6 ] = ( yz + wx ) * sy; - te[ 7 ] = 0; - - te[ 8 ] = ( xz + wy ) * sz; - te[ 9 ] = ( yz - wx ) * sz; - te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; - te[ 11 ] = 0; - - te[ 12 ] = position.x; - te[ 13 ] = position.y; - te[ 14 ] = position.z; - te[ 15 ] = 1; - - return this; - - } - - decompose( position, quaternion, scale ) { - - const te = this.elements; - - let sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - const sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - const sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - - // if determine is negative, we need to invert one scale - const det = this.determinant(); - if ( det < 0 ) sx = - sx; - - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; - - // scale the rotation part - _m1.copy( this ); - - const invSX = 1 / sx; - const invSY = 1 / sy; - const invSZ = 1 / sz; - - _m1.elements[ 0 ] *= invSX; - _m1.elements[ 1 ] *= invSX; - _m1.elements[ 2 ] *= invSX; - - _m1.elements[ 4 ] *= invSY; - _m1.elements[ 5 ] *= invSY; - _m1.elements[ 6 ] *= invSY; - - _m1.elements[ 8 ] *= invSZ; - _m1.elements[ 9 ] *= invSZ; - _m1.elements[ 10 ] *= invSZ; - - quaternion.setFromRotationMatrix( _m1 ); - - scale.x = sx; - scale.y = sy; - scale.z = sz; - - return this; - - } - - makePerspective( left, right, top, bottom, near, far ) { - - if ( far === undefined ) { - - console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); - - } - - const te = this.elements; - const x = 2 * near / ( right - left ); - const y = 2 * near / ( top - bottom ); - - const a = ( right + left ) / ( right - left ); - const b = ( top + bottom ) / ( top - bottom ); - const c = - ( far + near ) / ( far - near ); - const d = - 2 * far * near / ( far - near ); - - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - - return this; - - } - - makeOrthographic( left, right, top, bottom, near, far ) { - - const te = this.elements; - const w = 1.0 / ( right - left ); - const h = 1.0 / ( top - bottom ); - const p = 1.0 / ( far - near ); - - const x = ( right + left ) * w; - const y = ( top + bottom ) * h; - const z = ( far + near ) * p; - - te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; - - return this; - - } - - equals( matrix ) { - - const te = this.elements; - const me = matrix.elements; - - for ( let i = 0; i < 16; i ++ ) { - - if ( te[ i ] !== me[ i ] ) return false; - - } - - return true; - - } - - fromArray( array, offset = 0 ) { - - for ( let i = 0; i < 16; i ++ ) { - - this.elements[ i ] = array[ i + offset ]; - - } - - return this; - - } - - toArray( array = [], offset = 0 ) { - - const te = this.elements; - - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; - - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; - - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; - - return array; - - } - -} - -Matrix4.prototype.isMatrix4 = true; - -const _v1 = /*@__PURE__*/ new Vector3(); -const _m1 = /*@__PURE__*/ new Matrix4(); -const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); -const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); -const _x = /*@__PURE__*/ new Vector3(); -const _y = /*@__PURE__*/ new Vector3(); -const _z = /*@__PURE__*/ new Vector3(); - -export { Matrix4 }; diff --git a/GameDev/bin/Release/project_template/math/Plane.js b/GameDev/bin/Release/project_template/math/Plane.js deleted file mode 100644 index fc8a471b..00000000 --- a/GameDev/bin/Release/project_template/math/Plane.js +++ /dev/null @@ -1,205 +0,0 @@ -import { Matrix3 } from './Matrix3.js'; -import { Vector3 } from './Vector3.js'; - -const _vector1 = /*@__PURE__*/ new Vector3(); -const _vector2 = /*@__PURE__*/ new Vector3(); -const _normalMatrix = /*@__PURE__*/ new Matrix3(); - -class Plane { - - constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { - - // normal is assumed to be normalized - - this.normal = normal; - this.constant = constant; - - } - - set( normal, constant ) { - - this.normal.copy( normal ); - this.constant = constant; - - return this; - - } - - setComponents( x, y, z, w ) { - - this.normal.set( x, y, z ); - this.constant = w; - - return this; - - } - - setFromNormalAndCoplanarPoint( normal, point ) { - - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); - - return this; - - } - - setFromCoplanarPoints( a, b, c ) { - - const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); - - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - - this.setFromNormalAndCoplanarPoint( normal, a ); - - return this; - - } - - copy( plane ) { - - this.normal.copy( plane.normal ); - this.constant = plane.constant; - - return this; - - } - - normalize() { - - // Note: will lead to a divide by zero if the plane is invalid. - - const inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; - - return this; - - } - - negate() { - - this.constant *= - 1; - this.normal.negate(); - - return this; - - } - - distanceToPoint( point ) { - - return this.normal.dot( point ) + this.constant; - - } - - distanceToSphere( sphere ) { - - return this.distanceToPoint( sphere.center ) - sphere.radius; - - } - - projectPoint( point, target ) { - - return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); - - } - - intersectLine( line, target ) { - - const direction = line.delta( _vector1 ); - - const denominator = this.normal.dot( direction ); - - if ( denominator === 0 ) { - - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { - - return target.copy( line.start ); - - } - - // Unsure if this is the correct method to handle this case. - return null; - - } - - const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - - if ( t < 0 || t > 1 ) { - - return null; - - } - - return target.copy( direction ).multiplyScalar( t ).add( line.start ); - - } - - intersectsLine( line ) { - - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - - const startSign = this.distanceToPoint( line.start ); - const endSign = this.distanceToPoint( line.end ); - - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - - } - - intersectsBox( box ) { - - return box.intersectsPlane( this ); - - } - - intersectsSphere( sphere ) { - - return sphere.intersectsPlane( this ); - - } - - coplanarPoint( target ) { - - return target.copy( this.normal ).multiplyScalar( - this.constant ); - - } - - applyMatrix4( matrix, optionalNormalMatrix ) { - - const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); - - const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); - - const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - - this.constant = - referencePoint.dot( normal ); - - return this; - - } - - translate( offset ) { - - this.constant -= offset.dot( this.normal ); - - return this; - - } - - equals( plane ) { - - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -Plane.prototype.isPlane = true; - -export { Plane }; diff --git a/GameDev/bin/Release/project_template/math/Quaternion.js b/GameDev/bin/Release/project_template/math/Quaternion.js deleted file mode 100644 index 485fe865..00000000 --- a/GameDev/bin/Release/project_template/math/Quaternion.js +++ /dev/null @@ -1,689 +0,0 @@ -import * as MathUtils from './MathUtils.js'; - -class Quaternion { - - constructor( x = 0, y = 0, z = 0, w = 1 ) { - - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - } - - static slerp( qa, qb, qm, t ) { - - console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' ); - return qm.slerpQuaternions( qa, qb, t ); - - } - - static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - - // fuzz-free, array-based Quaternion SLERP operation - - let x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ]; - - const x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; - - if ( t === 0 ) { - - dst[ dstOffset + 0 ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - return; - - } - - if ( t === 1 ) { - - dst[ dstOffset + 0 ] = x1; - dst[ dstOffset + 1 ] = y1; - dst[ dstOffset + 2 ] = z1; - dst[ dstOffset + 3 ] = w1; - return; - - } - - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - - let s = 1 - t; - const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; - - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { - - const sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); - - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; - - } - - const tDir = t * dir; - - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; - - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { - - const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; - - } - - } - - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - - } - - static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { - - const x0 = src0[ srcOffset0 ]; - const y0 = src0[ srcOffset0 + 1 ]; - const z0 = src0[ srcOffset0 + 2 ]; - const w0 = src0[ srcOffset0 + 3 ]; - - const x1 = src1[ srcOffset1 ]; - const y1 = src1[ srcOffset1 + 1 ]; - const z1 = src1[ srcOffset1 + 2 ]; - const w1 = src1[ srcOffset1 + 3 ]; - - dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; - dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; - dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; - dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; - - return dst; - - } - - get x() { - - return this._x; - - } - - set x( value ) { - - this._x = value; - this._onChangeCallback(); - - } - - get y() { - - return this._y; - - } - - set y( value ) { - - this._y = value; - this._onChangeCallback(); - - } - - get z() { - - return this._z; - - } - - set z( value ) { - - this._z = value; - this._onChangeCallback(); - - } - - get w() { - - return this._w; - - } - - set w( value ) { - - this._w = value; - this._onChangeCallback(); - - } - - set( x, y, z, w ) { - - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - this._onChangeCallback(); - - return this; - - } - - clone() { - - return new this.constructor( this._x, this._y, this._z, this._w ); - - } - - copy( quaternion ) { - - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; - - this._onChangeCallback(); - - return this; - - } - - setFromEuler( euler, update ) { - - if ( ! ( euler && euler.isEuler ) ) { - - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - - } - - const x = euler._x, y = euler._y, z = euler._z, order = euler._order; - - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m - - const cos = Math.cos; - const sin = Math.sin; - - const c1 = cos( x / 2 ); - const c2 = cos( y / 2 ); - const c3 = cos( z / 2 ); - - const s1 = sin( x / 2 ); - const s2 = sin( y / 2 ); - const s3 = sin( z / 2 ); - - switch ( order ) { - - case 'XYZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'YXZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - case 'ZXY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'ZYX': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - case 'YZX': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'XZY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - default: - console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); - - } - - if ( update !== false ) this._onChangeCallback(); - - return this; - - } - - setFromAxisAngle( axis, angle ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - - // assumes axis is normalized - - const halfAngle = angle / 2, s = Math.sin( halfAngle ); - - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); - - this._onChangeCallback(); - - return this; - - } - - setFromRotationMatrix( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - const te = m.elements, - - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - - trace = m11 + m22 + m33; - - if ( trace > 0 ) { - - const s = 0.5 / Math.sqrt( trace + 1.0 ); - - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; - - } else if ( m11 > m22 && m11 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; - - } else if ( m22 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; - - } else { - - const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; - - } - - this._onChangeCallback(); - - return this; - - } - - setFromUnitVectors( vFrom, vTo ) { - - // assumes direction vectors vFrom and vTo are normalized - - let r = vFrom.dot( vTo ) + 1; - - if ( r < Number.EPSILON ) { - - // vFrom and vTo point in opposite directions - - r = 0; - - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - - this._x = - vFrom.y; - this._y = vFrom.x; - this._z = 0; - this._w = r; - - } else { - - this._x = 0; - this._y = - vFrom.z; - this._z = vFrom.y; - this._w = r; - - } - - } else { - - // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 - - this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; - this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; - this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; - this._w = r; - - } - - return this.normalize(); - - } - - angleTo( q ) { - - return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) ); - - } - - rotateTowards( q, step ) { - - const angle = this.angleTo( q ); - - if ( angle === 0 ) return this; - - const t = Math.min( 1, step / angle ); - - this.slerp( q, t ); - - return this; - - } - - identity() { - - return this.set( 0, 0, 0, 1 ); - - } - - invert() { - - // quaternion is assumed to have unit length - - return this.conjugate(); - - } - - conjugate() { - - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; - - this._onChangeCallback(); - - return this; - - } - - dot( v ) { - - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - - } - - lengthSq() { - - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - - } - - length() { - - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - - } - - normalize() { - - let l = this.length(); - - if ( l === 0 ) { - - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; - - } else { - - l = 1 / l; - - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; - - } - - this._onChangeCallback(); - - return this; - - } - - multiply( q, p ) { - - if ( p !== undefined ) { - - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); - - } - - return this.multiplyQuaternions( this, q ); - - } - - premultiply( q ) { - - return this.multiplyQuaternions( q, this ); - - } - - multiplyQuaternions( a, b ) { - - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - - const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - - this._onChangeCallback(); - - return this; - - } - - slerp( qb, t ) { - - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); - - const x = this._x, y = this._y, z = this._z, w = this._w; - - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - - let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - - if ( cosHalfTheta < 0 ) { - - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; - - cosHalfTheta = - cosHalfTheta; - - } else { - - this.copy( qb ); - - } - - if ( cosHalfTheta >= 1.0 ) { - - this._w = w; - this._x = x; - this._y = y; - this._z = z; - - return this; - - } - - const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; - - if ( sqrSinHalfTheta <= Number.EPSILON ) { - - const s = 1 - t; - this._w = s * w + t * this._w; - this._x = s * x + t * this._x; - this._y = s * y + t * this._y; - this._z = s * z + t * this._z; - - this.normalize(); - this._onChangeCallback(); - - return this; - - } - - const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); - const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); - - this._onChangeCallback(); - - return this; - - } - - slerpQuaternions( qa, qb, t ) { - - this.copy( qa ).slerp( qb, t ); - - } - - random() { - - // Derived from http://planning.cs.uiuc.edu/node198.html - // Note, this source uses w, x, y, z ordering, - // so we swap the order below. - - const u1 = Math.random(); - const sqrt1u1 = Math.sqrt( 1 - u1 ); - const sqrtu1 = Math.sqrt( u1 ); - - const u2 = 2 * Math.PI * Math.random(); - - const u3 = 2 * Math.PI * Math.random(); - - return this.set( - sqrt1u1 * Math.cos( u2 ), - sqrtu1 * Math.sin( u3 ), - sqrtu1 * Math.cos( u3 ), - sqrt1u1 * Math.sin( u2 ), - ); - - } - - equals( quaternion ) { - - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - - } - - fromArray( array, offset = 0 ) { - - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; - - this._onChangeCallback(); - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; - - return array; - - } - - fromBufferAttribute( attribute, index ) { - - this._x = attribute.getX( index ); - this._y = attribute.getY( index ); - this._z = attribute.getZ( index ); - this._w = attribute.getW( index ); - - return this; - - } - - _onChange( callback ) { - - this._onChangeCallback = callback; - - return this; - - } - - _onChangeCallback() {} - -} - -Quaternion.prototype.isQuaternion = true; - -export { Quaternion }; diff --git a/GameDev/bin/Release/project_template/math/Ray.js b/GameDev/bin/Release/project_template/math/Ray.js deleted file mode 100644 index 5798c7bf..00000000 --- a/GameDev/bin/Release/project_template/math/Ray.js +++ /dev/null @@ -1,496 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -const _vector = /*@__PURE__*/ new Vector3(); -const _segCenter = /*@__PURE__*/ new Vector3(); -const _segDir = /*@__PURE__*/ new Vector3(); -const _diff = /*@__PURE__*/ new Vector3(); - -const _edge1 = /*@__PURE__*/ new Vector3(); -const _edge2 = /*@__PURE__*/ new Vector3(); -const _normal = /*@__PURE__*/ new Vector3(); - -class Ray { - - constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { - - this.origin = origin; - this.direction = direction; - - } - - set( origin, direction ) { - - this.origin.copy( origin ); - this.direction.copy( direction ); - - return this; - - } - - copy( ray ) { - - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); - - return this; - - } - - at( t, target ) { - - return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - - } - - lookAt( v ) { - - this.direction.copy( v ).sub( this.origin ).normalize(); - - return this; - - } - - recast( t ) { - - this.origin.copy( this.at( t, _vector ) ); - - return this; - - } - - closestPointToPoint( point, target ) { - - target.subVectors( point, this.origin ); - - const directionDistance = target.dot( this.direction ); - - if ( directionDistance < 0 ) { - - return target.copy( this.origin ); - - } - - return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - - } - - distanceToPoint( point ) { - - return Math.sqrt( this.distanceSqToPoint( point ) ); - - } - - distanceSqToPoint( point ) { - - const directionDistance = _vector.subVectors( point, this.origin ).dot( this.direction ); - - // point behind the ray - - if ( directionDistance < 0 ) { - - return this.origin.distanceToSquared( point ); - - } - - _vector.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - - return _vector.distanceToSquared( point ); - - } - - distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment - - _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - _segDir.copy( v1 ).sub( v0 ).normalize(); - _diff.copy( this.origin ).sub( _segCenter ); - - const segExtent = v0.distanceTo( v1 ) * 0.5; - const a01 = - this.direction.dot( _segDir ); - const b0 = _diff.dot( this.direction ); - const b1 = - _diff.dot( _segDir ); - const c = _diff.lengthSq(); - const det = Math.abs( 1 - a01 * a01 ); - let s0, s1, sqrDist, extDet; - - if ( det > 0 ) { - - // The ray and segment are not parallel. - - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; - - if ( s0 >= 0 ) { - - if ( s1 >= - extDet ) { - - if ( s1 <= extDet ) { - - // region 0 - // Minimum at interior points of ray and segment. - - const invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - - } else { - - // region 1 - - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } else { - - // region 5 - - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } else { - - if ( s1 <= - extDet ) { - - // region 4 - - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } else if ( s1 <= extDet ) { - - // region 3 - - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; - - } else { - - // region 2 - - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } - - } else { - - // Ray and segment are parallel. - - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - if ( optionalPointOnRay ) { - - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - - } - - if ( optionalPointOnSegment ) { - - optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); - - } - - return sqrDist; - - } - - intersectSphere( sphere, target ) { - - _vector.subVectors( sphere.center, this.origin ); - const tca = _vector.dot( this.direction ); - const d2 = _vector.dot( _vector ) - tca * tca; - const radius2 = sphere.radius * sphere.radius; - - if ( d2 > radius2 ) return null; - - const thc = Math.sqrt( radius2 - d2 ); - - // t0 = first intersect point - entrance on front of sphere - const t0 = tca - thc; - - // t1 = second intersect point - exit point on back of sphere - const t1 = tca + thc; - - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; - - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if ( t0 < 0 ) return this.at( t1, target ); - - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, target ); - - } - - intersectsSphere( sphere ) { - - return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); - - } - - distanceToPlane( plane ) { - - const denominator = plane.normal.dot( this.direction ); - - if ( denominator === 0 ) { - - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { - - return 0; - - } - - // Null is preferable to undefined since undefined means.... it is undefined - - return null; - - } - - const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - - // Return if the ray never intersects the plane - - return t >= 0 ? t : null; - - } - - intersectPlane( plane, target ) { - - const t = this.distanceToPlane( plane ); - - if ( t === null ) { - - return null; - - } - - return this.at( t, target ); - - } - - intersectsPlane( plane ) { - - // check if the ray lies on the plane first - - const distToPoint = plane.distanceToPoint( this.origin ); - - if ( distToPoint === 0 ) { - - return true; - - } - - const denominator = plane.normal.dot( this.direction ); - - if ( denominator * distToPoint < 0 ) { - - return true; - - } - - // ray origin is behind the plane (and is pointing behind it) - - return false; - - } - - intersectBox( box, target ) { - - let tmin, tmax, tymin, tymax, tzmin, tzmax; - - const invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; - - const origin = this.origin; - - if ( invdirx >= 0 ) { - - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; - - } else { - - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; - - } - - if ( invdiry >= 0 ) { - - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; - - } else { - - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; - - } - - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN - - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - - if ( invdirz >= 0 ) { - - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; - - } else { - - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; - - } - - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - - //return point closest to the ray (positive side) - - if ( tmax < 0 ) return null; - - return this.at( tmin >= 0 ? tmin : tmax, target ); - - } - - intersectsBox( box ) { - - return this.intersectBox( box, _vector ) !== null; - - } - - intersectTriangle( a, b, c, backfaceCulling, target ) { - - // Compute the offset origin, edges, and normal. - - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - - _edge1.subVectors( b, a ); - _edge2.subVectors( c, a ); - _normal.crossVectors( _edge1, _edge2 ); - - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - let DdN = this.direction.dot( _normal ); - let sign; - - if ( DdN > 0 ) { - - if ( backfaceCulling ) return null; - sign = 1; - - } else if ( DdN < 0 ) { - - sign = - 1; - DdN = - DdN; - - } else { - - return null; - - } - - _diff.subVectors( this.origin, a ); - const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); - - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { - - return null; - - } - - const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); - - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { - - return null; - - } - - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { - - return null; - - } - - // Line intersects triangle, check if ray does. - const QdN = - sign * _diff.dot( _normal ); - - // t < 0, no intersection - if ( QdN < 0 ) { - - return null; - - } - - // Ray intersects triangle. - return this.at( QdN / DdN, target ); - - } - - applyMatrix4( matrix4 ) { - - this.origin.applyMatrix4( matrix4 ); - this.direction.transformDirection( matrix4 ); - - return this; - - } - - equals( ray ) { - - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Ray }; diff --git a/GameDev/bin/Release/project_template/math/Sphere.js b/GameDev/bin/Release/project_template/math/Sphere.js deleted file mode 100644 index 657335ba..00000000 --- a/GameDev/bin/Release/project_template/math/Sphere.js +++ /dev/null @@ -1,219 +0,0 @@ -import { Box3 } from './Box3.js'; -import { Vector3 } from './Vector3.js'; - -const _box = /*@__PURE__*/ new Box3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _toFarthestPoint = /*@__PURE__*/ new Vector3(); -const _toPoint = /*@__PURE__*/ new Vector3(); - -class Sphere { - - constructor( center = new Vector3(), radius = - 1 ) { - - this.center = center; - this.radius = radius; - - } - - set( center, radius ) { - - this.center.copy( center ); - this.radius = radius; - - return this; - - } - - setFromPoints( points, optionalCenter ) { - - const center = this.center; - - if ( optionalCenter !== undefined ) { - - center.copy( optionalCenter ); - - } else { - - _box.setFromPoints( points ).getCenter( center ); - - } - - let maxRadiusSq = 0; - - for ( let i = 0, il = points.length; i < il; i ++ ) { - - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - - } - - this.radius = Math.sqrt( maxRadiusSq ); - - return this; - - } - - copy( sphere ) { - - this.center.copy( sphere.center ); - this.radius = sphere.radius; - - return this; - - } - - isEmpty() { - - return ( this.radius < 0 ); - - } - - makeEmpty() { - - this.center.set( 0, 0, 0 ); - this.radius = - 1; - - return this; - - } - - containsPoint( point ) { - - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - - } - - distanceToPoint( point ) { - - return ( point.distanceTo( this.center ) - this.radius ); - - } - - intersectsSphere( sphere ) { - - const radiusSum = this.radius + sphere.radius; - - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - - } - - intersectsBox( box ) { - - return box.intersectsSphere( this ); - - } - - intersectsPlane( plane ) { - - return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; - - } - - clampPoint( point, target ) { - - const deltaLengthSq = this.center.distanceToSquared( point ); - - target.copy( point ); - - if ( deltaLengthSq > ( this.radius * this.radius ) ) { - - target.sub( this.center ).normalize(); - target.multiplyScalar( this.radius ).add( this.center ); - - } - - return target; - - } - - getBoundingBox( target ) { - - if ( this.isEmpty() ) { - - // Empty sphere produces empty bounding box - target.makeEmpty(); - return target; - - } - - target.set( this.center, this.center ); - target.expandByScalar( this.radius ); - - return target; - - } - - applyMatrix4( matrix ) { - - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); - - return this; - - } - - translate( offset ) { - - this.center.add( offset ); - - return this; - - } - - expandByPoint( point ) { - - // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671 - - _toPoint.subVectors( point, this.center ); - - const lengthSq = _toPoint.lengthSq(); - - if ( lengthSq > ( this.radius * this.radius ) ) { - - const length = Math.sqrt( lengthSq ); - const missingRadiusHalf = ( length - this.radius ) * 0.5; - - // Nudge this sphere towards the target point. Add half the missing distance to radius, - // and the other half to position. This gives a tighter enclosure, instead of if - // the whole missing distance were just added to radius. - - this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) ); - this.radius += missingRadiusHalf; - - } - - return this; - - } - - union( sphere ) { - - // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769 - - // To enclose another sphere into this sphere, we only need to enclose two points: - // 1) Enclose the farthest point on the other sphere into this sphere. - // 2) Enclose the opposite point of the farthest point into this sphere. - - _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius ); - - this.expandByPoint( _v1.copy( sphere.center ).add( _toFarthestPoint ) ); - this.expandByPoint( _v1.copy( sphere.center ).sub( _toFarthestPoint ) ); - - return this; - - } - - equals( sphere ) { - - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Sphere }; diff --git a/GameDev/bin/Release/project_template/math/Spherical.js b/GameDev/bin/Release/project_template/math/Spherical.js deleted file mode 100644 index 9b7bb6c6..00000000 --- a/GameDev/bin/Release/project_template/math/Spherical.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. - * The azimuthal angle (theta) is measured from the positive z-axis. - */ - -import * as MathUtils from './MathUtils.js'; - -class Spherical { - - constructor( radius = 1, phi = 0, theta = 0 ) { - - this.radius = radius; - this.phi = phi; // polar angle - this.theta = theta; // azimuthal angle - - return this; - - } - - set( radius, phi, theta ) { - - this.radius = radius; - this.phi = phi; - this.theta = theta; - - return this; - - } - - copy( other ) { - - this.radius = other.radius; - this.phi = other.phi; - this.theta = other.theta; - - return this; - - } - - // restrict phi to be betwee EPS and PI-EPS - makeSafe() { - - const EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - - return this; - - } - - setFromVector3( v ) { - - return this.setFromCartesianCoords( v.x, v.y, v.z ); - - } - - setFromCartesianCoords( x, y, z ) { - - this.radius = Math.sqrt( x * x + y * y + z * z ); - - if ( this.radius === 0 ) { - - this.theta = 0; - this.phi = 0; - - } else { - - this.theta = Math.atan2( x, z ); - this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) ); - - } - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Spherical }; diff --git a/GameDev/bin/Release/project_template/math/SphericalHarmonics3.js b/GameDev/bin/Release/project_template/math/SphericalHarmonics3.js deleted file mode 100644 index 2d8796fb..00000000 --- a/GameDev/bin/Release/project_template/math/SphericalHarmonics3.js +++ /dev/null @@ -1,243 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -/** - * Primary reference: - * https://graphics.stanford.edu/papers/envmap/envmap.pdf - * - * Secondary reference: - * https://www.ppsloan.org/publications/StupidSH36.pdf - */ - -// 3-band SH defined by 9 coefficients - -class SphericalHarmonics3 { - - constructor() { - - this.coefficients = []; - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients.push( new Vector3() ); - - } - - } - - set( coefficients ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].copy( coefficients[ i ] ); - - } - - return this; - - } - - zero() { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].set( 0, 0, 0 ); - - } - - return this; - - } - - // get the radiance in the direction of the normal - // target is a Vector3 - getAt( normal, target ) { - - // normal is assumed to be unit length - - const x = normal.x, y = normal.y, z = normal.z; - - const coeff = this.coefficients; - - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); - - // band 1 - target.addScaledVector( coeff[ 1 ], 0.488603 * y ); - target.addScaledVector( coeff[ 2 ], 0.488603 * z ); - target.addScaledVector( coeff[ 3 ], 0.488603 * x ); - - // band 2 - target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); - target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); - target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); - target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); - target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); - - return target; - - } - - // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal - // target is a Vector3 - // https://graphics.stanford.edu/papers/envmap/envmap.pdf - getIrradianceAt( normal, target ) { - - // normal is assumed to be unit length - - const x = normal.x, y = normal.y, z = normal.z; - - const coeff = this.coefficients; - - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 - - // band 1 - target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 - target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); - target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); - - // band 2 - target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 - target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); - target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 - target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); - target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 - - return target; - - } - - add( sh ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].add( sh.coefficients[ i ] ); - - } - - return this; - - } - - addScaledSH( sh, s ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); - - } - - return this; - - } - - scale( s ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].multiplyScalar( s ); - - } - - return this; - - } - - lerp( sh, alpha ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); - - } - - return this; - - } - - equals( sh ) { - - for ( let i = 0; i < 9; i ++ ) { - - if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { - - return false; - - } - - } - - return true; - - } - - copy( sh ) { - - return this.set( sh.coefficients ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - fromArray( array, offset = 0 ) { - - const coefficients = this.coefficients; - - for ( let i = 0; i < 9; i ++ ) { - - coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); - - } - - return this; - - } - - toArray( array = [], offset = 0 ) { - - const coefficients = this.coefficients; - - for ( let i = 0; i < 9; i ++ ) { - - coefficients[ i ].toArray( array, offset + ( i * 3 ) ); - - } - - return array; - - } - - // evaluate the basis functions - // shBasis is an Array[ 9 ] - static getBasisAt( normal, shBasis ) { - - // normal is assumed to be unit length - - const x = normal.x, y = normal.y, z = normal.z; - - // band 0 - shBasis[ 0 ] = 0.282095; - - // band 1 - shBasis[ 1 ] = 0.488603 * y; - shBasis[ 2 ] = 0.488603 * z; - shBasis[ 3 ] = 0.488603 * x; - - // band 2 - shBasis[ 4 ] = 1.092548 * x * y; - shBasis[ 5 ] = 1.092548 * y * z; - shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); - shBasis[ 7 ] = 1.092548 * x * z; - shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); - - } - -} - -SphericalHarmonics3.prototype.isSphericalHarmonics3 = true; - -export { SphericalHarmonics3 }; diff --git a/GameDev/bin/Release/project_template/math/Triangle.js b/GameDev/bin/Release/project_template/math/Triangle.js deleted file mode 100644 index 617ca629..00000000 --- a/GameDev/bin/Release/project_template/math/Triangle.js +++ /dev/null @@ -1,299 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -const _v0 = /*@__PURE__*/ new Vector3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _v2 = /*@__PURE__*/ new Vector3(); -const _v3 = /*@__PURE__*/ new Vector3(); - -const _vab = /*@__PURE__*/ new Vector3(); -const _vac = /*@__PURE__*/ new Vector3(); -const _vbc = /*@__PURE__*/ new Vector3(); -const _vap = /*@__PURE__*/ new Vector3(); -const _vbp = /*@__PURE__*/ new Vector3(); -const _vcp = /*@__PURE__*/ new Vector3(); - -class Triangle { - - constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { - - this.a = a; - this.b = b; - this.c = c; - - } - - static getNormal( a, b, c, target ) { - - target.subVectors( c, b ); - _v0.subVectors( a, b ); - target.cross( _v0 ); - - const targetLengthSq = target.lengthSq(); - if ( targetLengthSq > 0 ) { - - return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); - - } - - return target.set( 0, 0, 0 ); - - } - - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - static getBarycoord( point, a, b, c, target ) { - - _v0.subVectors( c, a ); - _v1.subVectors( b, a ); - _v2.subVectors( point, a ); - - const dot00 = _v0.dot( _v0 ); - const dot01 = _v0.dot( _v1 ); - const dot02 = _v0.dot( _v2 ); - const dot11 = _v1.dot( _v1 ); - const dot12 = _v1.dot( _v2 ); - - const denom = ( dot00 * dot11 - dot01 * dot01 ); - - // collinear or singular triangle - if ( denom === 0 ) { - - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return target.set( - 2, - 1, - 1 ); - - } - - const invDenom = 1 / denom; - const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - - // barycentric coordinates must always sum to 1 - return target.set( 1 - u - v, v, u ); - - } - - static containsPoint( point, a, b, c ) { - - this.getBarycoord( point, a, b, c, _v3 ); - - return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); - - } - - static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { - - this.getBarycoord( point, p1, p2, p3, _v3 ); - - target.set( 0, 0 ); - target.addScaledVector( uv1, _v3.x ); - target.addScaledVector( uv2, _v3.y ); - target.addScaledVector( uv3, _v3.z ); - - return target; - - } - - static isFrontFacing( a, b, c, direction ) { - - _v0.subVectors( c, b ); - _v1.subVectors( a, b ); - - // strictly front facing - return ( _v0.cross( _v1 ).dot( direction ) < 0 ) ? true : false; - - } - - set( a, b, c ) { - - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); - - return this; - - } - - setFromPointsAndIndices( points, i0, i1, i2 ) { - - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); - - return this; - - } - - setFromAttributeAndIndices( attribute, i0, i1, i2 ) { - - this.a.fromBufferAttribute( attribute, i0 ); - this.b.fromBufferAttribute( attribute, i1 ); - this.c.fromBufferAttribute( attribute, i2 ); - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - copy( triangle ) { - - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); - - return this; - - } - - getArea() { - - _v0.subVectors( this.c, this.b ); - _v1.subVectors( this.a, this.b ); - - return _v0.cross( _v1 ).length() * 0.5; - - } - - getMidpoint( target ) { - - return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - - } - - getNormal( target ) { - - return Triangle.getNormal( this.a, this.b, this.c, target ); - - } - - getPlane( target ) { - - return target.setFromCoplanarPoints( this.a, this.b, this.c ); - - } - - getBarycoord( point, target ) { - - return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); - - } - - getUV( point, uv1, uv2, uv3, target ) { - - return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); - - } - - containsPoint( point ) { - - return Triangle.containsPoint( point, this.a, this.b, this.c ); - - } - - isFrontFacing( direction ) { - - return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); - - } - - intersectsBox( box ) { - - return box.intersectsTriangle( this ); - - } - - closestPointToPoint( p, target ) { - - const a = this.a, b = this.b, c = this.c; - let v, w; - - // algorithm thanks to Real-Time Collision Detection by Christer Ericson, - // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., - // under the accompanying license; see chapter 5.1.5 for detailed explanation. - // basically, we're distinguishing which of the voronoi regions of the triangle - // the point lies in with the minimum amount of redundant computation. - - _vab.subVectors( b, a ); - _vac.subVectors( c, a ); - _vap.subVectors( p, a ); - const d1 = _vab.dot( _vap ); - const d2 = _vac.dot( _vap ); - if ( d1 <= 0 && d2 <= 0 ) { - - // vertex region of A; barycentric coords (1, 0, 0) - return target.copy( a ); - - } - - _vbp.subVectors( p, b ); - const d3 = _vab.dot( _vbp ); - const d4 = _vac.dot( _vbp ); - if ( d3 >= 0 && d4 <= d3 ) { - - // vertex region of B; barycentric coords (0, 1, 0) - return target.copy( b ); - - } - - const vc = d1 * d4 - d3 * d2; - if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { - - v = d1 / ( d1 - d3 ); - // edge region of AB; barycentric coords (1-v, v, 0) - return target.copy( a ).addScaledVector( _vab, v ); - - } - - _vcp.subVectors( p, c ); - const d5 = _vab.dot( _vcp ); - const d6 = _vac.dot( _vcp ); - if ( d6 >= 0 && d5 <= d6 ) { - - // vertex region of C; barycentric coords (0, 0, 1) - return target.copy( c ); - - } - - const vb = d5 * d2 - d1 * d6; - if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { - - w = d2 / ( d2 - d6 ); - // edge region of AC; barycentric coords (1-w, 0, w) - return target.copy( a ).addScaledVector( _vac, w ); - - } - - const va = d3 * d6 - d5 * d4; - if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { - - _vbc.subVectors( c, b ); - w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); - // edge region of BC; barycentric coords (0, 1-w, w) - return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC - - } - - // face region - const denom = 1 / ( va + vb + vc ); - // u = va * denom - v = vb * denom; - w = vc * denom; - - return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); - - } - - equals( triangle ) { - - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - - } - -} - -export { Triangle }; diff --git a/GameDev/bin/Release/project_template/math/Vector2.js b/GameDev/bin/Release/project_template/math/Vector2.js deleted file mode 100644 index 88592aa3..00000000 --- a/GameDev/bin/Release/project_template/math/Vector2.js +++ /dev/null @@ -1,484 +0,0 @@ -class Vector2 { - - constructor( x = 0, y = 0 ) { - - this.x = x; - this.y = y; - - } - - get width() { - - return this.x; - - } - - set width( value ) { - - this.x = value; - - } - - get height() { - - return this.y; - - } - - set height( value ) { - - this.y = value; - - } - - set( x, y ) { - - this.x = x; - this.y = y; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - - return this; - - } - - multiply( v ) { - - this.x *= v.x; - this.y *= v.y; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - - return this; - - } - - divide( v ) { - - this.x /= v.x; - this.y /= v.y; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - applyMatrix3( m ) { - - const x = this.x, y = this.y; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; - - return this; - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y; - - } - - cross( v ) { - - return this.x * v.y - this.y * v.x; - - } - - lengthSq() { - - return this.x * this.x + this.y * this.y; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - angle() { - - // computes the angle in radians with respect to the positive x-axis - - const angle = Math.atan2( - this.y, - this.x ) + Math.PI; - - return angle; - - } - - distanceTo( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - } - - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; - - } - - manhattanDistanceTo( v ) { - - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - - return this; - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - - return this; - - } - - rotateAround( center, angle ) { - - const c = Math.cos( angle ), s = Math.sin( angle ); - - const x = this.x - center.x; - const y = this.y - center.y; - - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - - } - -} - -Vector2.prototype.isVector2 = true; - -export { Vector2 }; diff --git a/GameDev/bin/Release/project_template/math/Vector3.js b/GameDev/bin/Release/project_template/math/Vector3.js deleted file mode 100644 index d3303860..00000000 --- a/GameDev/bin/Release/project_template/math/Vector3.js +++ /dev/null @@ -1,745 +0,0 @@ -import * as MathUtils from './MathUtils.js'; -import { Quaternion } from './Quaternion.js'; - -class Vector3 { - - constructor( x = 0, y = 0, z = 0 ) { - - this.x = x; - this.y = y; - this.z = z; - - } - - set( x, y, z ) { - - if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) - - this.x = x; - this.y = y; - this.z = z; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - this.z = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setZ( z ) { - - this.z = z; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y, this.z ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - this.z += v.z; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - this.z += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - this.z -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - - return this; - - } - - multiply( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); - - } - - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - - return this; - - } - - multiplyVectors( a, b ) { - - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; - - return this; - - } - - applyEuler( euler ) { - - if ( ! ( euler && euler.isEuler ) ) { - - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - - } - - return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); - - } - - applyAxisAngle( axis, angle ) { - - return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); - - } - - applyMatrix3( m ) { - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; - this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; - - return this; - - } - - applyNormalMatrix( m ) { - - return this.applyMatrix3( m ).normalize(); - - } - - applyMatrix4( m ) { - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); - - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; - this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; - - return this; - - } - - applyQuaternion( q ) { - - const x = this.x, y = this.y, z = this.z; - const qx = q.x, qy = q.y, qz = q.z, qw = q.w; - - // calculate quat * vector - - const ix = qw * x + qy * z - qz * y; - const iy = qw * y + qz * x - qx * z; - const iz = qw * z + qx * y - qy * x; - const iw = - qx * x - qy * y - qz * z; - - // calculate result * inverse quat - - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; - - return this; - - } - - project( camera ) { - - return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); - - } - - unproject( camera ) { - - return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); - - } - - transformDirection( m ) { - - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; - - return this.normalize(); - - } - - divide( v ) { - - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z; - - } - - // TODO lengthSquared? - - lengthSq() { - - return this.x * this.x + this.y * this.y + this.z * this.z; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; - - return this; - - } - - cross( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); - - } - - return this.crossVectors( this, v ); - - } - - crossVectors( a, b ) { - - const ax = a.x, ay = a.y, az = a.z; - const bx = b.x, by = b.y, bz = b.z; - - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - - return this; - - } - - projectOnVector( v ) { - - const denominator = v.lengthSq(); - - if ( denominator === 0 ) return this.set( 0, 0, 0 ); - - const scalar = v.dot( this ) / denominator; - - return this.copy( v ).multiplyScalar( scalar ); - - } - - projectOnPlane( planeNormal ) { - - _vector.copy( this ).projectOnVector( planeNormal ); - - return this.sub( _vector ); - - } - - reflect( normal ) { - - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length - - return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - - } - - angleTo( v ) { - - const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); - - if ( denominator === 0 ) return Math.PI / 2; - - const theta = this.dot( v ) / denominator; - - // clamp, to handle numerical problems - - return Math.acos( MathUtils.clamp( theta, - 1, 1 ) ); - - } - - distanceTo( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - } - - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - - return dx * dx + dy * dy + dz * dz; - - } - - manhattanDistanceTo( v ) { - - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - - } - - setFromSpherical( s ) { - - return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); - - } - - setFromSphericalCoords( radius, phi, theta ) { - - const sinPhiRadius = Math.sin( phi ) * radius; - - this.x = sinPhiRadius * Math.sin( theta ); - this.y = Math.cos( phi ) * radius; - this.z = sinPhiRadius * Math.cos( theta ); - - return this; - - } - - setFromCylindrical( c ) { - - return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); - - } - - setFromCylindricalCoords( radius, theta, y ) { - - this.x = radius * Math.sin( theta ); - this.y = y; - this.z = radius * Math.cos( theta ); - - return this; - - } - - setFromMatrixPosition( m ) { - - const e = m.elements; - - this.x = e[ 12 ]; - this.y = e[ 13 ]; - this.z = e[ 14 ]; - - return this; - - } - - setFromMatrixScale( m ) { - - const sx = this.setFromMatrixColumn( m, 0 ).length(); - const sy = this.setFromMatrixColumn( m, 1 ).length(); - const sz = this.setFromMatrixColumn( m, 2 ).length(); - - this.x = sx; - this.y = sy; - this.z = sz; - - return this; - - } - - setFromMatrixColumn( m, index ) { - - return this.fromArray( m.elements, index * 4 ); - - } - - setFromMatrix3Column( m, index ) { - - return this.fromArray( m.elements, index * 3 ); - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - - return this; - - } - - randomDirection() { - - // Derived from https://mathworld.wolfram.com/SpherePointPicking.html - - const u = ( Math.random() - 0.5 ) * 2; - const t = Math.random() * Math.PI * 2; - const f = Math.sqrt( 1 - u ** 2 ); - - this.x = f * Math.cos( t ); - this.y = f * Math.sin( t ); - this.z = u; - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - yield this.z; - - } - -} - -Vector3.prototype.isVector3 = true; - -const _vector = /*@__PURE__*/ new Vector3(); -const _quaternion = /*@__PURE__*/ new Quaternion(); - -export { Vector3 }; diff --git a/GameDev/bin/Release/project_template/math/Vector4.js b/GameDev/bin/Release/project_template/math/Vector4.js deleted file mode 100644 index c9af047a..00000000 --- a/GameDev/bin/Release/project_template/math/Vector4.js +++ /dev/null @@ -1,664 +0,0 @@ -class Vector4 { - - constructor( x = 0, y = 0, z = 0, w = 1 ) { - - this.x = x; - this.y = y; - this.z = z; - this.w = w; - - } - - get width() { - - return this.z; - - } - - set width( value ) { - - this.z = value; - - } - - get height() { - - return this.w; - - } - - set height( value ) { - - this.w = value; - - } - - set( x, y, z, w ) { - - this.x = x; - this.y = y; - this.z = z; - this.w = w; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setZ( z ) { - - this.z = z; - - return this; - - } - - setW( w ) { - - this.w = w; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y, this.z, this.w ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - this.z += s; - this.w += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; - - return this; - - } - - multiply( v ) { - - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - this.w *= v.w; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; - - return this; - - } - - applyMatrix4( m ) { - - const x = this.x, y = this.y, z = this.z, w = this.w; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; - this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - setAxisAngleFromQuaternion( q ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - - // q is assumed to be normalized - - this.w = 2 * Math.acos( q.w ); - - const s = Math.sqrt( 1 - q.w * q.w ); - - if ( s < 0.0001 ) { - - this.x = 1; - this.y = 0; - this.z = 0; - - } else { - - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; - - } - - return this; - - } - - setAxisAngleFromRotationMatrix( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - let angle, x, y, z; // variables for result - const epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - - te = m.elements, - - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { - - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms - - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - - // this singularity is identity matrix so angle = 0 - - this.set( 1, 0, 0, 0 ); - - return this; // zero angle, arbitrary axis - - } - - // otherwise this singularity is angle = 180 - - angle = Math.PI; - - const xx = ( m11 + 1 ) / 2; - const yy = ( m22 + 1 ) / 2; - const zz = ( m33 + 1 ) / 2; - const xy = ( m12 + m21 ) / 4; - const xz = ( m13 + m31 ) / 4; - const yz = ( m23 + m32 ) / 4; - - if ( ( xx > yy ) && ( xx > zz ) ) { - - // m11 is the largest diagonal term - - if ( xx < epsilon ) { - - x = 0; - y = 0.707106781; - z = 0.707106781; - - } else { - - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; - - } - - } else if ( yy > zz ) { - - // m22 is the largest diagonal term - - if ( yy < epsilon ) { - - x = 0.707106781; - y = 0; - z = 0.707106781; - - } else { - - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; - - } - - } else { - - // m33 is the largest diagonal term so base result on this - - if ( zz < epsilon ) { - - x = 0.707106781; - y = 0.707106781; - z = 0; - - } else { - - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; - - } - - } - - this.set( x, y, z, angle ); - - return this; // return 180 deg rotation - - } - - // as we have reached here there are no singularities so we can handle normally - - let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + - ( m13 - m31 ) * ( m13 - m31 ) + - ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - - if ( Math.abs( s ) < 0.001 ) s = 1; - - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case - - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - - return this; - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - this.w = Math.min( this.w, v.w ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - this.w = Math.max( this.w, v.w ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - - } - - lengthSq() { - - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; - this.w = v1.w + ( v2.w - v1.w ) * alpha; - - return this; - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - this.w = attribute.getW( index ); - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - this.w = Math.random(); - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - yield this.z; - yield this.w; - - } - -} - -Vector4.prototype.isVector4 = true; - -export { Vector4 }; diff --git a/GameDev/bin/Release/project_template/math/interpolants/CubicInterpolant.js b/GameDev/bin/Release/project_template/math/interpolants/CubicInterpolant.js deleted file mode 100644 index 3484dbfa..00000000 --- a/GameDev/bin/Release/project_template/math/interpolants/CubicInterpolant.js +++ /dev/null @@ -1,151 +0,0 @@ -import { ZeroCurvatureEnding } from '../../constants.js'; -import { Interpolant } from '../Interpolant.js'; -import { WrapAroundEnding, ZeroSlopeEnding } from '../../constants.js'; - -/** - * Fast and simple cubic spline interpolant. - * - * It was derived from a Hermitian construction setting the first derivative - * at each sample position to the linear slope between neighboring positions - * over their parameter interval. - */ - -class CubicInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - this._weightPrev = - 0; - this._offsetPrev = - 0; - this._weightNext = - 0; - this._offsetNext = - 0; - - this.DefaultSettings_ = { - - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding - - }; - - } - - intervalChanged_( i1, t0, t1 ) { - - const pp = this.parameterPositions; - let iPrev = i1 - 2, - iNext = i1 + 1, - - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; - - if ( tPrev === undefined ) { - - switch ( this.getSettings_().endingStart ) { - - case ZeroSlopeEnding: - - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; - - break; - - case WrapAroundEnding: - - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - - break; - - default: // ZeroCurvatureEnding - - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; - - } - - } - - if ( tNext === undefined ) { - - switch ( this.getSettings_().endingEnd ) { - - case ZeroSlopeEnding: - - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; - - break; - - case WrapAroundEnding: - - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; - - break; - - default: // ZeroCurvatureEnding - - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; - - } - - } - - const halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; - - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; - - } - - interpolate_( i1, t0, t, t1 ) { - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, - - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; - - // evaluate polynomials - - const sP = - wP * ppp + 2 * wP * pp - wP * p; - const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; - const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - const sN = wN * ppp - wN * pp; - - // combine data linearly - - for ( let i = 0; i !== stride; ++ i ) { - - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; - - } - - return result; - - } - -} - -export { CubicInterpolant }; diff --git a/GameDev/bin/Release/project_template/math/interpolants/DiscreteInterpolant.js b/GameDev/bin/Release/project_template/math/interpolants/DiscreteInterpolant.js deleted file mode 100644 index 38ff2702..00000000 --- a/GameDev/bin/Release/project_template/math/interpolants/DiscreteInterpolant.js +++ /dev/null @@ -1,26 +0,0 @@ -import { Interpolant } from '../Interpolant.js'; - -/** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - */ - -class DiscreteInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - } - - interpolate_( i1 /*, t0, t, t1 */ ) { - - return this.copySampleValue_( i1 - 1 ); - - } - -} - - -export { DiscreteInterpolant }; diff --git a/GameDev/bin/Release/project_template/math/interpolants/LinearInterpolant.js b/GameDev/bin/Release/project_template/math/interpolants/LinearInterpolant.js deleted file mode 100644 index dae736e2..00000000 --- a/GameDev/bin/Release/project_template/math/interpolants/LinearInterpolant.js +++ /dev/null @@ -1,38 +0,0 @@ -import { Interpolant } from '../Interpolant.js'; - -class LinearInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - } - - interpolate_( i1, t0, t, t1 ) { - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - - offset1 = i1 * stride, - offset0 = offset1 - stride, - - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; - - for ( let i = 0; i !== stride; ++ i ) { - - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; - - } - - return result; - - } - -} - - -export { LinearInterpolant }; diff --git a/GameDev/bin/Release/project_template/math/interpolants/QuaternionLinearInterpolant.js b/GameDev/bin/Release/project_template/math/interpolants/QuaternionLinearInterpolant.js deleted file mode 100644 index 3b8bd4f2..00000000 --- a/GameDev/bin/Release/project_template/math/interpolants/QuaternionLinearInterpolant.js +++ /dev/null @@ -1,39 +0,0 @@ -import { Interpolant } from '../Interpolant.js'; -import { Quaternion } from '../Quaternion.js'; - -/** - * Spherical linear unit quaternion interpolant. - */ - -class QuaternionLinearInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - } - - interpolate_( i1, t0, t, t1 ) { - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - - alpha = ( t - t0 ) / ( t1 - t0 ); - - let offset = i1 * stride; - - for ( let end = offset + stride; offset !== end; offset += 4 ) { - - Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); - - } - - return result; - - } - -} - - -export { QuaternionLinearInterpolant }; diff --git a/GameDev/bin/Release/project_template/project.json b/GameDev/bin/Release/project_template/project.json deleted file mode 100644 index 06493ab8..00000000 --- a/GameDev/bin/Release/project_template/project.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "project_name": "xml_based", - "targets": [ - { - "name": "target", - "input": "index.js", - "output": "bundle_index.js", - "dirty": true - } - ] -} \ No newline at end of file diff --git a/GameDev/bin/Release/project_template/scene.js b/GameDev/bin/Release/project_template/scene.js deleted file mode 100644 index b6af3ec7..00000000 --- a/GameDev/bin/Release/project_template/scene.js +++ /dev/null @@ -1,5 +0,0 @@ -export async function load(doc) -{ - doc.load_local_xml("scene.xml"); -} - diff --git a/GameDev/bin/Release/project_template/scene.xml b/GameDev/bin/Release/project_template/scene.xml deleted file mode 100644 index 476de974..00000000 --- a/GameDev/bin/Release/project_template/scene.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/GameDev/bin/Release/project_template/txml.js b/GameDev/bin/Release/project_template/txml.js deleted file mode 100644 index e1a81018..00000000 --- a/GameDev/bin/Release/project_template/txml.js +++ /dev/null @@ -1,482 +0,0 @@ -'use strict'; - -// ==ClosureCompiler== -// @output_file_name default.js -// @compilation_level SIMPLE_OPTIMIZATIONS -// ==/ClosureCompiler== -// module.exports = { -// parse: parse, -// simplify: simplify, -// simplifyLostLess: simplifyLostLess, -// filter: filter, -// stringify: stringify, -// toContentString: toContentString, -// getElementById: getElementById, -// getElementsByClassName: getElementsByClassName, -// transformStream: transformStream, -// }; - -/** - * @author: Tobias Nickel - * @created: 06.04.2015 - * I needed a small xmlparser chat can be used in a worker. - */ - -/** - * @typedef tNode - * @property {string} tagName - * @property {object} attributes - * @property {(tNode|string)[]} children - **/ - -/** - * @typedef TParseOptions - * @property {number} [pos] - * @property {string[]} [noChildNodes] - * @property {boolean} [setPos] - * @property {boolean} [keepComments] - * @property {boolean} [keepWhitespace] - * @property {boolean} [simplify] - * @property {(a: tNode, b: tNode) => boolean} [filter] - */ - -/** - * parseXML / html into a DOM Object. with no validation and some failur tolerance - * @param {string} S your XML to parse - * @param {TParseOptions} [options] all other options: - * @return {(tNode | string)[]} - */ -function parse(S, options) { - "txml"; - options = options || {}; - - var pos = options.pos || 0; - var keepComments = !!options.keepComments; - var keepWhitespace = !!options.keepWhitespace; - - var openBracket = "<"; - var openBracketCC = "<".charCodeAt(0); - var closeBracket = ">"; - var closeBracketCC = ">".charCodeAt(0); - var minusCC = "-".charCodeAt(0); - var slashCC = "/".charCodeAt(0); - var exclamationCC = '!'.charCodeAt(0); - var singleQuoteCC = "'".charCodeAt(0); - var doubleQuoteCC = '"'.charCodeAt(0); - var openCornerBracketCC = '['.charCodeAt(0); - var closeCornerBracketCC = ']'.charCodeAt(0); - - - /** - * parsing a list of entries - */ - function parseChildren(tagName) { - var children = []; - while (S[pos]) { - if (S.charCodeAt(pos) == openBracketCC) { - if (S.charCodeAt(pos + 1) === slashCC) { - var closeStart = pos + 2; - pos = S.indexOf(closeBracket, pos); - - var closeTag = S.substring(closeStart, pos); - if (closeTag.indexOf(tagName) == -1) { - var parsedText = S.substring(0, pos).split('\n'); - throw new Error( - 'Unexpected close tag\nLine: ' + (parsedText.length - 1) + - '\nColumn: ' + (parsedText[parsedText.length - 1].length + 1) + - '\nChar: ' + S[pos] - ); - } - - if (pos + 1) pos += 1; - - return children; - } else if (S.charCodeAt(pos + 1) === exclamationCC) { - if (S.charCodeAt(pos + 2) == minusCC) { - //comment support - const startCommentPos = pos; - while (pos !== -1 && !(S.charCodeAt(pos) === closeBracketCC && S.charCodeAt(pos - 1) == minusCC && S.charCodeAt(pos - 2) == minusCC && pos != -1)) { - pos = S.indexOf(closeBracket, pos + 1); - } - if (pos === -1) { - pos = S.length; - } - if (keepComments) { - children.push(S.substring(startCommentPos, pos + 1)); - } - } else if ( - S.charCodeAt(pos + 2) === openCornerBracketCC && - S.charCodeAt(pos + 8) === openCornerBracketCC && - S.substr(pos + 3, 5).toLowerCase() === 'cdata' - ) { - // cdata - var cdataEndIndex = S.indexOf(']]>', pos); - if (cdataEndIndex == -1) { - children.push(S.substr(pos + 9)); - pos = S.length; - } else { - children.push(S.substring(pos + 9, cdataEndIndex)); - pos = cdataEndIndex + 3; - } - continue; - } else { - // doctypesupport - const startDoctype = pos + 1; - pos += 2; - var encapsuled = false; - while ((S.charCodeAt(pos) !== closeBracketCC || encapsuled === true) && S[pos]) { - if (S.charCodeAt(pos) === openCornerBracketCC) { - encapsuled = true; - } else if (encapsuled === true && S.charCodeAt(pos) === closeCornerBracketCC) { - encapsuled = false; - } - pos++; - } - children.push(S.substring(startDoctype, pos)); - } - pos++; - continue; - } - var node = parseNode(); - children.push(node); - if (node.tagName[0] === '?') { - children.push(...node.children); - node.children = []; - } - } else { - var text = parseText(); - if (keepWhitespace) { - if (text.length > 0) { - children.push(text); - } - } else { - var trimmed = text.trim(); - if (trimmed.length > 0) { - children.push(trimmed); - } - } - pos++; - } - } - return children; - } - - /** - * returns the text outside of texts until the first '<' - */ - function parseText() { - var start = pos; - pos = S.indexOf(openBracket, pos) - 1; - if (pos === -2) - pos = S.length; - return S.slice(start, pos + 1); - } - /** - * returns text until the first nonAlphabetic letter - */ - var nameSpacer = '\r\n\t>/= '; - - function parseName() { - var start = pos; - while (nameSpacer.indexOf(S[pos]) === -1 && S[pos]) { - pos++; - } - return S.slice(start, pos); - } - /** - * is parsing a node, including tagName, Attributes and its children, - * to parse children it uses the parseChildren again, that makes the parsing recursive - */ - var NoChildNodes = options.noChildNodes || ['img', 'br', 'input', 'meta', 'link', 'hr']; - - function parseNode() { - pos++; - const tagName = parseName(); - const attributes = {}; - let children = []; - - // parsing attributes - while (S.charCodeAt(pos) !== closeBracketCC && S[pos]) { - var c = S.charCodeAt(pos); - if ((c > 64 && c < 91) || (c > 96 && c < 123)) { - //if('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(S[pos])!==-1 ){ - var name = parseName(); - // search beginning of the string - var code = S.charCodeAt(pos); - while (code && code !== singleQuoteCC && code !== doubleQuoteCC && !((code > 64 && code < 91) || (code > 96 && code < 123)) && code !== closeBracketCC) { - pos++; - code = S.charCodeAt(pos); - } - if (code === singleQuoteCC || code === doubleQuoteCC) { - var value = parseString(); - if (pos === -1) { - return { - tagName, - attributes, - children, - }; - } - } else { - value = null; - pos--; - } - attributes[name] = value; - } - pos++; - } - // optional parsing of children - if (S.charCodeAt(pos - 1) !== slashCC) { - if (tagName == "script") { - var start = pos + 1; - pos = S.indexOf('', pos); - children = [S.slice(start, pos)]; - pos += 9; - } else if (tagName == "style") { - var start = pos + 1; - pos = S.indexOf('', pos); - children = [S.slice(start, pos)]; - pos += 8; - } else if (NoChildNodes.indexOf(tagName) === -1) { - pos++; - children = parseChildren(tagName); - } else { - pos++; - } - } else { - pos++; - } - return { - tagName, - attributes, - children, - }; - } - - /** - * is parsing a string, that starts with a char and with the same usually ' or " - */ - - function parseString() { - var startChar = S[pos]; - var startpos = pos + 1; - pos = S.indexOf(startChar, startpos); - return S.slice(startpos, pos); - } - - /** - * - */ - function findElements() { - var r = new RegExp('\\s' + options.attrName + '\\s*=[\'"]' + options.attrValue + '[\'"]').exec(S); - if (r) { - return r.index; - } else { - return -1; - } - } - - var out = null; - if (options.attrValue !== undefined) { - options.attrName = options.attrName || 'id'; - var out = []; - - while ((pos = findElements()) !== -1) { - pos = S.lastIndexOf('<', pos); - if (pos !== -1) { - out.push(parseNode()); - } - S = S.substr(pos); - pos = 0; - } - } else if (options.parseNode) { - out = parseNode(); - } else { - out = parseChildren(''); - } - - if (options.filter) { - out = filter(out, options.filter); - } - - if (options.simplify) { - return simplify(Array.isArray(out) ? out : [out]); - } - - if (options.setPos) { - out.pos = pos; - } - - return out; -} - -/** - * transform the DomObject to an object that is like the object of PHP`s simple_xmp_load_*() methods. - * this format helps you to write that is more likely to keep your program working, even if there a small changes in the XML schema. - * be aware, that it is not possible to reproduce the original xml from a simplified version, because the order of elements is not saved. - * therefore your program will be more flexible and easier to read. - * - * @param {tNode[]} children the childrenList - */ -function simplify(children) { - var out = {}; - if (!children.length) { - return ''; - } - - if (children.length === 1 && typeof children[0] == 'string') { - return children[0]; - } - // map each object - children.forEach(function(child) { - if (typeof child !== 'object') { - return; - } - if (!out[child.tagName]) - out[child.tagName] = []; - var kids = simplify(child.children); - out[child.tagName].push(kids); - if (Object.keys(child.attributes).length && typeof kids !== 'string') { - kids._attributes = child.attributes; - } - }); - - for (var i in out) { - if (out[i].length == 1) { - out[i] = out[i][0]; - } - } - - return out; -} - -/** - * similar to simplify, but lost less - * - * @param {tNode[]} children the childrenList - */ -function simplifyLostLess(children, parentAttributes = {}) { - var out = {}; - if (!children.length) { - return out; - } - - if (children.length === 1 && typeof children[0] == 'string') { - return Object.keys(parentAttributes).length ? { - _attributes: parentAttributes, - value: children[0] - } : children[0]; - } - // map each object - children.forEach(function(child) { - if (typeof child !== 'object') { - return; - } - if (!out[child.tagName]) - out[child.tagName] = []; - var kids = simplifyLostLess(child.children || [], child.attributes); - out[child.tagName].push(kids); - if (Object.keys(child.attributes).length) { - kids._attributes = child.attributes; - } - }); - - return out; -} -/** - * behaves the same way as Array.filter, if the filter method return true, the element is in the resultList - * @params children{Array} the children of a node - * @param f{function} the filter method - */ -function filter(children, f, dept = 0, path = '') { - var out = []; - children.forEach(function(child, i) { - if (typeof(child) === 'object' && f(child, i, dept, path)) out.push(child); - if (child.children) { - var kids = filter(child.children, f, dept + 1, (path ? path + '.' : '') + i + '.' + child.tagName); - out = out.concat(kids); - } - }); - return out; -} -/** - * stringify a previously parsed string object. - * this is useful, - * 1. to remove whitespace - * 2. to recreate xml data, with some changed data. - * @param {tNode} O the object to Stringify - */ -function stringify(O) { - var out = ''; - - function writeChildren(O) { - if (O) { - for (var i = 0; i < O.length; i++) { - if (typeof O[i] == 'string') { - out += O[i].trim(); - } else { - writeNode(O[i]); - } - } - } - } - - function writeNode(N) { - out += "<" + N.tagName; - for (var i in N.attributes) { - if (N.attributes[i] === null) { - out += ' ' + i; - } else if (N.attributes[i].indexOf('"') === -1) { - out += ' ' + i + '="' + N.attributes[i].trim() + '"'; - } else { - out += ' ' + i + "='" + N.attributes[i].trim() + "'"; - } - } - if (N.tagName[0] === '?') { - out += '?>'; - return; - } - out += '>'; - writeChildren(N.children); - out += ''; - } - writeChildren(O); - - return out; -} - -/** - * use this method to read the text content, of some node. - * It is great if you have mixed content like: - * this text has some big text and a link - * @return {string} - */ -function toContentString(tDom) { - if (Array.isArray(tDom)) { - var out = ''; - tDom.forEach(function(e) { - out += ' ' + toContentString(e); - out = out.trim(); - }); - return out; - } else if (typeof tDom === 'object') { - return toContentString(tDom.children) - } else { - return ' ' + tDom; - } -} -function getElementById(S, id, simplified) { - var out = parse(S, { - attrValue: id - }); - return simplified ? tXml.simplify(out) : out[0]; -} -function getElementsByClassName(S, classname, simplified) { - const out = parse(S, { - attrName: 'class', - attrValue: '[a-zA-Z0-9- ]*' + classname + '[a-zA-Z0-9- ]*' - }); - return simplified ? tXml.simplify(out) : out; -} - -export { filter, getElementById, getElementsByClassName, parse, simplify, simplifyLostLess, stringify, toContentString }; - diff --git a/GameDev/bin/Release/project_template/utils/Clock.js b/GameDev/bin/Release/project_template/utils/Clock.js deleted file mode 100644 index 94cae91e..00000000 --- a/GameDev/bin/Release/project_template/utils/Clock.js +++ /dev/null @@ -1,68 +0,0 @@ -class Clock { - - constructor( autoStart = true ) { - - this.autoStart = autoStart; - - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; - - this.running = false; - - } - - start() { - - this.startTime = now(); - - this.oldTime = this.startTime; - this.elapsedTime = 0; - this.running = true; - - } - - stop() { - - this.getElapsedTime(); - this.running = false; - this.autoStart = false; - - } - - getElapsedTime() { - - this.getDelta(); - return this.elapsedTime; - - } - - getDelta() { - - let diff = 0; - - if ( this.autoStart && ! this.running ) { - - this.start(); - return 0; - - } - - if ( this.running ) { - - const newTime = now(); - - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; - - this.elapsedTime += diff; - - } - - return diff; - - } - -} - -export { Clock }; diff --git a/GameDev/bin/Release/project_template/view.js b/GameDev/bin/Release/project_template/view.js deleted file mode 100644 index 6f179efb..00000000 --- a/GameDev/bin/Release/project_template/view.js +++ /dev/null @@ -1,155 +0,0 @@ -import { EventDispatcher } from "./controls/EventDispatcher.js"; - -class View extends EventDispatcher { - - get clientWidth() { - return gamePlayer.width; - } - - get clientHeight() { - return gamePlayer.height; - } - - setPointerCapture() { - gamePlayer.message("setPointerCapture", ""); - } - - releasePointerCapture() { - gamePlayer.message("releasePointerCapture", ""); - } -} - -const view = new View(); - -function makeMouseEvent(e, type) { - let event = { - type: type, - pointerType: "mouse", - pointerId: 0, - clientX: e.x, - clientY: e.y, - deltaY: e.delta, - button: e.button - }; - - return event; -} - -function OnMouseDown(e) { - let event = makeMouseEvent(e, "pointerdown"); - view.dispatchEvent(event); -} - -function OnMouseUp(e) { - let event = makeMouseEvent(e, "pointerup"); - view.dispatchEvent(event); -} - -function OnMouseMove(e) { - let event = makeMouseEvent(e, "pointermove"); - view.dispatchEvent(event); -} - -function OnMouseWheel(e) { - let event = makeMouseEvent(e, "wheel"); - view.dispatchEvent(event); -} - -setCallback('OnMouseDown', OnMouseDown); -setCallback('OnMouseUp', OnMouseUp); -setCallback('OnMouseMove', OnMouseMove); -setCallback('OnMouseWheel', OnMouseWheel); - - -function makeTouchEvent(e, type) { - let event = { - type: type, - pointerType: "touch", - pointerId: e.pointerId, - pageX: e.x, - pageY: e.y, - deltaY: 0, - button: -1 - }; - - return event; -} - -function OnTouchDown(e) { - let event = makeTouchEvent(e, "pointerdown"); - view.dispatchEvent(event); -} - -function OnTouchUp(e) { - let event = makeTouchEvent(e, "pointerup"); - view.dispatchEvent(event); -} - -function OnTouchMove(e) { - let event = makeTouchEvent(e, "pointermove"); - view.dispatchEvent(event); -} - -setCallback('OnTouchDown', OnTouchDown); -setCallback('OnTouchUp', OnTouchUp); -setCallback('OnTouchMove', OnTouchMove); - - -class UIViewDispatcher extends EventDispatcher { - - constructor(view3d){ - super(); - this.view = view3d; - view3d.onMouseDown = (e)=>{ - let event = makeMouseEvent(e, "pointerdown"); - this.dispatchEvent(event); - }; - view3d.onMouseUp = (e)=>{ - let event = makeMouseEvent(e, "pointerup"); - this.dispatchEvent(event); - }; - view3d.onMouseMove = (e)=>{ - let event = makeMouseEvent(e, "pointermove"); - this.dispatchEvent(event); - }; - view3d.onMouseWheel = (e)=>{ - let event = makeMouseEvent(e, "wheel"); - this.dispatchEvent(event); - }; - view3d.onTouchDown = (e)=>{ - let event = makeTouchEvent(e, "pointerdown"); - print(JSON.stringify(event)); - this.dispatchEvent(event); - } - view3d.onTouchUp = (e)=>{ - let event = makeTouchEvent(e, "pointerup"); - print(JSON.stringify(event)); - this.dispatchEvent(event); - } - view3d.onTouchMove = (e)=>{ - let event = makeTouchEvent(e, "pointermove"); - print(JSON.stringify(event)); - this.dispatchEvent(event); - } - } - - get clientWidth() { - return this.view.size.x; - } - - get clientHeight() { - return this.view.size.y; - } - - setPointerCapture() { - gamePlayer.message("setPointerCapture", ""); - } - - releasePointerCapture() { - gamePlayer.message("releasePointerCapture", ""); - } -} - - -export { view, UIViewDispatcher }; - diff --git a/GameDev/bin/Release/swresample-3.dll b/GameDev/bin/Release/swresample-3.dll deleted file mode 100644 index b2492ed0..00000000 Binary files a/GameDev/bin/Release/swresample-3.dll and /dev/null differ diff --git a/GameDev/bin/Release/swscale-5.dll b/GameDev/bin/Release/swscale-5.dll deleted file mode 100644 index 3315062c..00000000 Binary files a/GameDev/bin/Release/swscale-5.dll and /dev/null differ diff --git a/GameDev/bin/Release/v8.dll b/GameDev/bin/Release/v8.dll deleted file mode 100644 index 7737c6ae..00000000 Binary files a/GameDev/bin/Release/v8.dll and /dev/null differ diff --git a/GameDev/bin/Release/v8_libbase.dll b/GameDev/bin/Release/v8_libbase.dll deleted file mode 100644 index 419e0f91..00000000 Binary files a/GameDev/bin/Release/v8_libbase.dll and /dev/null differ diff --git a/GameDev/bin/Release/v8_libplatform.dll b/GameDev/bin/Release/v8_libplatform.dll deleted file mode 100644 index fb940ec9..00000000 Binary files a/GameDev/bin/Release/v8_libplatform.dll and /dev/null differ diff --git a/GameDev/bin/Release/xmleditor/bundle_index.js b/GameDev/bin/Release/xmleditor/bundle_index.js deleted file mode 100644 index 8d037b72..00000000 --- a/GameDev/bin/Release/xmleditor/bundle_index.js +++ /dev/null @@ -1,7898 +0,0 @@ -/** - * https://github.com/mrdoob/eventdispatcher.js/ - */ - -class EventDispatcher { - - addEventListener( type, listener ) { - - if ( this._listeners === undefined ) this._listeners = {}; - - const listeners = this._listeners; - - if ( listeners[ type ] === undefined ) { - - listeners[ type ] = []; - - } - - if ( listeners[ type ].indexOf( listener ) === - 1 ) { - - listeners[ type ].push( listener ); - - } - - } - - hasEventListener( type, listener ) { - - if ( this._listeners === undefined ) return false; - - const listeners = this._listeners; - - return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; - - } - - removeEventListener( type, listener ) { - - if ( this._listeners === undefined ) return; - - const listeners = this._listeners; - const listenerArray = listeners[ type ]; - - if ( listenerArray !== undefined ) { - - const index = listenerArray.indexOf( listener ); - - if ( index !== - 1 ) { - - listenerArray.splice( index, 1 ); - - } - - } - - } - - dispatchEvent( event ) { - if ( this._listeners === undefined ) return; - - const listeners = this._listeners; - const listenerArray = listeners[event.type]; - - if ( listenerArray !== undefined ) { - - event.target = this; - - // Make a copy, in case listeners are removed while iterating. - const array = listenerArray.slice( 0 ); - - for ( let i = 0, l = array.length; i < l; i ++ ) { - - array[ i ].call( this, event ); - - } - - event.target = null; - - } - - } - -} - -const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; -const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; - -for ( let i = 0; i < 256; i ++ ) { - - ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); - -} - -function clamp( value, min, max ) { - - return Math.max( min, Math.min( max, value ) ); - -} - -class Quaternion { - - constructor( x = 0, y = 0, z = 0, w = 1 ) { - - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - } - - static slerp( qa, qb, qm, t ) { - - console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' ); - return qm.slerpQuaternions( qa, qb, t ); - - } - - static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - - // fuzz-free, array-based Quaternion SLERP operation - - let x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ]; - - const x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; - - if ( t === 0 ) { - - dst[ dstOffset + 0 ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - return; - - } - - if ( t === 1 ) { - - dst[ dstOffset + 0 ] = x1; - dst[ dstOffset + 1 ] = y1; - dst[ dstOffset + 2 ] = z1; - dst[ dstOffset + 3 ] = w1; - return; - - } - - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - - let s = 1 - t; - const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; - - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { - - const sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); - - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; - - } - - const tDir = t * dir; - - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; - - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { - - const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; - - } - - } - - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - - } - - static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { - - const x0 = src0[ srcOffset0 ]; - const y0 = src0[ srcOffset0 + 1 ]; - const z0 = src0[ srcOffset0 + 2 ]; - const w0 = src0[ srcOffset0 + 3 ]; - - const x1 = src1[ srcOffset1 ]; - const y1 = src1[ srcOffset1 + 1 ]; - const z1 = src1[ srcOffset1 + 2 ]; - const w1 = src1[ srcOffset1 + 3 ]; - - dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; - dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; - dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; - dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; - - return dst; - - } - - get x() { - - return this._x; - - } - - set x( value ) { - - this._x = value; - this._onChangeCallback(); - - } - - get y() { - - return this._y; - - } - - set y( value ) { - - this._y = value; - this._onChangeCallback(); - - } - - get z() { - - return this._z; - - } - - set z( value ) { - - this._z = value; - this._onChangeCallback(); - - } - - get w() { - - return this._w; - - } - - set w( value ) { - - this._w = value; - this._onChangeCallback(); - - } - - set( x, y, z, w ) { - - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - this._onChangeCallback(); - - return this; - - } - - clone() { - - return new this.constructor( this._x, this._y, this._z, this._w ); - - } - - copy( quaternion ) { - - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; - - this._onChangeCallback(); - - return this; - - } - - setFromEuler( euler, update ) { - - if ( ! ( euler && euler.isEuler ) ) { - - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - - } - - const x = euler._x, y = euler._y, z = euler._z, order = euler._order; - - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m - - const cos = Math.cos; - const sin = Math.sin; - - const c1 = cos( x / 2 ); - const c2 = cos( y / 2 ); - const c3 = cos( z / 2 ); - - const s1 = sin( x / 2 ); - const s2 = sin( y / 2 ); - const s3 = sin( z / 2 ); - - switch ( order ) { - - case 'XYZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'YXZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - case 'ZXY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'ZYX': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - case 'YZX': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'XZY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - default: - console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); - - } - - if ( update !== false ) this._onChangeCallback(); - - return this; - - } - - setFromAxisAngle( axis, angle ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - - // assumes axis is normalized - - const halfAngle = angle / 2, s = Math.sin( halfAngle ); - - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); - - this._onChangeCallback(); - - return this; - - } - - setFromRotationMatrix( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - const te = m.elements, - - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - - trace = m11 + m22 + m33; - - if ( trace > 0 ) { - - const s = 0.5 / Math.sqrt( trace + 1.0 ); - - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; - - } else if ( m11 > m22 && m11 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; - - } else if ( m22 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; - - } else { - - const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; - - } - - this._onChangeCallback(); - - return this; - - } - - setFromUnitVectors( vFrom, vTo ) { - - // assumes direction vectors vFrom and vTo are normalized - - let r = vFrom.dot( vTo ) + 1; - - if ( r < Number.EPSILON ) { - - // vFrom and vTo point in opposite directions - - r = 0; - - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - - this._x = - vFrom.y; - this._y = vFrom.x; - this._z = 0; - this._w = r; - - } else { - - this._x = 0; - this._y = - vFrom.z; - this._z = vFrom.y; - this._w = r; - - } - - } else { - - // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 - - this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; - this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; - this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; - this._w = r; - - } - - return this.normalize(); - - } - - angleTo( q ) { - - return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) ); - - } - - rotateTowards( q, step ) { - - const angle = this.angleTo( q ); - - if ( angle === 0 ) return this; - - const t = Math.min( 1, step / angle ); - - this.slerp( q, t ); - - return this; - - } - - identity() { - - return this.set( 0, 0, 0, 1 ); - - } - - invert() { - - // quaternion is assumed to have unit length - - return this.conjugate(); - - } - - conjugate() { - - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; - - this._onChangeCallback(); - - return this; - - } - - dot( v ) { - - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - - } - - lengthSq() { - - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - - } - - length() { - - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - - } - - normalize() { - - let l = this.length(); - - if ( l === 0 ) { - - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; - - } else { - - l = 1 / l; - - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; - - } - - this._onChangeCallback(); - - return this; - - } - - multiply( q, p ) { - - if ( p !== undefined ) { - - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); - - } - - return this.multiplyQuaternions( this, q ); - - } - - premultiply( q ) { - - return this.multiplyQuaternions( q, this ); - - } - - multiplyQuaternions( a, b ) { - - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - - const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - - this._onChangeCallback(); - - return this; - - } - - slerp( qb, t ) { - - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); - - const x = this._x, y = this._y, z = this._z, w = this._w; - - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - - let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - - if ( cosHalfTheta < 0 ) { - - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; - - cosHalfTheta = - cosHalfTheta; - - } else { - - this.copy( qb ); - - } - - if ( cosHalfTheta >= 1.0 ) { - - this._w = w; - this._x = x; - this._y = y; - this._z = z; - - return this; - - } - - const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; - - if ( sqrSinHalfTheta <= Number.EPSILON ) { - - const s = 1 - t; - this._w = s * w + t * this._w; - this._x = s * x + t * this._x; - this._y = s * y + t * this._y; - this._z = s * z + t * this._z; - - this.normalize(); - this._onChangeCallback(); - - return this; - - } - - const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); - const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); - - this._onChangeCallback(); - - return this; - - } - - slerpQuaternions( qa, qb, t ) { - - this.copy( qa ).slerp( qb, t ); - - } - - random() { - - // Derived from http://planning.cs.uiuc.edu/node198.html - // Note, this source uses w, x, y, z ordering, - // so we swap the order below. - - const u1 = Math.random(); - const sqrt1u1 = Math.sqrt( 1 - u1 ); - const sqrtu1 = Math.sqrt( u1 ); - - const u2 = 2 * Math.PI * Math.random(); - - const u3 = 2 * Math.PI * Math.random(); - - return this.set( - sqrt1u1 * Math.cos( u2 ), - sqrtu1 * Math.sin( u3 ), - sqrtu1 * Math.cos( u3 ), - sqrt1u1 * Math.sin( u2 ), - ); - - } - - equals( quaternion ) { - - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - - } - - fromArray( array, offset = 0 ) { - - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; - - this._onChangeCallback(); - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; - - return array; - - } - - fromBufferAttribute( attribute, index ) { - - this._x = attribute.getX( index ); - this._y = attribute.getY( index ); - this._z = attribute.getZ( index ); - this._w = attribute.getW( index ); - - return this; - - } - - _onChange( callback ) { - - this._onChangeCallback = callback; - - return this; - - } - - _onChangeCallback() {} - -} - -Quaternion.prototype.isQuaternion = true; - -/** - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. - * The azimuthal angle (theta) is measured from the positive z-axis. - */ - -class Spherical { - - constructor( radius = 1, phi = 0, theta = 0 ) { - - this.radius = radius; - this.phi = phi; // polar angle - this.theta = theta; // azimuthal angle - - return this; - - } - - set( radius, phi, theta ) { - - this.radius = radius; - this.phi = phi; - this.theta = theta; - - return this; - - } - - copy( other ) { - - this.radius = other.radius; - this.phi = other.phi; - this.theta = other.theta; - - return this; - - } - - // restrict phi to be betwee EPS and PI-EPS - makeSafe() { - - const EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - - return this; - - } - - setFromVector3( v ) { - - return this.setFromCartesianCoords( v.x, v.y, v.z ); - - } - - setFromCartesianCoords( x, y, z ) { - - this.radius = Math.sqrt( x * x + y * y + z * z ); - - if ( this.radius === 0 ) { - - this.theta = 0; - this.phi = 0; - - } else { - - this.theta = Math.atan2( x, z ); - this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); - - } - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -class Vector2 { - - constructor( x = 0, y = 0 ) { - - this.x = x; - this.y = y; - - } - - get width() { - - return this.x; - - } - - set width( value ) { - - this.x = value; - - } - - get height() { - - return this.y; - - } - - set height( value ) { - - this.y = value; - - } - - set( x, y ) { - - this.x = x; - this.y = y; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - - return this; - - } - - multiply( v ) { - - this.x *= v.x; - this.y *= v.y; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - - return this; - - } - - divide( v ) { - - this.x /= v.x; - this.y /= v.y; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - applyMatrix3( m ) { - - const x = this.x, y = this.y; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; - - return this; - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y; - - } - - cross( v ) { - - return this.x * v.y - this.y * v.x; - - } - - lengthSq() { - - return this.x * this.x + this.y * this.y; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - angle() { - - // computes the angle in radians with respect to the positive x-axis - - const angle = Math.atan2( - this.y, - this.x ) + Math.PI; - - return angle; - - } - - distanceTo( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - } - - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; - - } - - manhattanDistanceTo( v ) { - - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - - return this; - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - - return this; - - } - - rotateAround( center, angle ) { - - const c = Math.cos( angle ), s = Math.sin( angle ); - - const x = this.x - center.x; - const y = this.y - center.y; - - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - - } - -} - -Vector2.prototype.isVector2 = true; - -class Vector3 { - - constructor( x = 0, y = 0, z = 0 ) { - - this.x = x; - this.y = y; - this.z = z; - - } - - set( x, y, z ) { - - if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) - - this.x = x; - this.y = y; - this.z = z; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - this.z = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setZ( z ) { - - this.z = z; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y, this.z ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - this.z += v.z; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - this.z += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - this.z -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - - return this; - - } - - multiply( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); - - } - - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - - return this; - - } - - multiplyVectors( a, b ) { - - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; - - return this; - - } - - applyEuler( euler ) { - - if ( ! ( euler && euler.isEuler ) ) { - - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - - } - - return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); - - } - - applyAxisAngle( axis, angle ) { - - return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); - - } - - applyMatrix3( m ) { - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; - this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; - - return this; - - } - - applyNormalMatrix( m ) { - - return this.applyMatrix3( m ).normalize(); - - } - - applyMatrix4( m ) { - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); - - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; - this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; - - return this; - - } - - applyQuaternion( q ) { - - const x = this.x, y = this.y, z = this.z; - const qx = q.x, qy = q.y, qz = q.z, qw = q.w; - - // calculate quat * vector - - const ix = qw * x + qy * z - qz * y; - const iy = qw * y + qz * x - qx * z; - const iz = qw * z + qx * y - qy * x; - const iw = - qx * x - qy * y - qz * z; - - // calculate result * inverse quat - - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; - - return this; - - } - - project( camera ) { - - return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); - - } - - unproject( camera ) { - - return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); - - } - - transformDirection( m ) { - - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; - - return this.normalize(); - - } - - divide( v ) { - - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z; - - } - - // TODO lengthSquared? - - lengthSq() { - - return this.x * this.x + this.y * this.y + this.z * this.z; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; - - return this; - - } - - cross( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); - - } - - return this.crossVectors( this, v ); - - } - - crossVectors( a, b ) { - - const ax = a.x, ay = a.y, az = a.z; - const bx = b.x, by = b.y, bz = b.z; - - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - - return this; - - } - - projectOnVector( v ) { - - const denominator = v.lengthSq(); - - if ( denominator === 0 ) return this.set( 0, 0, 0 ); - - const scalar = v.dot( this ) / denominator; - - return this.copy( v ).multiplyScalar( scalar ); - - } - - projectOnPlane( planeNormal ) { - - _vector.copy( this ).projectOnVector( planeNormal ); - - return this.sub( _vector ); - - } - - reflect( normal ) { - - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length - - return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - - } - - angleTo( v ) { - - const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); - - if ( denominator === 0 ) return Math.PI / 2; - - const theta = this.dot( v ) / denominator; - - // clamp, to handle numerical problems - - return Math.acos( clamp( theta, - 1, 1 ) ); - - } - - distanceTo( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - } - - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - - return dx * dx + dy * dy + dz * dz; - - } - - manhattanDistanceTo( v ) { - - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - - } - - setFromSpherical( s ) { - - return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); - - } - - setFromSphericalCoords( radius, phi, theta ) { - - const sinPhiRadius = Math.sin( phi ) * radius; - - this.x = sinPhiRadius * Math.sin( theta ); - this.y = Math.cos( phi ) * radius; - this.z = sinPhiRadius * Math.cos( theta ); - - return this; - - } - - setFromCylindrical( c ) { - - return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); - - } - - setFromCylindricalCoords( radius, theta, y ) { - - this.x = radius * Math.sin( theta ); - this.y = y; - this.z = radius * Math.cos( theta ); - - return this; - - } - - setFromMatrixPosition( m ) { - - const e = m.elements; - - this.x = e[ 12 ]; - this.y = e[ 13 ]; - this.z = e[ 14 ]; - - return this; - - } - - setFromMatrixScale( m ) { - - const sx = this.setFromMatrixColumn( m, 0 ).length(); - const sy = this.setFromMatrixColumn( m, 1 ).length(); - const sz = this.setFromMatrixColumn( m, 2 ).length(); - - this.x = sx; - this.y = sy; - this.z = sz; - - return this; - - } - - setFromMatrixColumn( m, index ) { - - return this.fromArray( m.elements, index * 4 ); - - } - - setFromMatrix3Column( m, index ) { - - return this.fromArray( m.elements, index * 3 ); - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - - return this; - - } - - randomDirection() { - - // Derived from https://mathworld.wolfram.com/SpherePointPicking.html - - const u = ( Math.random() - 0.5 ) * 2; - const t = Math.random() * Math.PI * 2; - const f = Math.sqrt( 1 - u ** 2 ); - - this.x = f * Math.cos( t ); - this.y = f * Math.sin( t ); - this.z = u; - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - yield this.z; - - } - -} - -Vector3.prototype.isVector3 = true; - -const _vector = /*@__PURE__*/ new Vector3(); -const _quaternion = /*@__PURE__*/ new Quaternion(); - -class Matrix4 { - - constructor() { - - this.elements = [ - - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ]; - - if ( arguments.length > 0 ) { - - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - - } - - } - - set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - - const te = this.elements; - - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - - return this; - - } - - identity() { - - this.set( - - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - clone() { - - return new Matrix4().fromArray( this.elements ); - - } - - copy( m ) { - - const te = this.elements; - const me = m.elements; - - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; - te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; - te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; - te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; - - return this; - - } - - copyPosition( m ) { - - const te = this.elements, me = m.elements; - - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; - - return this; - - } - - setFromMatrix3( m ) { - - const me = m.elements; - - this.set( - - me[ 0 ], me[ 3 ], me[ 6 ], 0, - me[ 1 ], me[ 4 ], me[ 7 ], 0, - me[ 2 ], me[ 5 ], me[ 8 ], 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - extractBasis( xAxis, yAxis, zAxis ) { - - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); - - return this; - - } - - makeBasis( xAxis, yAxis, zAxis ) { - - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 - ); - - return this; - - } - - extractRotation( m ) { - - // this method does not support reflection matrices - - const te = this.elements; - const me = m.elements; - - const scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length(); - const scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length(); - const scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length(); - - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; - te[ 3 ] = 0; - - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; - te[ 7 ] = 0; - - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; - te[ 11 ] = 0; - - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; - - return this; - - } - - makeRotationFromEuler( euler ) { - - if ( ! ( euler && euler.isEuler ) ) { - - console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - - } - - const te = this.elements; - - const x = euler.x, y = euler.y, z = euler.z; - const a = Math.cos( x ), b = Math.sin( x ); - const c = Math.cos( y ), d = Math.sin( y ); - const e = Math.cos( z ), f = Math.sin( z ); - - if ( euler.order === 'XYZ' ) { - - const ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; - - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; - - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; - - } else if ( euler.order === 'YXZ' ) { - - const ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; - - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; - - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; - - } else if ( euler.order === 'ZXY' ) { - - const ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; - - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; - - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; - - } else if ( euler.order === 'ZYX' ) { - - const ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; - - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; - - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; - - } else if ( euler.order === 'YZX' ) { - - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; - - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; - - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; - - } else if ( euler.order === 'XZY' ) { - - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; - - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; - - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; - - } - - // bottom row - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; - - // last column - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; - - return this; - - } - - makeRotationFromQuaternion( q ) { - - return this.compose( _zero, q, _one ); - - } - - lookAt( eye, target, up ) { - - const te = this.elements; - - _z.subVectors( eye, target ); - - if ( _z.lengthSq() === 0 ) { - - // eye and target are in the same position - - _z.z = 1; - - } - - _z.normalize(); - _x.crossVectors( up, _z ); - - if ( _x.lengthSq() === 0 ) { - - // up and z are parallel - - if ( Math.abs( up.z ) === 1 ) { - - _z.x += 0.0001; - - } else { - - _z.z += 0.0001; - - } - - _z.normalize(); - _x.crossVectors( up, _z ); - - } - - _x.normalize(); - _y.crossVectors( _z, _x ); - - te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; - te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; - te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; - - return this; - - } - - multiply( m, n ) { - - if ( n !== undefined ) { - - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); - - } - - return this.multiplyMatrices( this, m ); - - } - - premultiply( m ) { - - return this.multiplyMatrices( m, this ); - - } - - multiplyMatrices( a, b ) { - - const ae = a.elements; - const be = b.elements; - const te = this.elements; - - const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - - const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - - return this; - - } - - multiplyScalar( s ) { - - const te = this.elements; - - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; - - return this; - - } - - determinant() { - - const te = this.elements; - - const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) - - ); - - } - - transpose() { - - const te = this.elements; - let tmp; - - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - - return this; - - } - - setPosition( x, y, z ) { - - const te = this.elements; - - if ( x.isVector3 ) { - - te[ 12 ] = x.x; - te[ 13 ] = x.y; - te[ 14 ] = x.z; - - } else { - - te[ 12 ] = x; - te[ 13 ] = y; - te[ 14 ] = z; - - } - - return this; - - } - - invert() { - - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - const te = this.elements, - - n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], - n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], - n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], - n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], - - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - - const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - - if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - const detInv = 1 / det; - - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; - - return this; - - } - - scale( v ) { - - const te = this.elements; - const x = v.x, y = v.y, z = v.z; - - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; - - return this; - - } - - getMaxScaleOnAxis() { - - const te = this.elements; - - const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; - - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - - } - - makeTranslation( x, y, z ) { - - this.set( - - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationX( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationY( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationZ( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationAxis( axis, angle ) { - - // Based on http://www.gamedev.net/reference/articles/article1199.asp - - const c = Math.cos( angle ); - const s = Math.sin( angle ); - const t = 1 - c; - const x = axis.x, y = axis.y, z = axis.z; - const tx = t * x, ty = t * y; - - this.set( - - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeScale( x, y, z ) { - - this.set( - - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeShear( xy, xz, yx, yz, zx, zy ) { - - this.set( - - 1, yx, zx, 0, - xy, 1, zy, 0, - xz, yz, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - compose( position, quaternion, scale ) { - - const te = this.elements; - - const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; - const x2 = x + x, y2 = y + y, z2 = z + z; - const xx = x * x2, xy = x * y2, xz = x * z2; - const yy = y * y2, yz = y * z2, zz = z * z2; - const wx = w * x2, wy = w * y2, wz = w * z2; - - const sx = scale.x, sy = scale.y, sz = scale.z; - - te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; - te[ 1 ] = ( xy + wz ) * sx; - te[ 2 ] = ( xz - wy ) * sx; - te[ 3 ] = 0; - - te[ 4 ] = ( xy - wz ) * sy; - te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; - te[ 6 ] = ( yz + wx ) * sy; - te[ 7 ] = 0; - - te[ 8 ] = ( xz + wy ) * sz; - te[ 9 ] = ( yz - wx ) * sz; - te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; - te[ 11 ] = 0; - - te[ 12 ] = position.x; - te[ 13 ] = position.y; - te[ 14 ] = position.z; - te[ 15 ] = 1; - - return this; - - } - - decompose( position, quaternion, scale ) { - - const te = this.elements; - - let sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - const sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - const sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - - // if determine is negative, we need to invert one scale - const det = this.determinant(); - if ( det < 0 ) sx = - sx; - - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; - - // scale the rotation part - _m1.copy( this ); - - const invSX = 1 / sx; - const invSY = 1 / sy; - const invSZ = 1 / sz; - - _m1.elements[ 0 ] *= invSX; - _m1.elements[ 1 ] *= invSX; - _m1.elements[ 2 ] *= invSX; - - _m1.elements[ 4 ] *= invSY; - _m1.elements[ 5 ] *= invSY; - _m1.elements[ 6 ] *= invSY; - - _m1.elements[ 8 ] *= invSZ; - _m1.elements[ 9 ] *= invSZ; - _m1.elements[ 10 ] *= invSZ; - - quaternion.setFromRotationMatrix( _m1 ); - - scale.x = sx; - scale.y = sy; - scale.z = sz; - - return this; - - } - - makePerspective( left, right, top, bottom, near, far ) { - - if ( far === undefined ) { - - console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); - - } - - const te = this.elements; - const x = 2 * near / ( right - left ); - const y = 2 * near / ( top - bottom ); - - const a = ( right + left ) / ( right - left ); - const b = ( top + bottom ) / ( top - bottom ); - const c = - ( far + near ) / ( far - near ); - const d = - 2 * far * near / ( far - near ); - - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - - return this; - - } - - makeOrthographic( left, right, top, bottom, near, far ) { - - const te = this.elements; - const w = 1.0 / ( right - left ); - const h = 1.0 / ( top - bottom ); - const p = 1.0 / ( far - near ); - - const x = ( right + left ) * w; - const y = ( top + bottom ) * h; - const z = ( far + near ) * p; - - te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; - - return this; - - } - - equals( matrix ) { - - const te = this.elements; - const me = matrix.elements; - - for ( let i = 0; i < 16; i ++ ) { - - if ( te[ i ] !== me[ i ] ) return false; - - } - - return true; - - } - - fromArray( array, offset = 0 ) { - - for ( let i = 0; i < 16; i ++ ) { - - this.elements[ i ] = array[ i + offset ]; - - } - - return this; - - } - - toArray( array = [], offset = 0 ) { - - const te = this.elements; - - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; - - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; - - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; - - return array; - - } - -} - -Matrix4.prototype.isMatrix4 = true; - -const _v1 = /*@__PURE__*/ new Vector3(); -const _m1 = /*@__PURE__*/ new Matrix4(); -const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); -const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); -const _x = /*@__PURE__*/ new Vector3(); -const _y = /*@__PURE__*/ new Vector3(); -const _z = /*@__PURE__*/ new Vector3(); - -// This set of controls performs orbiting, dollying (zooming), and panning. -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// -// Orbit - left mouse / touch: one-finger move -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move - -const _changeEvent = { type: 'change' }; -const _startEvent = { type: 'start' }; -const _endEvent = { type: 'end' }; - -class OrbitControls extends EventDispatcher { - - constructor( object, domElement ) { - - super(); - - if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); - - this.object = object; - this.domElement = domElement; - - // Set to false to disable this control - this.enabled = true; - - // "target" sets the location of focus, where the object orbits around - this.target = new Vector3(); - - // How far you can dolly in and out ( PerspectiveCamera only ) - this.minDistance = 0; - this.maxDistance = Infinity; - - // How far you can zoom in and out ( OrthographicCamera only ) - this.minZoom = 0; - this.maxZoom = Infinity; - - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - this.minPolarAngle = 0; // radians - this.maxPolarAngle = Math.PI; // radians - - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - this.minAzimuthAngle = - Infinity; // radians - this.maxAzimuthAngle = Infinity; // radians - - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - this.enableDamping = false; - this.dampingFactor = 0.05; - - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - this.enableZoom = true; - this.zoomSpeed = 1.0; - - // Set to false to disable rotating - this.enableRotate = true; - this.rotateSpeed = 1.0; - - // Set to false to disable panning - this.enablePan = true; - this.panSpeed = 1.0; - this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up - this.keyPanSpeed = 7.0; // pixels moved per arrow key push - - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - this.autoRotate = false; - this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 - - // The four arrow keys - this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; - - // Mouse buttons - this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; - - // Touch fingers - this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; - - // for reset - this.target0 = this.target.clone(); - this.position0 = this.object.getPosition(new Vector3()); - - // this.zoom0 = this.object.zoom; - this.zoom0 = 1.0; - - // the target DOM element for key events - this._domElementKeyEvents = null; - - // - // public methods - // - - this.getPolarAngle = function () { - - return spherical.phi; - - }; - - this.getAzimuthalAngle = function () { - - return spherical.theta; - - }; - - this.getDistance = function () { - let position = this.object.getPosition(new Vector3()); - return position.distanceTo( this.target ); - - }; - - this.listenToKeyEvents = function ( domElement ) { - - domElement.addEventListener( 'keydown', onKeyDown ); - this._domElementKeyEvents = domElement; - - }; - - this.saveState = function () { - - scope.target0.copy(scope.target); - this.object.getPosition(scope.position0); - - // scope.zoom0 = scope.object.zoom; - scope.zoom0 = 1.0; - - }; - - this.reset = function () { - - scope.target.copy(scope.target0); - - this.object.getPosition(scope.position0); - - // scope.object.zoom = scope.zoom0; - - scope.object.updateProjectionMatrix(); - scope.dispatchEvent( _changeEvent ); - - scope.update(); - - state = STATE.NONE; - - }; - - // this method is exposed, but perhaps it would be better if we can make it private... - this.update = function () { - - const offset = new Vector3(); - - // so camera.up is the orbit axis - let camera_up = object.getUp(new Vector3()); - const quat = new Quaternion().setFromUnitVectors(camera_up, new Vector3(0, 1, 0)); - const quatInverse = quat.clone().invert(); - - const lastPosition = new Vector3(); - const lastQuaternion = new Quaternion(); - - const twoPI = 2 * Math.PI; - - return function update() { - - const position = scope.object.getPosition(new Vector3()); - - offset.copy( position ).sub( scope.target ); - - // rotate offset to "y-axis-is-up" space - offset.applyQuaternion( quat ); - - // angle from z-axis around y-axis - spherical.setFromVector3( offset ); - - if ( scope.autoRotate && state === STATE.NONE ) { - - rotateLeft( getAutoRotationAngle() ); - - } - - if ( scope.enableDamping ) { - - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; - - } else { - - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; - - } - - // restrict theta to be between desired limits - - let min = scope.minAzimuthAngle; - let max = scope.maxAzimuthAngle; - - if ( isFinite( min ) && isFinite( max ) ) { - - if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; - - if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; - - if ( min <= max ) { - - spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); - - } else { - - spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? - Math.max( min, spherical.theta ) : - Math.min( max, spherical.theta ); - - } - - } - - // restrict phi to be between desired limits - spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); - - spherical.makeSafe(); - - - spherical.radius *= scale; - - // restrict radius to be between desired limits - spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); - - // move target to panned location - - if ( scope.enableDamping === true ) { - - scope.target.addScaledVector( panOffset, scope.dampingFactor ); - - } else { - - scope.target.add( panOffset ); - - } - - offset.setFromSpherical( spherical ); - - // rotate offset back to "camera-up-vector-is-up" space - offset.applyQuaternion( quatInverse ); - - position.copy(scope.target).add(offset); - scope.object.setPosition(position); - - scope.object.lookAt( scope.target ); - - if ( scope.enableDamping === true ) { - - sphericalDelta.theta *= ( 1 - scope.dampingFactor ); - sphericalDelta.phi *= ( 1 - scope.dampingFactor ); - - panOffset.multiplyScalar( 1 - scope.dampingFactor ); - - } else { - - sphericalDelta.set( 0, 0, 0 ); - - panOffset.set( 0, 0, 0 ); - - } - - scale = 1; - - // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 - - const quaternion = scope.object.getQuaternion(new Quaternion()); - - if ( zoomChanged || - lastPosition.distanceToSquared(position) > EPS || - 8 * (1 - lastQuaternion.dot(quaternion) ) > EPS ) { - - scope.dispatchEvent( _changeEvent ); - - lastPosition.copy(position ); - lastQuaternion.copy(quaternion); - zoomChanged = false; - - return true; - - } - - return false; - - }; - - }(); - - this.dispose = function () { - - scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); - - scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); - scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); - scope.domElement.removeEventListener( 'wheel', onMouseWheel ); - - scope.domElement.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - - - if ( scope._domElementKeyEvents !== null ) { - - scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); - - } - - //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? - - }; - - // - // internals - // - - const scope = this; - - const STATE = { - NONE: - 1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; - - let state = STATE.NONE; - - const EPS = 0.000001; - - // current position in spherical coordinates - const spherical = new Spherical(); - const sphericalDelta = new Spherical(); - - let scale = 1; - const panOffset = new Vector3(); - let zoomChanged = false; - - const rotateStart = new Vector2(); - const rotateEnd = new Vector2(); - const rotateDelta = new Vector2(); - - const panStart = new Vector2(); - const panEnd = new Vector2(); - const panDelta = new Vector2(); - - const dollyStart = new Vector2(); - const dollyEnd = new Vector2(); - const dollyDelta = new Vector2(); - - const pointers = []; - const pointerPositions = {}; - - function getAutoRotationAngle() { - - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - - } - - function getZoomScale() { - - return Math.pow( 0.95, scope.zoomSpeed ); - - } - - function rotateLeft( angle ) { - - sphericalDelta.theta -= angle; - - } - - function rotateUp( angle ) { - - sphericalDelta.phi -= angle; - - } - - const panLeft = function () { - - const v = new Vector3(); - - return function panLeft( distance, objectMatrix ) { - - v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix - v.multiplyScalar( - distance ); - - panOffset.add( v ); - - }; - - }(); - - const panUp = function () { - - const v = new Vector3(); - - return function panUp( distance, objectMatrix ) { - - if ( scope.screenSpacePanning === true ) { - - v.setFromMatrixColumn( objectMatrix, 1 ); - - } else { - let up = scope.object.getUp(new Vector3()); - v.setFromMatrixColumn( objectMatrix, 0 ); - v.crossVectors(up, v ); - - } - - v.multiplyScalar( distance ); - - panOffset.add( v ); - - }; - - }(); - - // deltaX and deltaY are in pixels; right and down are positive - const pan = function () { - - const offset = new Vector3(); - - return function pan( deltaX, deltaY ) { - - const element = scope.domElement; - - if ( scope.object.isPerspectiveCamera ) { - - // perspective - const position = scope.object.getPosition(new Vector3()); - offset.copy( position ).sub( scope.target ); - let targetDistance = offset.length(); - - // half of the fov is center to top of screen - targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); - - const matrix = scope.object.getMatrix(new Matrix4()); - // we use only clientHeight here so aspect ratio does not distort speed - panLeft(2 * deltaX * targetDistance / element.clientHeight, matrix ); - panUp(2 * deltaY * targetDistance / element.clientHeight, matrix ); - - } else if (scope.object.isOrthographicCamera) { - - const matrix = scope.object.getMatrix(new Matrix4()); - // orthographic - panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, matrix ); - panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, matrix ); - - } else { - - // camera neither orthographic nor perspective - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); - scope.enablePan = false; - - } - - }; - - }(); - - function dollyOut( dollyScale ) { - - if ( scope.object.isPerspectiveCamera ) { - - scale /= dollyScale; - - } else if ( scope.object.isOrthographicCamera ) { - - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - - } else { - - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; - - } - - } - - function dollyIn( dollyScale ) { - - if ( scope.object.isPerspectiveCamera ) { - - scale *= dollyScale; - - } else if ( scope.object.isOrthographicCamera ) { - - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - - } else { - - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; - - } - - } - - // - // event callbacks - update the object state - // - - function handleMouseDownRotate( event ) { - - rotateStart.set( event.clientX, event.clientY ); - - } - - function handleMouseDownDolly( event ) { - - dollyStart.set( event.clientX, event.clientY ); - - } - - function handleMouseDownPan( event ) { - - panStart.set( event.clientX, event.clientY ); - - } - - function handleMouseMoveRotate( event ) { - - rotateEnd.set( event.clientX, event.clientY ); - - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - - const element = scope.domElement; - - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - - rotateStart.copy( rotateEnd ); - - scope.update(); - - } - - function handleMouseMoveDolly( event ) { - - dollyEnd.set( event.clientX, event.clientY ); - - dollyDelta.subVectors( dollyEnd, dollyStart ); - - if ( dollyDelta.y > 0 ) { - - dollyOut( getZoomScale() ); - - } else if ( dollyDelta.y < 0 ) { - - dollyIn( getZoomScale() ); - - } - - dollyStart.copy( dollyEnd ); - - scope.update(); - - } - - function handleMouseMovePan( event ) { - - panEnd.set( event.clientX, event.clientY ); - - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - - pan( panDelta.x, panDelta.y ); - - panStart.copy( panEnd ); - - scope.update(); - - } - - function handleMouseWheel( event ) { - - if ( event.deltaY < 0 ) { - - dollyIn( getZoomScale() ); - - } else if ( event.deltaY > 0 ) { - - dollyOut( getZoomScale() ); - - } - - scope.update(); - - } - - function handleKeyDown( event ) { - - let needsUpdate = false; - - switch ( event.code ) { - - case scope.keys.UP: - pan( 0, scope.keyPanSpeed ); - needsUpdate = true; - break; - - case scope.keys.BOTTOM: - pan( 0, - scope.keyPanSpeed ); - needsUpdate = true; - break; - - case scope.keys.LEFT: - pan( scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; - - case scope.keys.RIGHT: - pan( - scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; - - } - - if ( needsUpdate ) { - - // prevent the browser from scrolling on cursor keys - // event.preventDefault(); - - scope.update(); - - } - - - } - - function handleTouchStartRotate() { - - if ( pointers.length === 1 ) { - - rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - - } else { - - const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); - const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - - rotateStart.set( x, y ); - - } - - } - - function handleTouchStartPan() { - - if ( pointers.length === 1 ) { - - panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - - } else { - - const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); - const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - - panStart.set( x, y ); - - } - - } - - function handleTouchStartDolly() { - - const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX; - const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY; - - const distance = Math.sqrt( dx * dx + dy * dy ); - - dollyStart.set( 0, distance ); - - } - - function handleTouchStartDollyPan() { - - if ( scope.enableZoom ) handleTouchStartDolly(); - - if ( scope.enablePan ) handleTouchStartPan(); - - } - - function handleTouchStartDollyRotate() { - - if ( scope.enableZoom ) handleTouchStartDolly(); - - if ( scope.enableRotate ) handleTouchStartRotate(); - - } - - function handleTouchMoveRotate( event ) { - - if ( pointers.length == 1 ) { - - rotateEnd.set( event.pageX, event.pageY ); - - } else { - - const position = getSecondPointerPosition( event ); - - const x = 0.5 * ( event.pageX + position.x ); - const y = 0.5 * ( event.pageY + position.y ); - - rotateEnd.set( x, y ); - - } - - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - - const element = scope.domElement; - - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - - rotateStart.copy( rotateEnd ); - - } - - function handleTouchMovePan( event ) { - - if ( pointers.length === 1 ) { - - panEnd.set( event.pageX, event.pageY ); - - } else { - - const position = getSecondPointerPosition( event ); - - const x = 0.5 * ( event.pageX + position.x ); - const y = 0.5 * ( event.pageY + position.y ); - - panEnd.set( x, y ); - - } - - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - - pan( panDelta.x, panDelta.y ); - - panStart.copy( panEnd ); - - } - - function handleTouchMoveDolly( event ) { - - const position = getSecondPointerPosition( event ); - - const dx = event.pageX - position.x; - const dy = event.pageY - position.y; - - const distance = Math.sqrt( dx * dx + dy * dy ); - - dollyEnd.set( 0, distance ); - - dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); - - dollyOut( dollyDelta.y ); - - dollyStart.copy( dollyEnd ); - - } - - function handleTouchMoveDollyPan( event ) { - - if ( scope.enableZoom ) handleTouchMoveDolly( event ); - - if ( scope.enablePan ) handleTouchMovePan( event ); - - } - - function handleTouchMoveDollyRotate( event ) { - - if ( scope.enableZoom ) handleTouchMoveDolly( event ); - - if ( scope.enableRotate ) handleTouchMoveRotate( event ); - - } - - // - // event handlers - FSM: listen for events and reset state - // - - function onPointerDown( event ) { - - if ( scope.enabled === false ) return; - - if ( pointers.length === 0 ) { - - scope.domElement.setPointerCapture(); - - scope.domElement.addEventListener( 'pointermove', onPointerMove ); - scope.domElement.addEventListener( 'pointerup', onPointerUp ); - - } - - // - - addPointer( event ); - - if ( event.pointerType === 'touch' ) { - - onTouchStart( event ); - - } else { - - onMouseDown( event ); - - } - - } - - function onPointerMove( event ) { - - if ( scope.enabled === false ) return; - - if ( event.pointerType === 'touch' ) { - - onTouchMove( event ); - - } else { - - onMouseMove( event ); - - } - - } - - function onPointerUp( event ) { - - removePointer( event ); - - if ( pointers.length === 0 ) { - - scope.domElement.releasePointerCapture(); - - scope.domElement.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - - } - - scope.dispatchEvent( _endEvent ); - - state = STATE.NONE; - - } - - function onPointerCancel( event ) { - - removePointer( event ); - - } - - function onMouseDown( event ) { - - let mouseAction; - - switch ( event.button ) { - - case 0: - - mouseAction = scope.mouseButtons.LEFT; - break; - - case 1: - - mouseAction = scope.mouseButtons.MIDDLE; - break; - - case 2: - - mouseAction = scope.mouseButtons.RIGHT; - break; - - default: - - mouseAction = - 1; - - } - - switch ( mouseAction ) { - - case MOUSE.DOLLY: - - if ( scope.enableZoom === false ) return; - - handleMouseDownDolly( event ); - - state = STATE.DOLLY; - - break; - - case MOUSE.ROTATE: - - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - - if ( scope.enablePan === false ) return; - - handleMouseDownPan( event ); - - state = STATE.PAN; - - } else { - - if ( scope.enableRotate === false ) return; - - handleMouseDownRotate( event ); - - state = STATE.ROTATE; - - } - - break; - - case MOUSE.PAN: - - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - - if ( scope.enableRotate === false ) return; - - handleMouseDownRotate( event ); - - state = STATE.ROTATE; - - } else { - - if ( scope.enablePan === false ) return; - - handleMouseDownPan( event ); - - state = STATE.PAN; - - } - - break; - - default: - - state = STATE.NONE; - - } - - if ( state !== STATE.NONE ) { - - scope.dispatchEvent( _startEvent ); - - } - - } - - function onMouseMove( event ) { - - if ( scope.enabled === false ) return; - - switch ( state ) { - - case STATE.ROTATE: - - if ( scope.enableRotate === false ) return; - - handleMouseMoveRotate( event ); - - break; - - case STATE.DOLLY: - - if ( scope.enableZoom === false ) return; - - handleMouseMoveDolly( event ); - - break; - - case STATE.PAN: - - if ( scope.enablePan === false ) return; - - handleMouseMovePan( event ); - - break; - - } - - } - - function onMouseWheel( event ) { - - if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return; - - // event.preventDefault(); - - scope.dispatchEvent( _startEvent ); - - handleMouseWheel( event ); - - scope.dispatchEvent( _endEvent ); - - } - - function onKeyDown( event ) { - - if ( scope.enabled === false || scope.enablePan === false ) return; - - handleKeyDown( event ); - - } - - function onTouchStart( event ) { - - trackPointer( event ); - - switch ( pointers.length ) { - - case 1: - - switch ( scope.touches.ONE ) { - - case TOUCH.ROTATE: - - if ( scope.enableRotate === false ) return; - - handleTouchStartRotate(); - - state = STATE.TOUCH_ROTATE; - - break; - - case TOUCH.PAN: - - if ( scope.enablePan === false ) return; - - handleTouchStartPan(); - - state = STATE.TOUCH_PAN; - - break; - - default: - - state = STATE.NONE; - - } - - break; - - case 2: - - switch ( scope.touches.TWO ) { - - case TOUCH.DOLLY_PAN: - - if ( scope.enableZoom === false && scope.enablePan === false ) return; - - handleTouchStartDollyPan(); - - state = STATE.TOUCH_DOLLY_PAN; - - break; - - case TOUCH.DOLLY_ROTATE: - - if ( scope.enableZoom === false && scope.enableRotate === false ) return; - - handleTouchStartDollyRotate(); - - state = STATE.TOUCH_DOLLY_ROTATE; - - break; - - default: - - state = STATE.NONE; - - } - - break; - - default: - - state = STATE.NONE; - - } - - if ( state !== STATE.NONE ) { - - scope.dispatchEvent( _startEvent ); - - } - - } - - function onTouchMove( event ) { - - trackPointer( event ); - - switch ( state ) { - - case STATE.TOUCH_ROTATE: - - if ( scope.enableRotate === false ) return; - - handleTouchMoveRotate( event ); - - scope.update(); - - break; - - case STATE.TOUCH_PAN: - - if ( scope.enablePan === false ) return; - - handleTouchMovePan( event ); - - scope.update(); - - break; - - case STATE.TOUCH_DOLLY_PAN: - - if ( scope.enableZoom === false && scope.enablePan === false ) return; - - handleTouchMoveDollyPan( event ); - - scope.update(); - - break; - - case STATE.TOUCH_DOLLY_ROTATE: - - if ( scope.enableZoom === false && scope.enableRotate === false ) return; - - handleTouchMoveDollyRotate( event ); - - scope.update(); - - break; - - default: - - state = STATE.NONE; - - } - - } - - function onContextMenu( event ) { - - if ( scope.enabled === false ) return; - - // event.preventDefault(); - - } - - function addPointer( event ) { - - pointers.push( event ); - - } - - function removePointer( event ) { - - delete pointerPositions[ event.pointerId ]; - - for ( let i = 0; i < pointers.length; i ++ ) { - - if ( pointers[ i ].pointerId == event.pointerId ) { - - pointers.splice( i, 1 ); - return; - - } - - } - - } - - function trackPointer( event ) { - - let position = pointerPositions[ event.pointerId ]; - - if ( position === undefined ) { - - position = new Vector2(); - pointerPositions[ event.pointerId ] = position; - - } - - position.set( event.pageX, event.pageY ); - - } - - function getSecondPointerPosition( event ) { - - const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ]; - - return pointerPositions[ pointer.pointerId ]; - - } - - // - - scope.domElement.addEventListener( 'contextmenu', onContextMenu ); - - scope.domElement.addEventListener( 'pointerdown', onPointerDown ); - scope.domElement.addEventListener( 'pointercancel', onPointerCancel ); - scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); - - // force an update at start - - this.update(); - - } - -} - -class View extends EventDispatcher { - - get clientWidth() { - return gamePlayer.width; - } - - get clientHeight() { - return gamePlayer.height; - } - - setPointerCapture() { - gamePlayer.message("setPointerCapture", ""); - } - - releasePointerCapture() { - gamePlayer.message("releasePointerCapture", ""); - } -} - -const view = new View(); - -function makeMouseEvent(e, type) { - let event = { - type: type, - pointerType: "mouse", - pointerId: 0, - clientX: e.x, - clientY: e.y, - deltaY: e.delta, - button: e.button - }; - - return event; -} - -function OnMouseDown(e) { - let event = makeMouseEvent(e, "pointerdown"); - view.dispatchEvent(event); -} - -function OnMouseUp(e) { - let event = makeMouseEvent(e, "pointerup"); - view.dispatchEvent(event); -} - -function OnMouseMove(e) { - let event = makeMouseEvent(e, "pointermove"); - view.dispatchEvent(event); -} - -function OnMouseWheel(e) { - let event = makeMouseEvent(e, "wheel"); - view.dispatchEvent(event); -} - -setCallback('OnMouseDown', OnMouseDown); -setCallback('OnMouseUp', OnMouseUp); -setCallback('OnMouseMove', OnMouseMove); -setCallback('OnMouseWheel', OnMouseWheel); - - -function makeTouchEvent(e, type) { - let event = { - type: type, - pointerType: "touch", - pointerId: e.pointerId, - pageX: e.x, - pageY: e.y, - deltaY: 0, - button: -1 - }; - - return event; -} - -function OnTouchDown(e) { - let event = makeTouchEvent(e, "pointerdown"); - view.dispatchEvent(event); -} - -function OnTouchUp(e) { - let event = makeTouchEvent(e, "pointerup"); - view.dispatchEvent(event); -} - -function OnTouchMove(e) { - let event = makeTouchEvent(e, "pointermove"); - view.dispatchEvent(event); -} - -setCallback('OnTouchDown', OnTouchDown); -setCallback('OnTouchUp', OnTouchUp); -setCallback('OnTouchMove', OnTouchMove); - -// ==ClosureCompiler== -// @output_file_name default.js -// @compilation_level SIMPLE_OPTIMIZATIONS -// ==/ClosureCompiler== -// module.exports = { -// parse: parse, -// simplify: simplify, -// simplifyLostLess: simplifyLostLess, -// filter: filter, -// stringify: stringify, -// toContentString: toContentString, -// getElementById: getElementById, -// getElementsByClassName: getElementsByClassName, -// transformStream: transformStream, -// }; - -/** - * @author: Tobias Nickel - * @created: 06.04.2015 - * I needed a small xmlparser chat can be used in a worker. - */ - -/** - * @typedef tNode - * @property {string} tagName - * @property {object} attributes - * @property {(tNode|string)[]} children - **/ - -/** - * @typedef TParseOptions - * @property {number} [pos] - * @property {string[]} [noChildNodes] - * @property {boolean} [setPos] - * @property {boolean} [keepComments] - * @property {boolean} [keepWhitespace] - * @property {boolean} [simplify] - * @property {(a: tNode, b: tNode) => boolean} [filter] - */ - -/** - * parseXML / html into a DOM Object. with no validation and some failur tolerance - * @param {string} S your XML to parse - * @param {TParseOptions} [options] all other options: - * @return {(tNode | string)[]} - */ -function parse(S, options) { - "txml"; - options = options || {}; - - var pos = options.pos || 0; - var keepComments = !!options.keepComments; - var keepWhitespace = !!options.keepWhitespace; - - var openBracket = "<"; - var openBracketCC = "<".charCodeAt(0); - var closeBracket = ">"; - var closeBracketCC = ">".charCodeAt(0); - var minusCC = "-".charCodeAt(0); - var slashCC = "/".charCodeAt(0); - var exclamationCC = '!'.charCodeAt(0); - var singleQuoteCC = "'".charCodeAt(0); - var doubleQuoteCC = '"'.charCodeAt(0); - var openCornerBracketCC = '['.charCodeAt(0); - var closeCornerBracketCC = ']'.charCodeAt(0); - - - /** - * parsing a list of entries - */ - function parseChildren(tagName) { - var children = []; - while (S[pos]) { - if (S.charCodeAt(pos) == openBracketCC) { - if (S.charCodeAt(pos + 1) === slashCC) { - var closeStart = pos + 2; - pos = S.indexOf(closeBracket, pos); - - var closeTag = S.substring(closeStart, pos); - if (closeTag.indexOf(tagName) == -1) { - var parsedText = S.substring(0, pos).split('\n'); - throw new Error( - 'Unexpected close tag\nLine: ' + (parsedText.length - 1) + - '\nColumn: ' + (parsedText[parsedText.length - 1].length + 1) + - '\nChar: ' + S[pos] - ); - } - - if (pos + 1) pos += 1; - - return children; - } else if (S.charCodeAt(pos + 1) === exclamationCC) { - if (S.charCodeAt(pos + 2) == minusCC) { - //comment support - const startCommentPos = pos; - while (pos !== -1 && !(S.charCodeAt(pos) === closeBracketCC && S.charCodeAt(pos - 1) == minusCC && S.charCodeAt(pos - 2) == minusCC && pos != -1)) { - pos = S.indexOf(closeBracket, pos + 1); - } - if (pos === -1) { - pos = S.length; - } - if (keepComments) { - children.push(S.substring(startCommentPos, pos + 1)); - } - } else if ( - S.charCodeAt(pos + 2) === openCornerBracketCC && - S.charCodeAt(pos + 8) === openCornerBracketCC && - S.substr(pos + 3, 5).toLowerCase() === 'cdata' - ) { - // cdata - var cdataEndIndex = S.indexOf(']]>', pos); - if (cdataEndIndex == -1) { - children.push(S.substr(pos + 9)); - pos = S.length; - } else { - children.push(S.substring(pos + 9, cdataEndIndex)); - pos = cdataEndIndex + 3; - } - continue; - } else { - // doctypesupport - const startDoctype = pos + 1; - pos += 2; - var encapsuled = false; - while ((S.charCodeAt(pos) !== closeBracketCC || encapsuled === true) && S[pos]) { - if (S.charCodeAt(pos) === openCornerBracketCC) { - encapsuled = true; - } else if (encapsuled === true && S.charCodeAt(pos) === closeCornerBracketCC) { - encapsuled = false; - } - pos++; - } - children.push(S.substring(startDoctype, pos)); - } - pos++; - continue; - } - var node = parseNode(); - children.push(node); - if (node.tagName[0] === '?') { - children.push(...node.children); - node.children = []; - } - } else { - var text = parseText(); - if (keepWhitespace) { - if (text.length > 0) { - children.push(text); - } - } else { - var trimmed = text.trim(); - if (trimmed.length > 0) { - children.push(trimmed); - } - } - pos++; - } - } - return children; - } - - /** - * returns the text outside of texts until the first '<' - */ - function parseText() { - var start = pos; - pos = S.indexOf(openBracket, pos) - 1; - if (pos === -2) - pos = S.length; - return S.slice(start, pos + 1); - } - /** - * returns text until the first nonAlphabetic letter - */ - var nameSpacer = '\r\n\t>/= '; - - function parseName() { - var start = pos; - while (nameSpacer.indexOf(S[pos]) === -1 && S[pos]) { - pos++; - } - return S.slice(start, pos); - } - /** - * is parsing a node, including tagName, Attributes and its children, - * to parse children it uses the parseChildren again, that makes the parsing recursive - */ - var NoChildNodes = options.noChildNodes || ['img', 'br', 'input', 'meta', 'link', 'hr']; - - function parseNode() { - pos++; - const tagName = parseName(); - const attributes = {}; - let children = []; - - // parsing attributes - while (S.charCodeAt(pos) !== closeBracketCC && S[pos]) { - var c = S.charCodeAt(pos); - if ((c > 64 && c < 91) || (c > 96 && c < 123)) { - //if('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(S[pos])!==-1 ){ - var name = parseName(); - // search beginning of the string - var code = S.charCodeAt(pos); - while (code && code !== singleQuoteCC && code !== doubleQuoteCC && !((code > 64 && code < 91) || (code > 96 && code < 123)) && code !== closeBracketCC) { - pos++; - code = S.charCodeAt(pos); - } - if (code === singleQuoteCC || code === doubleQuoteCC) { - var value = parseString(); - if (pos === -1) { - return { - tagName, - attributes, - children, - }; - } - } else { - value = null; - pos--; - } - attributes[name] = value; - } - pos++; - } - // optional parsing of children - if (S.charCodeAt(pos - 1) !== slashCC) { - if (tagName == "script") { - var start = pos + 1; - pos = S.indexOf('', pos); - children = [S.slice(start, pos)]; - pos += 9; - } else if (tagName == "style") { - var start = pos + 1; - pos = S.indexOf('', pos); - children = [S.slice(start, pos)]; - pos += 8; - } else if (NoChildNodes.indexOf(tagName) === -1) { - pos++; - children = parseChildren(tagName); - } else { - pos++; - } - } else { - pos++; - } - return { - tagName, - attributes, - children, - }; - } - - /** - * is parsing a string, that starts with a char and with the same usually ' or " - */ - - function parseString() { - var startChar = S[pos]; - var startpos = pos + 1; - pos = S.indexOf(startChar, startpos); - return S.slice(startpos, pos); - } - - /** - * - */ - function findElements() { - var r = new RegExp('\\s' + options.attrName + '\\s*=[\'"]' + options.attrValue + '[\'"]').exec(S); - if (r) { - return r.index; - } else { - return -1; - } - } - - var out = null; - if (options.attrValue !== undefined) { - options.attrName = options.attrName || 'id'; - var out = []; - - while ((pos = findElements()) !== -1) { - pos = S.lastIndexOf('<', pos); - if (pos !== -1) { - out.push(parseNode()); - } - S = S.substr(pos); - pos = 0; - } - } else if (options.parseNode) { - out = parseNode(); - } else { - out = parseChildren(''); - } - - if (options.filter) { - out = filter(out, options.filter); - } - - if (options.simplify) { - return simplify(Array.isArray(out) ? out : [out]); - } - - if (options.setPos) { - out.pos = pos; - } - - return out; -} - -/** - * transform the DomObject to an object that is like the object of PHP`s simple_xmp_load_*() methods. - * this format helps you to write that is more likely to keep your program working, even if there a small changes in the XML schema. - * be aware, that it is not possible to reproduce the original xml from a simplified version, because the order of elements is not saved. - * therefore your program will be more flexible and easier to read. - * - * @param {tNode[]} children the childrenList - */ -function simplify(children) { - var out = {}; - if (!children.length) { - return ''; - } - - if (children.length === 1 && typeof children[0] == 'string') { - return children[0]; - } - // map each object - children.forEach(function(child) { - if (typeof child !== 'object') { - return; - } - if (!out[child.tagName]) - out[child.tagName] = []; - var kids = simplify(child.children); - out[child.tagName].push(kids); - if (Object.keys(child.attributes).length && typeof kids !== 'string') { - kids._attributes = child.attributes; - } - }); - - for (var i in out) { - if (out[i].length == 1) { - out[i] = out[i][0]; - } - } - - return out; -} -/** - * behaves the same way as Array.filter, if the filter method return true, the element is in the resultList - * @params children{Array} the children of a node - * @param f{function} the filter method - */ -function filter(children, f, dept = 0, path = '') { - var out = []; - children.forEach(function(child, i) { - if (typeof(child) === 'object' && f(child, i, dept, path)) out.push(child); - if (child.children) { - var kids = filter(child.children, f, dept + 1, (path ? path + '.' : '') + i + '.' + child.tagName); - out = out.concat(kids); - } - }); - return out; -} - -function genNode(node, level) -{ - let code = ""; - for(let i=0;i\n`; - return code; - } - else - { - code += ">\n"; - } - - for (let child of children) - { - code += genNode(child, level+1); - } - - for(let i=0;i\n`; - - return code; -} - -function genXML(nodes) -{ - let xml = ""; - for (let top of nodes) - { - if (top.tagName =="?xml") - { - let version = top.attributes.version; - xml += `\n`; - } - else - { - xml += genNode(top, 0); - } - - } - return xml; - -} - -function uuid(len, radix) { - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); - var uuid = [], i; - radix = radix || chars.length; - - if (len) { - // Compact form - for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix]; - } else { - // rfc4122, version 4 form - var r; - - // rfc4122 requires these characters - uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; - uuid[14] = '4'; - - // Fill in random data. At i==19 set the high bits of clock sequence as - // per rfc4122, sec. 4.1.5 - for (i = 0; i < 36; i++) { - if (!uuid[i]) { - r = 0 | Math.random()*16; - uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; - } - } - } - - return uuid.join(''); -} - -function string_to_boolean(string) { - switch (string.toLowerCase().trim()) { - case "true": - case "yes": - case "1": - return true; - - case "false": - case "no": - case "0": - case null: - return false; - - default: - return Boolean(string); - } -} - -class LightmapBaker -{ - constructor(doc, iterations, num_rays) - { - this.doc = doc; - this.lst = []; - for (let obj of doc.bakables) - { - let xml_node = doc.internal_index[obj.uuid].xml_node; - let attributes = xml_node.attributes; - if ("lightmap" in attributes) - { - let filename = attributes.lightmap; - let ext = filename.split('.').pop().toLowerCase(); - if (ext=='hdr') - { - this.lst.push({ model: obj, lightmap: filename, count: -1 }); - } - } - } - if (this.lst.length<1) - { - print("No bakable object found!"); - return; - } - - this.iterations = iterations; - this.num_rays_final = num_rays; - this.iter = 0; - this.idx_model = 0; - this.idx_texel = 0; - this.check_time = now(); - } - - render(renderer) - { - if (this.lst.length<1) - { - this.doc.lightmap_bake = null; - return; - } - - let frame_time = now(); - - while(this.doc.lightmap_bake != null) - { - let cur_time = now(); - if (cur_time -frame_time>=10) break; - - let item = this.lst[this.idx_model]; - if (item.count<0) - { - item.count = item.model.initializeLightmap(renderer); - } - - if (cur_time - this.check_time>=500) - { - print(`Building LOD Probe-Grid, iteration: ${this.iter+1}/${this.iterations}, model: ${this.idx_model+1}/${this.lst.length}, texel: ${this.idx_texel +1}/${item.count}`); - this.check_time = cur_time; - } - - let num_rays = (this.num_rays_final >> (this.iterations - this.iter)); - if (num_rays < 1) num_rays = 1; - let count_texels = renderer.updateLightmap(this.doc.scene, item.model, this.idx_texel, num_rays, 1.0); - this.idx_texel += count_texels; - if (this.idx_texel>=item.count) - { - renderer.filterLightmap(item.model); - this.idx_texel = 0; - this.idx_model++; - if (this.idx_model >= this.lst.length) - { - this.idx_model = 0; - this.iter++; - if (this.iter >= this.iterations) - { - this.doc.lightmap_bake = null; - print("Saving lightmaps."); - for (let item of this.lst) - { - let hdr_image = item.model.getLightmap(); - let res = HDRImageSaver.saveFile(hdr_image, item.lightmap); - if (!res) - { - print(`Failed to save ${item.lightmap}`); - } - } - - } - - } - - } - } - - } -} - -class EnvMapGen -{ - constructor(doc, proxy, xml_node, irradiance_only = false) - { - this.doc = doc; - this.xml_node = xml_node; - this.irradiance_only = irradiance_only; - - this.cube_target = new CubeRenderTarget(128,128); - this.envMapCreator = new EnvironmentMapCreator(); - this.iter = 0; - } - - render(renderer) - { - print(`Building environemnt map, iteration: ${this.iter}`); - let props = this.xml_node.attributes; - - let x = 0.0; - let y = 0.0; - let z = 0.0; - if ("probe_position" in props) - { - let probe_position = props.probe_position; - let position = probe_position.split(','); - x = parseFloat(position[0]); - y = parseFloat(position[1]); - z = parseFloat(position[2]); - } - - renderer.renderCube(this.doc.scene, this.cube_target, new Vector3(x, y,z)); - - let envLight = this.envMapCreator.create(this.cube_target, this.irradiance_only); - if (props.hasOwnProperty('dynamic_map')) - { - envLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - this.doc.scene.indirectLight = envLight; - - this.iter++; - if (this.iter > 5) - { - print("Saving environemnt map."); - if (this.irradiance_only) - { - let path_sh = "assets/sh.json"; - if (props.hasOwnProperty('path_sh')) - { - path_sh = props.path_sh; - } - - let text = JSON.stringify(envLight.shCoefficients); - let res = fileSaver.saveTextFile(path_sh, text); - - if (!res) - { - print("Failed to save enviroment map."); - } - } - else - { - let url = "assets/textures"; - let posx = "env_face0.jpg"; - let negx = "env_face1.jpg"; - let posy = "env_face2.jpg"; - let negy = "env_face3.jpg"; - let posz = "env_face4.jpg"; - let negz = "env_face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - if (posx.split('.').pop()=="hdr") - { - let down_img = this.cube_target.getHDRCubeImage(); - - let res = HDRImageSaver.saveCubeToFile(down_img, - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - if (!res) - { - print("Failed to save enviroment map."); - } - - } - else - { - let down_img = this.cube_target.getCubeImage(); - - let res = imageSaver.saveCubeToFile(down_img, - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - if (!res) - { - print("Failed to save enviroment map."); - } - } - } - - this.doc.env_gen = null; - } - } - -} - -class GPUProbeGridBaker -{ - constructor(doc, proxy, xml_node, iterations, num_rays) - { - this.doc = doc; - this.xml_node = xml_node; - - this.probe_grid = new ProbeGrid(); - this.probe_grid.setDivisions(proxy.divisions); - this.probe_grid.setCoverageMin(proxy.coverageMin); - this.probe_grid.setCoverageMax(proxy.coverageMax); - this.probe_grid.ypower = proxy.ypower; - - print("Constructing visibility information..."); - this.probe_grid.constructVisibility(doc.scene); - - let props = this.xml_node.attributes; - if (props.hasOwnProperty('dynamic_map')) - { - this.probe_grid.dynamicMap = string_to_boolean(props.dynamic_map); - } - if (props.hasOwnProperty('normal_bias')) - { - this.probe_grid.normalBias = parseFloat(props.normal_bias); - } - if (props.hasOwnProperty('per_primitive')) - { - this.probe_grid.perPrimitive = string_to_boolean(props.per_primitive); - } - this.doc.scene.indirectLight = this.probe_grid; - - let divisions = this.probe_grid.divisions; - this.probe_count = divisions.x*divisions.y*divisions.z; - - this.probe_idx = 0; - this.iterations = iterations; - this.num_rays_final = num_rays; - this.iter = 0; - this.check_time = now(); - } - - render(renderer) - { - let frame_time = now(); - - if (frame_time - this.check_time>=500) - { - print(`Building probe-grid, iteration: ${this.iter+1}/${this.iterations}, probe: ${this.probe_idx +1}/${this.probe_count}`); - this.check_time = frame_time; - } - - while(now()-frame_time<10) - { - if (this.doc.probe_grid_bake == null) break; - let num_rays = (this.num_rays_final >> (this.iterations - this.iter)); - let num_probes = renderer.updateProbes(this.doc.scene, this.probe_grid, this.probe_idx, num_rays, 0.5, 1.0); - this.probe_idx += num_probes; - if (this.probe_idx>=this.probe_count) - { - this.probe_idx = 0; - this.iter++; - - if (this.iter >= this.iterations) - { - print("Saving probe-grid."); - let props = this.xml_node.attributes; - let probe_data = "assets/probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let res = probeGridSaver.saveFile(this.probe_grid, probe_data); - if (!res) - { - print("Failed to save probe-grid."); - } - this.doc.probe_grid_bake = null; - } - } - } - } -} - -class GPULODProbeGridBaker -{ - constructor(doc, proxy, xml_node, iterations, num_rays) - { - this.doc = doc; - this.xml_node = xml_node; - - this.cube_target = new CubeRenderTarget(64,64); - this.probe_grid = this.doc.scene.indirectLight; - - print("Constructing visibility information..."); - this.probe_grid.constructVisibility(doc.scene); - - this.probe_count = this.probe_grid.numberOfProbes; - this.probe_idx = 0; - - this.iterations = iterations; - this.num_rays_final = num_rays; - this.iter = 0; - this.check_time = now(); - - } - - render(renderer) - { - let frame_time = now(); - - if (frame_time - this.check_time>=500) - { - print(`Building LOD Probe-Grid, iteration: ${this.iter+1}/${this.iterations}, probe: ${this.probe_idx +1}/${this.probe_count}`); - this.check_time = frame_time; - } - - while(now()-frame_time<10) - { - if (this.doc.lod_probe_grid_bake == null) break; - let num_rays = (this.num_rays_final >> (this.iterations - this.iter)); - let num_probes = renderer.updateProbes(this.doc.scene, this.probe_grid, this.probe_idx, num_rays, 0.5, 1.0); - this.probe_idx += num_probes; - if (this.probe_idx>=this.probe_count) - { - this.probe_idx = 0; - this.iter++; - - if (this.iter >= this.iterations) - { - print("Saving probe-grid."); - let props = this.xml_node.attributes; - let probe_data = "assets/lod_probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let res = LODProbeGridSaver.saveFile(this.probe_grid, probe_data); - if (!res) - { - print("Failed to save probe-grid."); - } - this.doc.lod_probe_grid_bake = null; - } - } - } - - } - -} - -// Tags -const create_default_controls = (doc)=>{ - if (doc.controls) - doc.controls.dispose(); - doc.controls = new OrbitControls(doc.camera, doc.view); - doc.controls.enableDamping = true; - doc.controls.target.set(0, 1.5, 0); -}; - -const create_default_sky = (doc)=>{ - let bg = new HemisphereBackground(); - bg.setSkyColor(0.318, 0.318, 0.318); - bg.setGroundColor(0.01, 0.025, 0.025); - doc.scene.background = bg; -}; - -const create_default_env_light = (doc) =>{ - let envLight = new HemisphereLight(); - envLight.setSkyColor(0.318, 0.318, 0.318); - envLight.setGroundColor(0.01, 0.025, 0.025); - doc.scene.indirectLight = envLight; -}; - -const scene = { - reset: (doc) => { - doc.scene = new Scene(); - }, - create: (doc, props, mode, parent) => { - doc.scene = new Scene(); - create_default_sky(doc); - create_default_env_light(doc); - return doc.scene; - }, - generate: (doc, obj, input) =>{ - generate_lightmap(doc, input); - } -}; - -const camera = { - reset: (doc) => { - doc.camera = new PerspectiveCamera(45, doc.width / doc.height, 0.1, 100); - doc.camera.setPosition(0, 1.5, 5.0); - }, - - create: (doc, props, mode, parent) => { - let fov = 50.0; - let near = 0.1; - let far = 200.0; - if (props.hasOwnProperty("fov")) - { - fov = parseFloat(props.fov); - } - if (props.hasOwnProperty("near")) - { - near = parseFloat(props.near); - } - if (props.hasOwnProperty("far")) - { - far = parseFloat(props.far); - } - doc.camera = new PerspectiveCamera(fov, doc.width / doc.height, near, far); - create_default_controls(doc); - return doc.camera; - }, - - remove: (doc, obj) => { - camera.reset(doc); - create_default_controls(doc); - } -}; - -const control = { - reset: (doc) => { - create_default_controls(doc); - }, - create: (doc, props, mode, parent) =>{ - let type = 'orbit'; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == 'orbit') - { - let from_x = 0.0; - let from_y = 1.5; - let from_z = 5.0; - if (props.hasOwnProperty("look_from")) - { - let look_from = props.look_from.split(','); - from_x = parseFloat(look_from[0]); - from_y = parseFloat(look_from[1]); - from_z = parseFloat(look_from[2]); - } - - let to_x = 0.0; - let to_y = 1.5; - let to_z = 0.0; - if (props.hasOwnProperty("look_at")) - { - let look_at = props.look_at.split(','); - to_x = parseFloat(look_at[0]); - to_y = parseFloat(look_at[1]); - to_z = parseFloat(look_at[2]); - } - - doc.camera.setPosition(from_x, from_y, from_z); - if (doc.controls != null) - doc.controls.dispose(); - doc.controls = new OrbitControls(doc.camera, doc.view); - doc.controls.enableDamping = true; - doc.controls.target.set(to_x, to_y, to_z); - } - return doc.controls; - }, - remove: (doc, obj) => { - create_default_controls(doc); - } - -}; - -const fog = { - create: (doc, props, mode, parent) =>{ - doc.scene.fog = new Fog(); - if (props.hasOwnProperty("density")) - { - doc.scene.fog.density = parseFloat(props.density); - } - return doc.scene.fog; - }, - tuning: (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("density" in input) - { - let density = input.density; - props.density = density; - obj.density = parseFloat(density); - } - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - return ""; - }, - remove: (doc, fog) => { - doc.scene.fog = null; - } -}; - -const create_uniform_sky = (doc, props) => { - let bg = new ColorBackground(); - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setColor(r,g,b); - } - doc.scene.background = bg; - return bg; -}; - -const create_hemisphere_sky = (doc, props)=>{ - let bg = new HemisphereBackground(); - - if (props.hasOwnProperty('skyColor')) - { - const color = props.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setSkyColor(r,g,b); - } - - if (props.hasOwnProperty('groundColor')) - { - const color = props.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setGroundColor(r,g,b); - - } - - doc.scene.background = bg; - return bg; -}; - -const create_cube_sky = (doc, props)=>{ - let bg = new CubeBackground(); - - let url = "assets/textures"; - let posx = "face0.jpg"; - let negx = "face1.jpg"; - let posy = "face2.jpg"; - let negy = "face3.jpg"; - let posz = "face4.jpg"; - let negz = "face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - if (cube_img!=null) - { - bg.setCubemap(cube_img); - } - doc.scene.background = bg; - - return bg; -}; - -const create_background_scene = (doc, props)=>{ - let path_scene = "terrain.xml"; - if (props.hasOwnProperty('scene')) - { - path_scene = props.scene; - } - - let near = 10.0; - let far = 10000.0; - if (props.hasOwnProperty('near')) - { - near = parseFloat(props.near); - } - if (props.hasOwnProperty('far')) - { - far = parseFloat(props.far); - } - - let bg_doc = new BackgroundDocument(near, far); - bg_doc.load_local_xml(path_scene); - doc.scene.background = bg_doc; - - return bg_doc; -}; - -const tuning_uniform_sky = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } -}; - -const tuning_hemisphere_sky = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("skyColor" in input) - { - props.skyColor = input.skyColor; - const color = input.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setSkyColor(r,g,b); - } - - if ("groundColor" in input) - { - props.groundColor = input.groundColor; - const color = input.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setGroundColor(r,g,b); - } -}; - -const tuning_cube_sky = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - let reload = false; - if ("path" in input) - { - props.path = input.path; - reload = true; - } - if ("posx" in input) - { - props.posx = input.posx; - reload = true; - } - if ("negx" in input) - { - props.negx = input.negx; - reload = true; - } - if ("posy" in input) - { - props.posy = input.posy; - reload = true; - } - if ("negy" in input) - { - props.negy = input.negy; - reload = true; - } - if ("posz" in input) - { - props.posz = input.posz; - reload = true; - } - if ("negz" in input) - { - props.negz = input.negz; - reload = true; - } - if (reload) - { - const url = props.path; - - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+props.posx, url+"/"+props.negx, - url+"/"+props.posy, url+"/"+props.negy, - url+"/"+props.posz, url+"/"+props.negz); - - obj.setCubemap(cube_img); - } -}; - -const tuning_background_scene = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("scene" in input) - { - props.scene = input.scene; - obj.load_local_xml(input.scene); - } - if ("near" in input) - { - props.near = input.near; - obj.near = parseFloat(input.near); - } - if ("far" in input) - { - props.far = input.far; - obj.far = parseFloat(input.far); - } -}; - -const sky = { - reset: (doc) => { - create_default_sky(doc); - }, - create: (doc, props, mode, parent) => { - let type = "hemisphere"; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == "uniform") - { - return create_uniform_sky(doc,props); - } - else if (type == "hemisphere") - { - return create_hemisphere_sky(doc,props); - } - else if (type == "cube") - { - return create_cube_sky(doc,props); - } - else if (type == "scene") - { - return create_background_scene(doc,props); - } - }, - remove: (doc, obj) => { - create_default_sky(doc); - }, - tuning: (doc, obj, input) => { - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - if (input.hasOwnProperty('type')) - { - node.attributes = {}; - node.attributes.type = input.type; - doc.external_index.index[key].attributes = node.attributes; - let obj_new = sky.create(doc, node.attributes, "local", doc.scene); - obj_new.uuid = key; - obj_new.tag = "sky"; - doc.internal_index[key].obj = obj_new; - return JSON.stringify(node.attributes); - } - else - { - let props = node.attributes; - let type = "hemisphere"; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == "uniform") - { - tuning_uniform_sky(doc, obj, input); - } - else if (type=="hemisphere") - { - tuning_hemisphere_sky(doc, obj, input); - } - else if (type=="cube") - { - tuning_cube_sky(doc, obj, input); - } - else if (type=="scene") - { - tuning_background_scene(doc, obj, input); - } - } - return "" - } -}; - -const create_uniform_env_light = (doc, props) => { - let envLight = new AmbientLight(); - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setColor(r,g,b); - } - doc.scene.indirectLight = envLight; - return envLight; -}; - -const create_hemisphere_env_light = (doc, props) => { - let envLight = new HemisphereLight(); - - if (props.hasOwnProperty('skyColor')) - { - const color = props.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setSkyColor(r,g,b); - } - - if (props.hasOwnProperty('groundColor')) - { - const color = props.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setGroundColor(r,g,b); - } - doc.scene.indirectLight = envLight; - return envLight; -}; - -const create_cube_env_light = (doc, props) => { - const proxy = new SimpleModel(); - proxy.createBox(0.3, 0.3, 0.3); - - if (props.hasOwnProperty('probe_position')) - { - const position = props.probe_position.split(','); - proxy.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - proxy.setColor(0.7,0.0,0.7); - doc.scene.addWidget(proxy); - - let irradiance_only = false; - if (props.hasOwnProperty('irradiance_only')) - { - irradiance_only = string_to_boolean(props.irradiance_only); - } - - if (irradiance_only) - { - let path_sh = "assets/sh.json"; - if (props.hasOwnProperty('path_sh')) - { - path_sh = props.path_sh; - } - - let envLight = new EnvironmentMap(); - let text = fileLoader.loadTextFile(path_sh); - if (text!=null) - { - envLight.shCoefficients = JSON.parse(text); - } - doc.scene.indirectLight = envLight; - } - else - { - let url = "assets/textures"; - let posx = "env_face0.jpg"; - let negx = "env_face1.jpg"; - let posy = "env_face2.jpg"; - let negy = "env_face3.jpg"; - let posz = "env_face4.jpg"; - let negz = "env_face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - if (posx.split('.').pop()=="hdr") - { - let cube_img = HDRImageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - doc.scene.indirectLight = envLight; - } - else - { - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - doc.scene.indirectLight = envLight; - } - } - - return proxy; -}; - -const create_probe_grid = (doc, props) => { - const proxy = new ProbeGridWidget(); - if (props.hasOwnProperty('divisions')) - { - const divisions = props.divisions.split(','); - proxy.setDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - if (props.hasOwnProperty('coverage_min')) - { - const coverage_min = props.coverage_min.split(','); - proxy.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - if (props.hasOwnProperty('coverage_max')) - { - const coverage_max = props.coverage_max.split(','); - proxy.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - if (props.hasOwnProperty('ypower')) - { - proxy.ypower = parseFloat(props.ypower); - } - doc.scene.addWidget(proxy); - - let probe_data = "assets/probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - - let probe_grid = probeGridLoader.loadFile(probe_data); - if (probe_grid == null) - { - probe_grid = new ProbeGrid(); - probe_grid.setDivisions(proxy.divisions); - probe_grid.setCoverageMin(proxy.coverageMin); - probe_grid.setCoverageMax(proxy.coverageMax); - probe_grid.ypower = proxy.ypower; - } - else - { - proxy.setDivisions(probe_grid.divisions); - proxy.setCoverageMin(probe_grid.coverageMin); - proxy.setCoverageMax(probe_grid.coverageMax); - proxy.ypower = probe_grid.ypower; - - props.divisions = `${probe_grid.divisions.x}, ${probe_grid.divisions.y}, ${probe_grid.divisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.ypower = `${probe_grid.ypower}`; - } - - if (props.hasOwnProperty('normal_bias')) - { - probe_grid.normalBias = parseFloat(props.normal_bias); - } - - if (props.hasOwnProperty('per_primitive')) - { - probe_grid.perPrimitive =string_to_boolean(props.per_primitive); - } - - doc.scene.indirectLight = probe_grid; - - return proxy; -}; - -const create_lod_probe_grid = (doc, props) => { - const proxy = new LODProbeGridWidget(); - if (props.hasOwnProperty('base_divisions')) - { - const divisions = props.base_divisions.split(','); - proxy.setBaseDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - if (props.hasOwnProperty('coverage_min')) - { - const coverage_min = props.coverage_min.split(','); - proxy.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - if (props.hasOwnProperty('coverage_max')) - { - const coverage_max = props.coverage_max.split(','); - proxy.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - proxy.subDivisionLevel = 2; - if (props.hasOwnProperty('sub_division_level')) - { - proxy.subDivisionLevel = parseInt(props.sub_division_level); - } - - doc.scene.addWidget(proxy); - - let probe_data = "assets/lod_probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - - let probe_grid = LODProbeGridLoader.loadFile(probe_data); - if (probe_grid == null) - { - probe_grid = new LODProbeGrid(); - probe_grid.setBaseDivisions(proxy.baseDivisions); - probe_grid.setCoverageMin(proxy.coverageMin); - probe_grid.setCoverageMax(proxy.coverageMax); - probe_grid.subDivisionLevel = proxy.subDivisionLevel; - } - else - { - proxy.setBaseDivisions(probe_grid.baseDivisions); - proxy.setCoverageMin(probe_grid.coverageMin); - proxy.setCoverageMax(probe_grid.coverageMax); - proxy.subDivisionLevel = probe_grid.subDivisionLevel; - - props.base_divisions = `${probe_grid.baseDivisions.x}, ${probe_grid.baseDivisions.y}, ${probe_grid.baseDivisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.sub_division_level = `${probe_grid.subDivisionLevel}`; - } - proxy.probeGrid = probe_grid; - - if (props.hasOwnProperty('normal_bias')) - { - probe_grid.normalBias = parseFloat(props.normal_bias); - } - - if (props.hasOwnProperty('per_primitive')) - { - probe_grid.perPrimitive =string_to_boolean(props.per_primitive); - } - - doc.scene.indirectLight = probe_grid; - - return proxy; -}; - -const tuning_ambient_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - return ""; -}; - - -const tuning_hemisphere_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("skyColor" in input) - { - props.skyColor = input.skyColor; - const color = input.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setSkyColor(r,g,b); - } - - if ("groundColor" in input) - { - props.groundColor = input.groundColor; - const color = input.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setGroundColor(r,g,b); - } - - return "" -}; - -const tuning_cube_env_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("probe_position" in input) - { - let probe_position = input.probe_position; - props.probe_position = probe_position; - let position = probe_position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - let reload = false; - - if ("irradiance_only" in input) - { - props.irradiance_only = input.irradiance_only; - reload = true; - } - - if ("path" in input) - { - props.path = input.path; - reload = true; - } - if ("posx" in input) - { - props.posx = input.posx; - reload = true; - } - if ("negx" in input) - { - props.negx = input.negx; - reload = true; - } - if ("posy" in input) - { - props.posy = input.posy; - reload = true; - } - if ("negy" in input) - { - props.negy = input.negy; - reload = true; - } - if ("posz" in input) - { - props.posz = input.posz; - reload = true; - } - if ("negz" in input) - { - props.negz = input.negz; - reload = true; - } - - if ("path_sh" in input) - { - props.path_sh = input.path_sh; - reload = true; - } - - if (reload) - { - let irradiance_only = false; - if (props.hasOwnProperty('irradiance_only')) - { - irradiance_only = string_to_boolean(props.irradiance_only); - } - - if (irradiance_only ) - { - let path_sh = "assets/sh.json"; - if (props.hasOwnProperty('path_sh')) - { - path_sh = props.path_sh; - } - - let envLight = new EnvironmentMap(); - let text = fileLoader.loadTextFile(path_sh); - if (text!=null) - { - envLight.shCoefficients = JSON.parse(text); - } - doc.scene.indirectLight = envLight; - } - else - { - let url = "assets/textures"; - let posx = "env_face0.jpg"; - let negx = "env_face1.jpg"; - let posy = "env_face2.jpg"; - let negy = "env_face3.jpg"; - let posz = "env_face4.jpg"; - let negz = "env_face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - if (posx.split('.').pop()=="hdr") - { - let cube_img = HDRImageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - - if (props.hasOwnProperty('dynamic_map')) - { - envLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = envLight; - } - else - { - - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - - if (props.hasOwnProperty('dynamic_map')) - { - envLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = envLight; - } - } - } - return ""; -}; - -const tuning_probe_grid = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("probe_data" in input) - { - props.probe_data = input.probe_data; - - let probe_grid = probeGridLoader.loadFile(input.probe_data); - if (probe_grid == null) - { - probe_grid = new ProbeGrid(); - probe_grid.setDivisions(obj.divisions); - probe_grid.setCoverageMin(obj.coverageMin); - probe_grid.setCoverageMax(obj.coverageMax); - probe_grid.ypower = obj.ypower; - } - else - { - obj.setDivisions(probe_grid.divisions); - obj.setCoverageMin(probe_grid.coverageMin); - obj.setCoverageMax(probe_grid.coverageMax); - obj.ypower = probe_grid.ypower; - - props.divisions = `${probe_grid.divisions.x}, ${probe_grid.divisions.y}, ${probe_grid.divisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.ypower = `${probe_grid.ypower}`; - } - - if (props.hasOwnProperty('dynamic_map')) - { - probe_grid.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = probe_grid; - - return JSON.stringify(props); - } - - if ("divisions" in input) - { - props.divisions = input.divisions; - let divisions = input.divisions.split(','); - obj.setDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - - if ("coverage_min" in input) - { - props.coverage_min = input.coverage_min; - let coverage_min = input.coverage_min.split(','); - obj.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - - if ("coverage_max" in input) - { - props.coverage_max = input.coverage_max; - let coverage_max = input.coverage_max.split(','); - obj.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - - if ("ypower" in input) - { - props.ypower = input.ypower; - obj.ypower = parseFloat(input.ypower); - } - - if ("normal_bias" in input) - { - props.normal_bias = input.normal_bias; - doc.scene.indirectLight.normalBias = parseFloat(input.normal_bias); - } - - if ("per_primitive" in input) - { - props.per_primitive = input.per_primitive; - doc.scene.indirectLight.perPrimitive =string_to_boolean(input.per_primitive); - } - - if ("auto_area" in input) - { - let aabb = doc.scene.getBoundingBox(); - let minPos = aabb.minPos; - let maxPos = aabb.maxPos; - let size_x = maxPos.x - minPos.x; - let size_y = maxPos.y - minPos.y; - let size_z = maxPos.z - minPos.z; - let div_x = Math.ceil(size_x); if (div_x<2) div_x = 2; - let div_y = Math.ceil(size_y); if (div_y<2) div_y = 2; - let div_z = Math.ceil(size_z); if (div_z<2) div_z = 2; - obj.setDivisions(div_x, div_y, div_z); - obj.setCoverageMin(minPos); - obj.setCoverageMax(maxPos); - props.divisions = `${div_x}, ${div_y}, ${div_z}`; - props.coverage_min = `${minPos.x}, ${minPos.y}, ${minPos.z}`; - props.coverage_max = `${maxPos.x}, ${maxPos.y}, ${maxPos.z}`; - let ret = { divisions: props.divisions, coverage_min: props.coverage_min, coverage_max: props.coverage_max }; - return JSON.stringify(ret); - } - - return ""; - -}; - -const tuning_lod_probe_grid = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("probe_data" in input) - { - props.probe_data = input.probe_data; - - let probe_grid = LODProbeGridLoader.loadFile(input.probe_data); - if (probe_grid == null) - { - probe_grid = new LODProbeGrid(); - probe_grid.setBaseDivisions(obj.baseDivisions); - probe_grid.setCoverageMin(obj.coverageMin); - probe_grid.setCoverageMax(obj.coverageMax); - probe_grid.subDivisionLevel = obj.subDivisionLevel; - } - else - { - obj.setBaseDivisions(probe_grid.baseDivisions); - obj.setCoverageMin(probe_grid.coverageMin); - obj.setCoverageMax(probe_grid.coverageMax); - obj.subDivisionLevel = probe_grid.subDivisionLevel; - - props.base_divisions = `${probe_grid.baseDivisions.x}, ${probe_grid.baseDivisions.y}, ${probe_grid.baseDivisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.sub_division_level = `${probe_grid.subDivisionLevel}`; - } - obj.probeGrid = probe_grid; - - if (props.hasOwnProperty('dynamic_map')) - { - probe_grid.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = probe_grid; - - return JSON.stringify(props); - } - - if ("base_divisions" in input) - { - props.base_divisions = input.base_divisions; - let divisions = input.base_divisions.split(','); - obj.setBaseDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - - if ("coverage_min" in input) - { - props.coverage_min = input.coverage_min; - let coverage_min = input.coverage_min.split(','); - obj.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - - if ("coverage_max" in input) - { - props.coverage_max = input.coverage_max; - let coverage_max = input.coverage_max.split(','); - obj.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - - if ("sub_division_level" in input) - { - props.sub_division_level = input.sub_division_level; - obj.subDivisionLevel = parseInt(input.sub_division_level); - } - - if ("normal_bias" in input) - { - props.normal_bias = input.normal_bias; - obj.probeGrid.normalBias = parseFloat(input.normal_bias); - } - - if ("per_primitive" in input) - { - props.per_primitive = input.per_primitive; - obj.probeGrid.perPrimitive =string_to_boolean(input.per_primitive); - } - - if ("auto_area" in input) - { - let aabb = doc.scene.getBoundingBox(); - let minPos = aabb.minPos; - let maxPos = aabb.maxPos; - let size_x = maxPos.x - minPos.x; - let size_y = maxPos.y - minPos.y; - let size_z = maxPos.z - minPos.z; - let div_x = Math.ceil(size_x / 4); if (div_x<2) div_x = 2; - let div_y = Math.ceil(size_y / 4); if (div_y<2) div_y = 2; - let div_z = Math.ceil(size_z / 4); if (div_z<2) div_z = 2; - obj.setBaseDivisions(div_x, div_y, div_z); - obj.setCoverageMin(minPos); - obj.setCoverageMax(maxPos); - obj.subDivisionLevel = 2; - props.base_divisions = `${div_x}, ${div_y}, ${div_z}`; - props.coverage_min = `${minPos.x}, ${minPos.y}, ${minPos.z}`; - props.coverage_max = `${maxPos.x}, ${maxPos.y}, ${maxPos.z}`; - props.sub_division_level = "2"; - let ret = { base_divisions: props.base_divisions, coverage_min: props.coverage_min, coverage_max: props.coverage_max, sub_division_level: "2" }; - return JSON.stringify(ret); - } - - return ""; - -}; - -const initialize_lod_probe_grid = (doc, obj, input) =>{ - let probe_grid = obj.probeGrid; - - doc.lod_probe_grid_bake = null; - probe_grid.setBaseDivisions(obj.baseDivisions); - probe_grid.setCoverageMin(obj.coverageMin); - probe_grid.setCoverageMax(obj.coverageMax); - probe_grid.subDivisionLevel = obj.subDivisionLevel; - probe_grid.initialize(doc.renderer, doc.scene); - return probe_grid.numberOfProbes; -}; - - -const generate_lightmap = (doc, input) =>{ - let iterations = parseInt(input.iterations); - let num_rays = parseInt(input.num_rays); - doc.lightmap_bake = new LightmapBaker(doc, iterations, num_rays); -}; - -const generate_cube_env_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - let irradiance_only = false; - if (props.hasOwnProperty('irradiance_only')) - { - irradiance_only = string_to_boolean(props.irradiance_only); - } - - if (!irradiance_only) - { - props.path = input.path; - props.posx = input.posx; - props.negx = input.negx; - props.posy = input.posy; - props.negy = input.negy; - props.posz = input.posz; - props.negz = input.negz; - } - doc.env_gen = new EnvMapGen(doc, obj, node, irradiance_only); -}; - -const generate_probe_grid = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let iterations = parseInt(input.iterations); - let num_rays = parseInt(input.num_rays); - doc.probe_grid_bake = new GPUProbeGridBaker(doc, obj, node, iterations, num_rays); -}; - - -const generate_lod_probe_grid = (doc, obj, input) =>{ - initialize_lod_probe_grid(doc, obj); - let node = doc.internal_index[obj.uuid].xml_node; - let iterations = parseInt(input.iterations); - let num_rays = parseInt(input.num_rays); - doc.lod_probe_grid_bake = new GPULODProbeGridBaker(doc, obj, node, iterations, num_rays); -}; - -const env_light = { - reset: (doc) => { - create_default_env_light(doc); - }, - create: (doc, props, mode, parent) => { - let type = "hemisphere"; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - - let ret = null; - - if (type == "uniform") - { - ret = create_uniform_env_light(doc,props); - } - else if (type == "hemisphere") - { - ret = create_hemisphere_env_light(doc,props); - } - else if (type == "cube") - { - ret = create_cube_env_light(doc,props); - } - else if (type == "probe_grid") - { - ret = create_probe_grid(doc, props); - } - else if (type == "lod_probe_grid") - { - ret = create_lod_probe_grid(doc, props); - } - - if (props.hasOwnProperty('dynamic_map')) - { - doc.scene.indirectLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - return ret; - }, - remove: (doc, obj) => { - create_default_env_light(doc); - - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - let props = node.attributes; - let type = "hemisphere"; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - - if (type == "cube" || type =="probe_grid" || type == "lod_probe_grid") - { - doc.scene.removeWidget(obj); - } - - }, - - tuning: (doc, obj, input) => { - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - if (input.hasOwnProperty('type')) - { - doc.remove(obj); - node.attributes = {}; - node.attributes.type = input.type; - doc.external_index.index[key].attributes = node.attributes; - let obj_new = env_light.create(doc, node.attributes, "local", doc.scene); - obj_new.uuid = key; - obj_new.tag = "env_light"; - doc.internal_index[key].obj = obj_new; - return JSON.stringify(node.attributes); - } - else - { - let props = node.attributes; - - if (input.hasOwnProperty('dynamic_map')) - { - props.dynamic_map = input.dynamic_map; - doc.scene.indirectLight.dynamicMap = string_to_boolean(input.dynamic_map); - return "" - } - - let type = "hemisphere"; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == "uniform") - { - return tuning_ambient_light(doc, obj, input); - } - else if (type=="hemisphere") - { - return tuning_hemisphere_light(doc, obj, input); - } - else if (type=="cube") - { - return tuning_cube_env_light(doc,obj,input); - } - else if (type == "probe_grid") - { - return tuning_probe_grid(doc,obj,input); - } - else if (type == "lod_probe_grid") - { - return tuning_lod_probe_grid(doc,obj,input); - } - } - - }, - - initialize: (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if (props.type == "lod_probe_grid") - { - return initialize_lod_probe_grid(doc,obj); - } - return ""; - }, - - generate: (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if (props.type == "cube") - { - generate_cube_env_light(doc,obj,input); - } - else if (props.type == "probe_grid") - { - generate_probe_grid(doc,obj,input); - } - else if (props.type == "lod_probe_grid") - { - generate_lod_probe_grid(doc,obj,input); - } - } - -}; - - -const tuning_object3d = (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("name" in input) - { - props.name = input.name; - obj.name = input.name; - } - if ("position" in input) - { - props.position = input.position; - let position = input.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - if ("rotation" in input) - { - props.rotation = input.rotation; - let rotation = input.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - if ("scale" in input) - { - props.scale = input.scale; - let scale = input.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - if ('is_building' in input) - { - props.is_building = input.is_building; - obj.isBuilding = string_to_boolean(input.is_building); - } -}; - -const tuning_material = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if ("texture" in input) - { - props.texture = input.texture; - let img = imageLoader.loadFile(input.texture); - obj.setColorTexture(img); - } - - if ("metalness" in input) - { - let metalness = input.metalness; - props.metalness = metalness; - obj.metalness = parseFloat(metalness); - } - - if ("roughness" in input) - { - let roughness = input.roughness; - props.roughness = roughness; - obj.roughness = parseFloat(roughness); - } -}; - -const group = { - create: (doc, props, mode, parent) => { - const group = new Object3D(); - if (parent != null) { - parent.add(group); - } - else { - doc.scene.add(group); - } - return group; - }, - - tuning: (doc, obj, input) => { - tuning_object3d(doc, obj, input); - return ""; - } -}; - -const plane = { - create: (doc, props, mode, parent) => { - let width = 1.0; - let height = 1.0; - if (props.hasOwnProperty('size')) - { - let size = props.size.split(','); - width = parseFloat(size[0]); - height = parseFloat(size[1]); - } - - const plane = new SimpleModel(); - plane.createPlane(width, height); - - if (parent != null) { - parent.add(plane); - } - else { - doc.scene.add(plane); - } - return plane; - }, - - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("size" in input) - { - props.size = input.size; - let size = input.size.split(','); - let width = parseFloat(size[0]); - let height = parseFloat(size[1]); - obj.createPlane(width, height); - } - tuning_object3d(doc, obj, input); - tuning_material(doc, obj, input); - return ""; - } -}; - - -const box = { - create: (doc, props, mode, parent) => { - let width = 1.0; - let height = 1.0; - let depth = 1.0; - if (props.hasOwnProperty('size')) - { - let size = props.size.split(','); - width = parseFloat(size[0]); - height = parseFloat(size[1]); - depth = parseFloat(size[2]); - } - - const box = new SimpleModel(); - box.createBox(width, height, depth); - - if (parent != null) { - parent.add(box); - } - else { - doc.scene.add(box); - } - return box; - }, - - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("size" in input) - { - props.size = input.size; - let size = input.size.split(','); - let width = parseFloat(size[0]); - let height = parseFloat(size[1]); - let depth = parseFloat(size[2]); - obj.createBox(width, height, depth); - } - tuning_object3d(doc, obj, input); - tuning_material(doc, obj, input); - return ""; - } -}; - -const sphere = { - create: (doc, props, mode, parent) => { - let radius = 1.0; - if (props.hasOwnProperty('radius')) - { - radius = parseFloat(props.radius); - } - let widthSegments = 32; - if (props.hasOwnProperty('widthSegments')) - { - widthSegments = parseInt(props.widthSegments); - } - let heightSegments = 16; - if (props.hasOwnProperty('heightSegments')) - { - heightSegments = parseInt(props.heightSegments); - } - - const sphere = new SimpleModel(); - sphere.createSphere(radius, widthSegments, heightSegments); - - if (parent != null) { - parent.add(sphere); - } - else { - doc.scene.add(sphere); - } - return sphere; - }, - - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - let to_create = false; - - let radius = 1.0; - if ("radius" in input) - { - props.radius = input.radius; - radius = parseFloat(input.radius); - to_create = true; - } - - let widthSegments = 32; - if ("widthSegments" in input) - { - props.widthSegments = input.widthSegments; - widthSegments = parseInt(input.widthSegments); - to_create = true; - } - - let heightSegments = 16; - if ("heightSegments" in input) - { - props.heightSegments = input.heightSegments; - heightSegments = parseInt(input.heightSegments); - to_create = true; - } - - if (to_create) - { - obj.createSphere(radius, widthSegments, heightSegments); - } - - tuning_object3d(doc, obj, input); - tuning_material(doc, obj, input); - return ""; - } -}; - -const model = { - create: (doc, props, mode, parent) => { - let url = "assets/models/model.glb"; - if (props.hasOwnProperty('src')) - { - url = props.src; - } - let model = gltfLoader.loadModelFromFile(url); - if (model == null) - { - model= new SimpleModel(); - model.createBox(0.5, 1.5, 0.5); - model.setColor(0.7,0.0,0.7); - } - else - { - if (props.hasOwnProperty('is_building') && string_to_boolean(props.is_building)) - { - model.batchPrimitives(); - } - - if (model.isBakable) - { - doc.bakables.push(model); - - if (props.hasOwnProperty('lightmap')) - { - let filename = props.lightmap; - let ext = filename.split('.').pop().toLowerCase(); - if (ext=="hdr") - { - let hdr_img = HDRImageLoader.loadFile(filename); - if (hdr_img!=null) - { - model.setLightmap(hdr_img); - } - } - else if (ext=="dds") - { - let dds_img = DDSImageLoader.loadFile(filename); - if (dds_img!=null) - { - model.setLightmap(dds_img); - } - } - else if (ext=="png" || ext == "webp") - { - let img = imageLoader.loadFile(filename); - if (img!=null) - { - let hdr_img = HDRImageLoader.fromRGBM(img); - model.setLightmap(hdr_img); - } - } - else if (ext=="csv") - { - let text = fileLoader.loadTextFile(filename); - if (text!=null) - { - let path = filename.match(/(.*)[\/\\]/)[1]||''; - let images = []; - let ranges = []; - let lines = text.split(/\r?\n/); - for(let line of lines) - { - let fields = line.split(","); - if (fields.length<7) continue; - let fn_img = fields[0]; - let img = imageLoader.loadFile(path + "/" + fn_img); - if (img == null) continue; - let low = new Vector3(parseFloat(fields[1]), parseFloat(fields[2]), parseFloat(fields[3])); - let high = new Vector3(parseFloat(fields[4]), parseFloat(fields[5]), parseFloat(fields[6])); - images.push(img); - ranges.push({low, high}); - } - let hdr_img = HDRImageLoader.fromImages(images, ranges); - model.setLightmap(hdr_img); - } - } - } - } - } - - - if (parent != null) { - parent.add(model); - } - else { - doc.scene.add(model); - } - return model; - }, - - tuning: (doc, obj, input) => { - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - let props = node.attributes; - if (input.hasOwnProperty('src')) - { - doc.remove(obj); - props.src = input.src; - let obj_new = model.create(doc, props, "local", obj.parent); - obj_new.uuid = key; - obj_new.tag = "model"; - - if (props.hasOwnProperty('name')) - { - obj_new.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj_new.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj_new.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj_new.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - obj_new.setToonShading(16, 5.0, new Vector3(1.0, 1.0, 0.2)); - - doc.internal_index[key].obj = obj_new; - } - else - { - if ("is_building" in input) - { - props.is_building = input.is_building; - if (string_to_boolean(props.is_building)) - { - obj.batchPrimitives(); - } - } - - if ("lightmap" in input) - { - props.lightmap = input.lightmap; - if (obj.isBakable) - { - let filename = input.lightmap; - let ext = filename.split('.').pop().toLowerCase(); - if (ext=="hdr") - { - let hdr_img = HDRImageLoader.loadFile(filename); - if (hdr_img!=null) - { - obj.setLightmap(hdr_img); - } - } - else if (ext=="dds") - { - let dds_img = DDSImageLoader.loadFile(filename); - if (dds_img!=null) - { - obj.setLightmap(dds_img); - } - } - else if (ext=="png" || ext == "webp") - { - let img = imageLoader.loadFile(filename); - if (img!=null) - { - let hdr_img = HDRImageLoader.fromRGBM(img); - obj.setLightmap(hdr_img); - } - } - else if (ext=="csv") - { - let text = fileLoader.loadTextFile(filename); - if (text!=null) - { - let path = filename.match(/(.*)[\/\\]/)[1]||''; - let images = []; - let ranges = []; - let lines = text.split(/\r?\n/); - for(let line of lines) - { - let fields = line.split(","); - if (fields.length<7) continue; - let fn_img = fields[0]; - let img = imageLoader.loadFile(path + "/" + fn_img); - if (img == null) continue; - let low = new Vector3(parseFloat(fields[1]), parseFloat(fields[2]), parseFloat(fields[3])); - let high = new Vector3(parseFloat(fields[4]), parseFloat(fields[5]), parseFloat(fields[6])); - images.push(img); - ranges.push({low, high}); - } - let hdr_img = HDRImageLoader.fromImages(images, ranges); - obj.setLightmap(hdr_img); - } - } - } - - } - tuning_object3d(doc, obj, input); - } - return ""; - }, - - generate: (doc, obj, input) =>{ - if (doc.renderer.compressLightmap(doc.scene, obj)) - { - doc.renderer.decompressLightmap(doc.scene, obj); - } - } -}; - -const avatar = { - create: (doc, props, mode, parent) => { - let avatar = model.create(doc, { ...props}, mode, parent); - return avatar; - }, - - tuning: (doc, obj, input) => { - model.tuning(doc,obj,input); - return ""; - } -}; - - -const directional_light = { - create: (doc, props, mode, parent) => { - const light = new DirectionalLight(); - - if (props.hasOwnProperty('intensity')) { - light.intensity = parseFloat(props.intensity); - } - - if (props.hasOwnProperty('target')){ - let target = doc.scene.getObjectByName(props.target); - light.target = target; - } - - if (props.hasOwnProperty('castShadow') && string_to_boolean(props.castShadow)) - { - let width = 512; - let height = 512; - if (props.hasOwnProperty('size')) { - const size = props.size.split(','); - width = parseInt(size[0]); - height = parseInt(size[1]); - } - light.setShadow(true, width, height); - - if (props.hasOwnProperty('area')) { - const area = props.area.split(','); - let left = parseFloat(area[0]); - let right = parseFloat(area[1]); - let bottom = parseFloat(area[2]); - let top = parseFloat(area[3]); - let near = parseFloat(area[4]); - let far = parseFloat(area[5]); - light.setShadowProjection(left, right, bottom, top, near, far); - } - - if (props.hasOwnProperty('radius')) - { - let radius = parseFloat(props.radius); - light.setShadowRadius(radius); - } - - if (props.hasOwnProperty('bias')) - { - light.bias = parseFloat(props.bias); - } - - if (props.hasOwnProperty('force_cull')) - { - light.forceCull = string_to_boolean(props.force_cull); - } - } - - if (parent != null) { - parent.add(light); - } - else { - doc.scene.add(light); - } - doc.scene.addWidget(light); - return light; - }, - remove: (doc, obj) => { - doc.scene.removeWidget(obj); - }, - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("intensity" in input) - { - let intensity = input.intensity; - props.intensity = intensity; - obj.intensity = parseFloat(intensity); - } - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if ("target" in input) - { - props.target = input.target; - let target = doc.scene.getObjectByName(input.target); - obj.target = target; - } - - if ("castShadow" in input) - { - props.castShadow = input.castShadow; - - let castShadow = string_to_boolean(input.castShadow); - let width = 512; - let height = 512; - if (input.hasOwnProperty('size')) { - props.size = input.size; - let size = input.size.split(','); - width = parseInt(size[0]); - height = parseInt(size[1]); - } - obj.setShadow(castShadow, width, height); - } - - if ("area" in input) - { - props.area = input.area; - const area = input.area.split(','); - let left = parseFloat(area[0]); - let right = parseFloat(area[1]); - let bottom = parseFloat(area[2]); - let top = parseFloat(area[3]); - let near = parseFloat(area[4]); - let far = parseFloat(area[5]); - obj.setShadowProjection(left, right, bottom, top, near, far); - } - - if ("radius" in input) - { - props.radius = input.radius; - let radius = parseFloat(input.radius); - obj.setShadowRadius(radius); - } - - if ("bias" in input) - { - props.bias = input.bias; - obj.bias = parseFloat(input.bias); - } - - if ("force_cull" in input) - { - props.force_cull = input.force_cull; - obj.forceCull = string_to_boolean(input.force_cull); - } - - if ("auto_area" in input) - { - let aabb = obj.getBoundingBox(doc.scene); - let minPos = aabb.minPos; - let maxPos = aabb.maxPos; - obj.setShadowProjection(minPos.x, maxPos.x, minPos.y, maxPos.y, -maxPos.z, -minPos.z); - props.area = `${minPos.x}, ${maxPos.x}, ${minPos.y}, ${maxPos.y}, ${-maxPos.z}, ${-minPos.z}`; - let ret = { area: props.area }; - return JSON.stringify(ret); - } - - tuning_object3d(doc, obj, input); - - return ""; - } -}; - -class BackgroundDocument extends BackgroundScene -{ - constructor(near, far) - { - super(null, near, far); - - this.Tags = { scene, sky, env_light, group, plane, box, sphere, model, directional_light }; - this.reset(); - } - - reset() - { - for (let tag in this.Tags) - { - if (this.Tags[tag].hasOwnProperty('reset')) - { - this.Tags[tag].reset(this); - } - } - } - - create(tag, props, mode, parent = null) - { - if (!(tag in this.Tags)) return null; - - const obj = this.Tags[tag].create(this, props, mode, parent); - if (obj == null) return null; - - if (Object.isExtensible(obj)) - { - obj.tag = tag; - } - - if (props.hasOwnProperty('name')) - { - obj.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if (props.hasOwnProperty('texture')) - { - let img = imageLoader.loadFile(props.texture); - if (img!=null) - { - obj.setColorTexture(img); - } - } - - if (props.hasOwnProperty('metalness')) - { - obj.metalness = parseFloat(props.metalness); - } - - if (props.hasOwnProperty('roughness')) - { - obj.roughness = parseFloat(props.roughness); - } - - if (props.hasOwnProperty('is_building')) - { - obj.isBuilding = string_to_boolean(props.is_building); - } - - return obj; - } - - load_xml_node(xmlNode, mode, parent = null) - { - if (parent == null) { - parent = this; - } - for (let child of xmlNode.children) { - const obj = this.create(child.tagName, child.attributes, mode, parent); - if (obj===null) continue; - this.load_xml_node(child, mode, obj); - } - - } - - load_xml(xmlText, mode) - { - const parsed = parse(xmlText); - let root = null; - for (let top of parsed) - { - if (top.tagName == 'document') - { - root = top; - break; - } - } - if (root) - { - this.load_xml_node(root, mode); - } - } - - load_local_xml(filename) - { - const xmlText = fileLoader.loadTextFile(filename); - if (xmlText!=null) - { - this.load_xml(xmlText, "local"); - } - } -} - -class Document -{ - constructor(view) - { - this.view = view; - this.width = view.clientWidth; - this.height = view.clientHeight; - this.Tags = { scene, camera, fog, sky, env_light, control, group, plane, box, sphere, model, avatar, directional_light }; - this.picked_key = ""; - this.reset(); - } - - setSize(width, height) - { - this.width = width; - this.height = height; - - if (this.camera) - { - this.camera.aspect = width / height; - this.camera.updateProjectionMatrix(); - } - } - - reset() - { - this.saved_text = ""; - - if (this.picked_key!="") - { - gamePlayer.message("object_picked", ""); - this.picked_key = ""; - } - - for (let tag in this.Tags) - { - if (this.Tags[tag].hasOwnProperty('reset')) - { - this.Tags[tag].reset(this); - } - } - - this.internal_index = {}; - this.external_index = {}; - this.external_index.index = {}; - this.bakables = []; - - this.lightmap_bake = null; - this.env_gen = null; - this.probe_grid_bake = null; - this.lod_probe_grid_bake = null; - } - - tick(delta) - { - if (this.controls) - { - if (this.controls.hasOwnProperty('update')) - { - this.controls.update(); - } - } - } - - render(renderer) - { - this.renderer = renderer; - - if (this.lightmap_bake!=null) - { - this.lightmap_bake.render(renderer); - } - - if (this.env_gen!=null) - { - this.env_gen.render(renderer); - } - - if (this.probe_grid_bake!=null) - { - this.probe_grid_bake.render(renderer); - } - - if (this.lod_probe_grid_bake!=null) - { - this.lod_probe_grid_bake.render(renderer); - } - - if (this.scene && this.camera) - { - renderer.render(this.scene, this.camera); - } - } - - create(tag, props, mode, parent = null) - { - if (!(tag in this.Tags)) return null; - - const obj = this.Tags[tag].create(this, props, mode, parent); - if (obj == null) return null; - - obj.uuid = uuid(); - obj.tag = tag; - - if (props.hasOwnProperty('name')) - { - obj.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if (props.hasOwnProperty('texture')) - { - let img = imageLoader.loadFile(props.texture); - if (img!=null) - { - obj.setColorTexture(img); - } - } - - if (props.hasOwnProperty('metalness')) - { - obj.metalness = parseFloat(props.metalness); - } - - if (props.hasOwnProperty('roughness')) - { - obj.roughness = parseFloat(props.roughness); - } - - if (props.hasOwnProperty('is_building')) - { - obj.isBuilding = string_to_boolean(props.is_building); - } - - return obj; - } - - remove(obj) - { - if (obj.hasOwnProperty('tag')) { - const tag = this.Tags[obj.tag]; - if (tag.hasOwnProperty('remove')) { - tag.remove(this, obj); - } - } - - { - let index = this.bakables.indexOf(obj); - if (index>=0) - { - this.bakables.splice(index, 1); - } - } - - if (obj.parent) - { - obj.parent.remove(obj); - } - } - - load_xml_node(xmlNode, mode, parent = null) - { - for (let child of xmlNode.children) { - let obj = null; - if (parent == null) - { - obj = this.create(child.tagName, child.attributes, mode, this); - } - else - { - obj = this.create(child.tagName, child.attributes, mode, parent); - } - if (obj===null) continue; - - let key = obj.uuid; - - let internal_node = {}; - internal_node.obj = obj; - internal_node.xml_node = child; - this.internal_index[key] = internal_node; - - let external_node = {}; - external_node.tagName = child.tagName; - external_node.attributes = child.attributes; - external_node.children = []; - - if(child.tagName == "scene") - { - this.external_index.root = key; - } - else if (parent!=null) - { - let parent_key = parent.uuid; - let external_node_parent = this.external_index.index[parent.uuid]; - external_node.parent = parent_key; - external_node_parent.children.push(key); - } - this.external_index.index[key] = external_node; - - this.load_xml_node(child, mode, obj); - } - } - - - load_xml(xmlText, mode) - { - this.xml_nodes = parse(xmlText, {keepComments: true}); - this.saved_text = genXML(this.xml_nodes); - - let root = null; - for (let top of this.xml_nodes) - { - if (top.tagName == 'document') - { - root = top; - break; - } - } - if (root) - { - this.load_xml_node(root, mode); - } - - gamePlayer.message("index_loaded", JSON.stringify(this.external_index)); - } - - is_modified() - { - let gen_xml = genXML(this.xml_nodes); - return gen_xml != this.saved_text; - } - - get_xml() - { - this.saved_text = genXML(this.xml_nodes); - return this.saved_text; - } - - picking(state) - { - if (state) - { - this.controls.enabled = false; - view.addEventListener("pointerdown", picking_pointerdown); - } - else - { - this.controls.enabled = true; - view.removeEventListener("pointerdown", picking_pointerdown); - } - } - - pick_obj(key) - { - let obj = null; - if (key!="") - { - obj = this.internal_index[key].obj; - } - - if (this.picked_key != "") - { - if (this.picked_key in this.internal_index) - { - let picked_obj = this.internal_index[this.picked_key].obj; - if (picked_obj.hasOwnProperty("setToonShading")) - { - picked_obj.setToonShading(0); - } - } - } - - this.picked_key = key; - - if (obj!=null) - { - if (obj.hasOwnProperty("setToonShading")) - { - obj.setToonShading(16, 5.0, new Vector3(1.0, 1.0, 0.2)); - } - } - gamePlayer.message("object_picked", key); - } - - tuning(input) - { - if (this.picked_key=="") return ""; - let picked_obj = this.internal_index[this.picked_key].obj; - let node = this.internal_index[this.picked_key].xml_node; - let tag = node.tagName; - - if (!(tag in this.Tags)) return ""; - return this.Tags[tag].tuning(this, picked_obj, input); - } - - initialize(input) - { - if (this.picked_key=="") return ""; - let picked_obj = this.internal_index[this.picked_key].obj; - let node = this.internal_index[this.picked_key].xml_node; - let tag = node.tagName; - - if (!(tag in this.Tags)) return ""; - return this.Tags[tag].initialize(this, picked_obj, input); - } - - generate(input) - { - if (this.picked_key=="") return; - let picked_obj = this.internal_index[this.picked_key].obj; - let node = this.internal_index[this.picked_key].xml_node; - let tag = node.tagName; - - if (!(tag in this.Tags)) return; - this.Tags[tag].generate(this, picked_obj, input); - } - - req_create(base_key, tag) - { - let internal_node_base = this.internal_index[base_key]; - let external_node_base = this.external_index.index[base_key]; - - let xmlNode = internal_node_base.xml_node; - let parent = internal_node_base.obj; - - let child = {tagName:tag, attributes: {}, children: []}; - xmlNode.children.push(child); - - let obj = this.create(tag, {}, "local", parent); - let key = obj.uuid; - - let internal_node = {}; - internal_node.obj = obj; - internal_node.xml_node = child; - this.internal_index[key] = internal_node; - - let external_node = {tagName:tag, attributes: {}, children: []}; - external_node.parent = base_key; - external_node_base.children.push(key); - this.external_index.index[key] = external_node; - - let msg = {}; - msg[key] = external_node; - - gamePlayer.message("object_created", JSON.stringify(msg)); - - this.pick_obj(key); - } - - req_remove(key) - { - let internal_node = this.internal_index[key]; - let external_node = this.external_index.index[key]; - - let base_key = external_node.parent; - let internal_node_base = this.internal_index[base_key]; - let external_node_base = this.external_index.index[base_key]; - - let xmlNode = internal_node.xml_node; - let xmlNode_parent = internal_node_base.xml_node; - { - let idx = xmlNode_parent.children.indexOf(xmlNode); - if (idx>-1) - { - xmlNode_parent.children.splice(idx, 1); - } - } - - let obj = internal_node.obj; - this.remove(obj); - - { - let idx = external_node_base.children.indexOf(key); - if (idx>-1) - { - external_node_base.children.splice(idx,1); - } - } - - delete this.internal_index[key]; - delete this.external_index.index[key]; - - gamePlayer.message("object_removed", key); - - this.pick_obj(""); - } -} - -function picking_pointerdown(event) -{ - let x = event.clientX; - let y = event.clientY; - - let intersect = gamePlayer.pickObject(x,y); - if (intersect!=null) - { - doc.pick_obj(intersect.uuid); - } - else if (doc.scene.background!=null) - { - doc.pick_obj(doc.scene.background.uuid); - } - else - { - doc.pick_obj(doc.scene.uuid); - } -} - -class Clock { - - constructor( autoStart = true ) { - - this.autoStart = autoStart; - - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; - - this.running = false; - - } - - start() { - - this.startTime = now(); - - this.oldTime = this.startTime; - this.elapsedTime = 0; - this.running = true; - - } - - stop() { - - this.getElapsedTime(); - this.running = false; - this.autoStart = false; - - } - - getElapsedTime() { - - this.getDelta(); - return this.elapsedTime; - - } - - getDelta() { - - let diff = 0; - - if ( this.autoStart && ! this.running ) { - - this.start(); - return 0; - - } - - if ( this.running ) { - - const newTime = now(); - - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; - - this.elapsedTime += diff; - - } - - return diff; - - } - -} - -function isModified(x) -{ - return JSON.stringify(doc.is_modified()); -} - -function setXML(xml) -{ - doc.reset(); - doc.load_xml(xml, "local"); - return ""; -} - -function getXML(x) -{ - return doc.get_xml(); -} - -function picking(state) -{ - let bstate = state=="on"; - gamePlayer.picking = bstate; - doc.picking(bstate); - return ""; -} - -function pick_obj(key) -{ - doc.pick_obj(key); - return ""; -} - -function tuning(args) -{ - let input = JSON.parse(args); - return doc.tuning(input); -} - -function initialize(args) -{ - let input = JSON.parse(args); - return doc.initialize(input); -} - -function generate(args) -{ - let input = JSON.parse(args); - doc.generate(input); - return ""; -} - -function create(args) -{ - let input = JSON.parse(args); - let base_key = input.base_key; - let tag = input.tag; - doc.req_create(base_key, tag); - return ""; -} - -function remove(key) -{ - doc.req_remove(key); - return ""; -} - -function init(width, height) -{ - renderer = new GLRenderer(); - doc = new Document(view); - clock = new Clock(); - - message_map = { isModified, setXML, getXML, picking, pick_obj, tuning, initialize, generate, create, remove}; -} - -function render(width, height, size_changed) -{ - if (size_changed) - { - doc.setSize(width, height); - } - let delta = clock.getDelta(); - doc.tick(delta); - doc.render(renderer); - -} - -function message_handling(name, msg) -{ - if (name in message_map) - { - return message_map[name](msg); - } - return ""; -} - -setCallback('init', init); -setCallback('render', render); -setCallback('message', message_handling); diff --git a/GameDev/bin/Release/xmleditor/controls/EventDispatcher.js b/GameDev/bin/Release/xmleditor/controls/EventDispatcher.js deleted file mode 100644 index 0a40a60e..00000000 --- a/GameDev/bin/Release/xmleditor/controls/EventDispatcher.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * https://github.com/mrdoob/eventdispatcher.js/ - */ - -class EventDispatcher { - - addEventListener( type, listener ) { - - if ( this._listeners === undefined ) this._listeners = {}; - - const listeners = this._listeners; - - if ( listeners[ type ] === undefined ) { - - listeners[ type ] = []; - - } - - if ( listeners[ type ].indexOf( listener ) === - 1 ) { - - listeners[ type ].push( listener ); - - } - - } - - hasEventListener( type, listener ) { - - if ( this._listeners === undefined ) return false; - - const listeners = this._listeners; - - return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; - - } - - removeEventListener( type, listener ) { - - if ( this._listeners === undefined ) return; - - const listeners = this._listeners; - const listenerArray = listeners[ type ]; - - if ( listenerArray !== undefined ) { - - const index = listenerArray.indexOf( listener ); - - if ( index !== - 1 ) { - - listenerArray.splice( index, 1 ); - - } - - } - - } - - dispatchEvent( event ) { - if ( this._listeners === undefined ) return; - - const listeners = this._listeners; - const listenerArray = listeners[event.type]; - - if ( listenerArray !== undefined ) { - - event.target = this; - - // Make a copy, in case listeners are removed while iterating. - const array = listenerArray.slice( 0 ); - - for ( let i = 0, l = array.length; i < l; i ++ ) { - - array[ i ].call( this, event ); - - } - - event.target = null; - - } - - } - -} - - -export { EventDispatcher }; diff --git a/GameDev/bin/Release/xmleditor/controls/OrbitControls.js b/GameDev/bin/Release/xmleditor/controls/OrbitControls.js deleted file mode 100644 index 74a34db6..00000000 --- a/GameDev/bin/Release/xmleditor/controls/OrbitControls.js +++ /dev/null @@ -1,1261 +0,0 @@ -import { EventDispatcher } from "./EventDispatcher.js"; -import { MOUSE, TOUCH } from "./constants.js"; -import { Quaternion } from "../math/Quaternion.js"; -import { Spherical } from "../math/Spherical.js"; -import { Vector2 } from "../math/Vector2.js"; -import { Vector3 } from "../math/Vector3.js"; -import { Matrix4 } from "../math/Matrix4.js"; - - -// This set of controls performs orbiting, dollying (zooming), and panning. -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// -// Orbit - left mouse / touch: one-finger move -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move - -const _changeEvent = { type: 'change' }; -const _startEvent = { type: 'start' }; -const _endEvent = { type: 'end' }; - -class OrbitControls extends EventDispatcher { - - constructor( object, domElement ) { - - super(); - - if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); - - this.object = object; - this.domElement = domElement; - - // Set to false to disable this control - this.enabled = true; - - // "target" sets the location of focus, where the object orbits around - this.target = new Vector3(); - - // How far you can dolly in and out ( PerspectiveCamera only ) - this.minDistance = 0; - this.maxDistance = Infinity; - - // How far you can zoom in and out ( OrthographicCamera only ) - this.minZoom = 0; - this.maxZoom = Infinity; - - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - this.minPolarAngle = 0; // radians - this.maxPolarAngle = Math.PI; // radians - - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - this.minAzimuthAngle = - Infinity; // radians - this.maxAzimuthAngle = Infinity; // radians - - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - this.enableDamping = false; - this.dampingFactor = 0.05; - - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - this.enableZoom = true; - this.zoomSpeed = 1.0; - - // Set to false to disable rotating - this.enableRotate = true; - this.rotateSpeed = 1.0; - - // Set to false to disable panning - this.enablePan = true; - this.panSpeed = 1.0; - this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up - this.keyPanSpeed = 7.0; // pixels moved per arrow key push - - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - this.autoRotate = false; - this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 - - // The four arrow keys - this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; - - // Mouse buttons - this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; - - // Touch fingers - this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; - - // for reset - this.target0 = this.target.clone(); - this.position0 = this.object.getPosition(new Vector3()); - - // this.zoom0 = this.object.zoom; - this.zoom0 = 1.0; - - // the target DOM element for key events - this._domElementKeyEvents = null; - - // - // public methods - // - - this.getPolarAngle = function () { - - return spherical.phi; - - }; - - this.getAzimuthalAngle = function () { - - return spherical.theta; - - }; - - this.getDistance = function () { - let position = this.object.getPosition(new Vector3()); - return position.distanceTo( this.target ); - - }; - - this.listenToKeyEvents = function ( domElement ) { - - domElement.addEventListener( 'keydown', onKeyDown ); - this._domElementKeyEvents = domElement; - - }; - - this.saveState = function () { - - scope.target0.copy(scope.target); - this.object.getPosition(scope.position0); - - // scope.zoom0 = scope.object.zoom; - scope.zoom0 = 1.0; - - }; - - this.reset = function () { - - scope.target.copy(scope.target0); - - this.object.getPosition(scope.position0); - - // scope.object.zoom = scope.zoom0; - - scope.object.updateProjectionMatrix(); - scope.dispatchEvent( _changeEvent ); - - scope.update(); - - state = STATE.NONE; - - }; - - // this method is exposed, but perhaps it would be better if we can make it private... - this.update = function () { - - const offset = new Vector3(); - - // so camera.up is the orbit axis - let camera_up = object.getUp(new Vector3()); - const quat = new Quaternion().setFromUnitVectors(camera_up, new Vector3(0, 1, 0)); - const quatInverse = quat.clone().invert(); - - const lastPosition = new Vector3(); - const lastQuaternion = new Quaternion(); - - const twoPI = 2 * Math.PI; - - return function update() { - - const position = scope.object.getPosition(new Vector3()); - - offset.copy( position ).sub( scope.target ); - - // rotate offset to "y-axis-is-up" space - offset.applyQuaternion( quat ); - - // angle from z-axis around y-axis - spherical.setFromVector3( offset ); - - if ( scope.autoRotate && state === STATE.NONE ) { - - rotateLeft( getAutoRotationAngle() ); - - } - - if ( scope.enableDamping ) { - - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; - - } else { - - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; - - } - - // restrict theta to be between desired limits - - let min = scope.minAzimuthAngle; - let max = scope.maxAzimuthAngle; - - if ( isFinite( min ) && isFinite( max ) ) { - - if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; - - if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; - - if ( min <= max ) { - - spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); - - } else { - - spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? - Math.max( min, spherical.theta ) : - Math.min( max, spherical.theta ); - - } - - } - - // restrict phi to be between desired limits - spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); - - spherical.makeSafe(); - - - spherical.radius *= scale; - - // restrict radius to be between desired limits - spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); - - // move target to panned location - - if ( scope.enableDamping === true ) { - - scope.target.addScaledVector( panOffset, scope.dampingFactor ); - - } else { - - scope.target.add( panOffset ); - - } - - offset.setFromSpherical( spherical ); - - // rotate offset back to "camera-up-vector-is-up" space - offset.applyQuaternion( quatInverse ); - - position.copy(scope.target).add(offset); - scope.object.setPosition(position) - - scope.object.lookAt( scope.target ); - - if ( scope.enableDamping === true ) { - - sphericalDelta.theta *= ( 1 - scope.dampingFactor ); - sphericalDelta.phi *= ( 1 - scope.dampingFactor ); - - panOffset.multiplyScalar( 1 - scope.dampingFactor ); - - } else { - - sphericalDelta.set( 0, 0, 0 ); - - panOffset.set( 0, 0, 0 ); - - } - - scale = 1; - - // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 - - const quaternion = scope.object.getQuaternion(new Quaternion()); - - if ( zoomChanged || - lastPosition.distanceToSquared(position) > EPS || - 8 * (1 - lastQuaternion.dot(quaternion) ) > EPS ) { - - scope.dispatchEvent( _changeEvent ); - - lastPosition.copy(position ); - lastQuaternion.copy(quaternion); - zoomChanged = false; - - return true; - - } - - return false; - - }; - - }(); - - this.dispose = function () { - - scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); - - scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); - scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); - scope.domElement.removeEventListener( 'wheel', onMouseWheel ); - - scope.domElement.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - - - if ( scope._domElementKeyEvents !== null ) { - - scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); - - } - - //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? - - }; - - // - // internals - // - - const scope = this; - - const STATE = { - NONE: - 1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; - - let state = STATE.NONE; - - const EPS = 0.000001; - - // current position in spherical coordinates - const spherical = new Spherical(); - const sphericalDelta = new Spherical(); - - let scale = 1; - const panOffset = new Vector3(); - let zoomChanged = false; - - const rotateStart = new Vector2(); - const rotateEnd = new Vector2(); - const rotateDelta = new Vector2(); - - const panStart = new Vector2(); - const panEnd = new Vector2(); - const panDelta = new Vector2(); - - const dollyStart = new Vector2(); - const dollyEnd = new Vector2(); - const dollyDelta = new Vector2(); - - const pointers = []; - const pointerPositions = {}; - - function getAutoRotationAngle() { - - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - - } - - function getZoomScale() { - - return Math.pow( 0.95, scope.zoomSpeed ); - - } - - function rotateLeft( angle ) { - - sphericalDelta.theta -= angle; - - } - - function rotateUp( angle ) { - - sphericalDelta.phi -= angle; - - } - - const panLeft = function () { - - const v = new Vector3(); - - return function panLeft( distance, objectMatrix ) { - - v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix - v.multiplyScalar( - distance ); - - panOffset.add( v ); - - }; - - }(); - - const panUp = function () { - - const v = new Vector3(); - - return function panUp( distance, objectMatrix ) { - - if ( scope.screenSpacePanning === true ) { - - v.setFromMatrixColumn( objectMatrix, 1 ); - - } else { - let up = scope.object.getUp(new Vector3()); - v.setFromMatrixColumn( objectMatrix, 0 ); - v.crossVectors(up, v ); - - } - - v.multiplyScalar( distance ); - - panOffset.add( v ); - - }; - - }(); - - // deltaX and deltaY are in pixels; right and down are positive - const pan = function () { - - const offset = new Vector3(); - - return function pan( deltaX, deltaY ) { - - const element = scope.domElement; - - if ( scope.object.isPerspectiveCamera ) { - - // perspective - const position = scope.object.getPosition(new Vector3()); - offset.copy( position ).sub( scope.target ); - let targetDistance = offset.length(); - - // half of the fov is center to top of screen - targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); - - const matrix = scope.object.getMatrix(new Matrix4()); - // we use only clientHeight here so aspect ratio does not distort speed - panLeft(2 * deltaX * targetDistance / element.clientHeight, matrix ); - panUp(2 * deltaY * targetDistance / element.clientHeight, matrix ); - - } else if (scope.object.isOrthographicCamera) { - - const matrix = scope.object.getMatrix(new Matrix4()); - // orthographic - panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, matrix ); - panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, matrix ); - - } else { - - // camera neither orthographic nor perspective - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); - scope.enablePan = false; - - } - - }; - - }(); - - function dollyOut( dollyScale ) { - - if ( scope.object.isPerspectiveCamera ) { - - scale /= dollyScale; - - } else if ( scope.object.isOrthographicCamera ) { - - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - - } else { - - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; - - } - - } - - function dollyIn( dollyScale ) { - - if ( scope.object.isPerspectiveCamera ) { - - scale *= dollyScale; - - } else if ( scope.object.isOrthographicCamera ) { - - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - - } else { - - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; - - } - - } - - // - // event callbacks - update the object state - // - - function handleMouseDownRotate( event ) { - - rotateStart.set( event.clientX, event.clientY ); - - } - - function handleMouseDownDolly( event ) { - - dollyStart.set( event.clientX, event.clientY ); - - } - - function handleMouseDownPan( event ) { - - panStart.set( event.clientX, event.clientY ); - - } - - function handleMouseMoveRotate( event ) { - - rotateEnd.set( event.clientX, event.clientY ); - - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - - const element = scope.domElement; - - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - - rotateStart.copy( rotateEnd ); - - scope.update(); - - } - - function handleMouseMoveDolly( event ) { - - dollyEnd.set( event.clientX, event.clientY ); - - dollyDelta.subVectors( dollyEnd, dollyStart ); - - if ( dollyDelta.y > 0 ) { - - dollyOut( getZoomScale() ); - - } else if ( dollyDelta.y < 0 ) { - - dollyIn( getZoomScale() ); - - } - - dollyStart.copy( dollyEnd ); - - scope.update(); - - } - - function handleMouseMovePan( event ) { - - panEnd.set( event.clientX, event.clientY ); - - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - - pan( panDelta.x, panDelta.y ); - - panStart.copy( panEnd ); - - scope.update(); - - } - - function handleMouseWheel( event ) { - - if ( event.deltaY < 0 ) { - - dollyIn( getZoomScale() ); - - } else if ( event.deltaY > 0 ) { - - dollyOut( getZoomScale() ); - - } - - scope.update(); - - } - - function handleKeyDown( event ) { - - let needsUpdate = false; - - switch ( event.code ) { - - case scope.keys.UP: - pan( 0, scope.keyPanSpeed ); - needsUpdate = true; - break; - - case scope.keys.BOTTOM: - pan( 0, - scope.keyPanSpeed ); - needsUpdate = true; - break; - - case scope.keys.LEFT: - pan( scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; - - case scope.keys.RIGHT: - pan( - scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; - - } - - if ( needsUpdate ) { - - // prevent the browser from scrolling on cursor keys - // event.preventDefault(); - - scope.update(); - - } - - - } - - function handleTouchStartRotate() { - - if ( pointers.length === 1 ) { - - rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - - } else { - - const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); - const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - - rotateStart.set( x, y ); - - } - - } - - function handleTouchStartPan() { - - if ( pointers.length === 1 ) { - - panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - - } else { - - const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); - const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - - panStart.set( x, y ); - - } - - } - - function handleTouchStartDolly() { - - const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX; - const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY; - - const distance = Math.sqrt( dx * dx + dy * dy ); - - dollyStart.set( 0, distance ); - - } - - function handleTouchStartDollyPan() { - - if ( scope.enableZoom ) handleTouchStartDolly(); - - if ( scope.enablePan ) handleTouchStartPan(); - - } - - function handleTouchStartDollyRotate() { - - if ( scope.enableZoom ) handleTouchStartDolly(); - - if ( scope.enableRotate ) handleTouchStartRotate(); - - } - - function handleTouchMoveRotate( event ) { - - if ( pointers.length == 1 ) { - - rotateEnd.set( event.pageX, event.pageY ); - - } else { - - const position = getSecondPointerPosition( event ); - - const x = 0.5 * ( event.pageX + position.x ); - const y = 0.5 * ( event.pageY + position.y ); - - rotateEnd.set( x, y ); - - } - - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - - const element = scope.domElement; - - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - - rotateStart.copy( rotateEnd ); - - } - - function handleTouchMovePan( event ) { - - if ( pointers.length === 1 ) { - - panEnd.set( event.pageX, event.pageY ); - - } else { - - const position = getSecondPointerPosition( event ); - - const x = 0.5 * ( event.pageX + position.x ); - const y = 0.5 * ( event.pageY + position.y ); - - panEnd.set( x, y ); - - } - - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - - pan( panDelta.x, panDelta.y ); - - panStart.copy( panEnd ); - - } - - function handleTouchMoveDolly( event ) { - - const position = getSecondPointerPosition( event ); - - const dx = event.pageX - position.x; - const dy = event.pageY - position.y; - - const distance = Math.sqrt( dx * dx + dy * dy ); - - dollyEnd.set( 0, distance ); - - dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); - - dollyOut( dollyDelta.y ); - - dollyStart.copy( dollyEnd ); - - } - - function handleTouchMoveDollyPan( event ) { - - if ( scope.enableZoom ) handleTouchMoveDolly( event ); - - if ( scope.enablePan ) handleTouchMovePan( event ); - - } - - function handleTouchMoveDollyRotate( event ) { - - if ( scope.enableZoom ) handleTouchMoveDolly( event ); - - if ( scope.enableRotate ) handleTouchMoveRotate( event ); - - } - - // - // event handlers - FSM: listen for events and reset state - // - - function onPointerDown( event ) { - - if ( scope.enabled === false ) return; - - if ( pointers.length === 0 ) { - - scope.domElement.setPointerCapture(); - - scope.domElement.addEventListener( 'pointermove', onPointerMove ); - scope.domElement.addEventListener( 'pointerup', onPointerUp ); - - } - - // - - addPointer( event ); - - if ( event.pointerType === 'touch' ) { - - onTouchStart( event ); - - } else { - - onMouseDown( event ); - - } - - } - - function onPointerMove( event ) { - - if ( scope.enabled === false ) return; - - if ( event.pointerType === 'touch' ) { - - onTouchMove( event ); - - } else { - - onMouseMove( event ); - - } - - } - - function onPointerUp( event ) { - - removePointer( event ); - - if ( pointers.length === 0 ) { - - scope.domElement.releasePointerCapture(); - - scope.domElement.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - - } - - scope.dispatchEvent( _endEvent ); - - state = STATE.NONE; - - } - - function onPointerCancel( event ) { - - removePointer( event ); - - } - - function onMouseDown( event ) { - - let mouseAction; - - switch ( event.button ) { - - case 0: - - mouseAction = scope.mouseButtons.LEFT; - break; - - case 1: - - mouseAction = scope.mouseButtons.MIDDLE; - break; - - case 2: - - mouseAction = scope.mouseButtons.RIGHT; - break; - - default: - - mouseAction = - 1; - - } - - switch ( mouseAction ) { - - case MOUSE.DOLLY: - - if ( scope.enableZoom === false ) return; - - handleMouseDownDolly( event ); - - state = STATE.DOLLY; - - break; - - case MOUSE.ROTATE: - - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - - if ( scope.enablePan === false ) return; - - handleMouseDownPan( event ); - - state = STATE.PAN; - - } else { - - if ( scope.enableRotate === false ) return; - - handleMouseDownRotate( event ); - - state = STATE.ROTATE; - - } - - break; - - case MOUSE.PAN: - - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - - if ( scope.enableRotate === false ) return; - - handleMouseDownRotate( event ); - - state = STATE.ROTATE; - - } else { - - if ( scope.enablePan === false ) return; - - handleMouseDownPan( event ); - - state = STATE.PAN; - - } - - break; - - default: - - state = STATE.NONE; - - } - - if ( state !== STATE.NONE ) { - - scope.dispatchEvent( _startEvent ); - - } - - } - - function onMouseMove( event ) { - - if ( scope.enabled === false ) return; - - switch ( state ) { - - case STATE.ROTATE: - - if ( scope.enableRotate === false ) return; - - handleMouseMoveRotate( event ); - - break; - - case STATE.DOLLY: - - if ( scope.enableZoom === false ) return; - - handleMouseMoveDolly( event ); - - break; - - case STATE.PAN: - - if ( scope.enablePan === false ) return; - - handleMouseMovePan( event ); - - break; - - } - - } - - function onMouseWheel( event ) { - - if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return; - - // event.preventDefault(); - - scope.dispatchEvent( _startEvent ); - - handleMouseWheel( event ); - - scope.dispatchEvent( _endEvent ); - - } - - function onKeyDown( event ) { - - if ( scope.enabled === false || scope.enablePan === false ) return; - - handleKeyDown( event ); - - } - - function onTouchStart( event ) { - - trackPointer( event ); - - switch ( pointers.length ) { - - case 1: - - switch ( scope.touches.ONE ) { - - case TOUCH.ROTATE: - - if ( scope.enableRotate === false ) return; - - handleTouchStartRotate(); - - state = STATE.TOUCH_ROTATE; - - break; - - case TOUCH.PAN: - - if ( scope.enablePan === false ) return; - - handleTouchStartPan(); - - state = STATE.TOUCH_PAN; - - break; - - default: - - state = STATE.NONE; - - } - - break; - - case 2: - - switch ( scope.touches.TWO ) { - - case TOUCH.DOLLY_PAN: - - if ( scope.enableZoom === false && scope.enablePan === false ) return; - - handleTouchStartDollyPan(); - - state = STATE.TOUCH_DOLLY_PAN; - - break; - - case TOUCH.DOLLY_ROTATE: - - if ( scope.enableZoom === false && scope.enableRotate === false ) return; - - handleTouchStartDollyRotate(); - - state = STATE.TOUCH_DOLLY_ROTATE; - - break; - - default: - - state = STATE.NONE; - - } - - break; - - default: - - state = STATE.NONE; - - } - - if ( state !== STATE.NONE ) { - - scope.dispatchEvent( _startEvent ); - - } - - } - - function onTouchMove( event ) { - - trackPointer( event ); - - switch ( state ) { - - case STATE.TOUCH_ROTATE: - - if ( scope.enableRotate === false ) return; - - handleTouchMoveRotate( event ); - - scope.update(); - - break; - - case STATE.TOUCH_PAN: - - if ( scope.enablePan === false ) return; - - handleTouchMovePan( event ); - - scope.update(); - - break; - - case STATE.TOUCH_DOLLY_PAN: - - if ( scope.enableZoom === false && scope.enablePan === false ) return; - - handleTouchMoveDollyPan( event ); - - scope.update(); - - break; - - case STATE.TOUCH_DOLLY_ROTATE: - - if ( scope.enableZoom === false && scope.enableRotate === false ) return; - - handleTouchMoveDollyRotate( event ); - - scope.update(); - - break; - - default: - - state = STATE.NONE; - - } - - } - - function onContextMenu( event ) { - - if ( scope.enabled === false ) return; - - // event.preventDefault(); - - } - - function addPointer( event ) { - - pointers.push( event ); - - } - - function removePointer( event ) { - - delete pointerPositions[ event.pointerId ]; - - for ( let i = 0; i < pointers.length; i ++ ) { - - if ( pointers[ i ].pointerId == event.pointerId ) { - - pointers.splice( i, 1 ); - return; - - } - - } - - } - - function trackPointer( event ) { - - let position = pointerPositions[ event.pointerId ]; - - if ( position === undefined ) { - - position = new Vector2(); - pointerPositions[ event.pointerId ] = position; - - } - - position.set( event.pageX, event.pageY ); - - } - - function getSecondPointerPosition( event ) { - - const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ]; - - return pointerPositions[ pointer.pointerId ]; - - } - - // - - scope.domElement.addEventListener( 'contextmenu', onContextMenu ); - - scope.domElement.addEventListener( 'pointerdown', onPointerDown ); - scope.domElement.addEventListener( 'pointercancel', onPointerCancel ); - scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); - - // force an update at start - - this.update(); - - } - -} - - -// This set of controls performs orbiting, dollying (zooming), and panning. -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// This is very similar to OrbitControls, another set of touch behavior -// -// Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - left mouse, or arrow keys / touch: one-finger move - -class MapControls extends OrbitControls { - - constructor( object, domElement ) { - - super( object, domElement ); - - this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up - - this.mouseButtons.LEFT = MOUSE.PAN; - this.mouseButtons.RIGHT = MOUSE.ROTATE; - - this.touches.ONE = TOUCH.PAN; - this.touches.TWO = TOUCH.DOLLY_ROTATE; - - } - -} - -export { OrbitControls, MapControls }; diff --git a/GameDev/bin/Release/xmleditor/controls/constants.js b/GameDev/bin/Release/xmleditor/controls/constants.js deleted file mode 100644 index ef811450..00000000 --- a/GameDev/bin/Release/xmleditor/controls/constants.js +++ /dev/null @@ -1,2 +0,0 @@ -export const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; -export const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; diff --git a/GameDev/bin/Release/xmleditor/editor_document.js b/GameDev/bin/Release/xmleditor/editor_document.js deleted file mode 100644 index 5e7a9191..00000000 --- a/GameDev/bin/Release/xmleditor/editor_document.js +++ /dev/null @@ -1,3224 +0,0 @@ -import { OrbitControls } from "./controls/OrbitControls.js"; -import { Vector3 } from "./math/Vector3.js"; -import { Vector4 } from "./math/Vector4.js"; -import { Matrix4 } from "./math/Matrix4.js"; -import { view } from "./view.js"; - -import * as txml from "./txml.js"; -import { genXML } from "./genXML.js"; - -function uuid(len, radix) { - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); - var uuid = [], i; - radix = radix || chars.length; - - if (len) { - // Compact form - for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix]; - } else { - // rfc4122, version 4 form - var r; - - // rfc4122 requires these characters - uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; - uuid[14] = '4'; - - // Fill in random data. At i==19 set the high bits of clock sequence as - // per rfc4122, sec. 4.1.5 - for (i = 0; i < 36; i++) { - if (!uuid[i]) { - r = 0 | Math.random()*16; - uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; - } - } - } - - return uuid.join(''); -} - -function string_to_boolean(string) { - switch (string.toLowerCase().trim()) { - case "true": - case "yes": - case "1": - return true; - - case "false": - case "no": - case "0": - case null: - return false; - - default: - return Boolean(string); - } -} - -class LightmapBaker -{ - constructor(doc, iterations, num_rays) - { - this.doc = doc; - this.lst = []; - for (let obj of doc.bakables) - { - let xml_node = doc.internal_index[obj.uuid].xml_node; - let attributes = xml_node.attributes; - if ("lightmap" in attributes) - { - let filename = attributes.lightmap; - let ext = filename.split('.').pop().toLowerCase(); - if (ext=='hdr') - { - this.lst.push({ model: obj, lightmap: filename, count: -1 }); - } - } - } - if (this.lst.length<1) - { - print("No bakable object found!"); - return; - } - - this.iterations = iterations; - this.num_rays_final = num_rays; - this.iter = 0; - this.idx_model = 0; - this.idx_texel = 0; - this.check_time = now(); - } - - render(renderer) - { - if (this.lst.length<1) - { - this.doc.lightmap_bake = null; - return; - } - - let frame_time = now(); - - while(this.doc.lightmap_bake != null) - { - let cur_time = now(); - if (cur_time -frame_time>=10) break; - - let item = this.lst[this.idx_model]; - if (item.count<0) - { - item.count = item.model.initializeLightmap(renderer); - } - - if (cur_time - this.check_time>=500) - { - print(`Building LOD Probe-Grid, iteration: ${this.iter+1}/${this.iterations}, model: ${this.idx_model+1}/${this.lst.length}, texel: ${this.idx_texel +1}/${item.count}`); - this.check_time = cur_time; - } - - let num_rays = (this.num_rays_final >> (this.iterations - this.iter)); - if (num_rays < 1) num_rays = 1; - let count_texels = renderer.updateLightmap(this.doc.scene, item.model, this.idx_texel, num_rays, 1.0); - this.idx_texel += count_texels; - if (this.idx_texel>=item.count) - { - renderer.filterLightmap(item.model); - this.idx_texel = 0; - this.idx_model++; - if (this.idx_model >= this.lst.length) - { - this.idx_model = 0; - this.iter++; - if (this.iter >= this.iterations) - { - this.doc.lightmap_bake = null; - print("Saving lightmaps."); - for (let item of this.lst) - { - let hdr_image = item.model.getLightmap(); - let res = HDRImageSaver.saveFile(hdr_image, item.lightmap); - if (!res) - { - print(`Failed to save ${item.lightmap}`); - } - } - - } - - } - - } - } - - } -} - -class EnvMapGen -{ - constructor(doc, proxy, xml_node, irradiance_only = false) - { - this.doc = doc; - this.xml_node = xml_node; - this.irradiance_only = irradiance_only; - - this.cube_target = new CubeRenderTarget(128,128); - this.envMapCreator = new EnvironmentMapCreator(); - this.iter = 0; - } - - render(renderer) - { - print(`Building environemnt map, iteration: ${this.iter}`); - let props = this.xml_node.attributes; - - let x = 0.0; - let y = 0.0; - let z = 0.0; - if ("probe_position" in props) - { - let probe_position = props.probe_position; - let position = probe_position.split(','); - x = parseFloat(position[0]); - y = parseFloat(position[1]); - z = parseFloat(position[2]); - } - - renderer.renderCube(this.doc.scene, this.cube_target, new Vector3(x, y,z)); - - let envLight = this.envMapCreator.create(this.cube_target, this.irradiance_only); - if (props.hasOwnProperty('dynamic_map')) - { - envLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - this.doc.scene.indirectLight = envLight; - - this.iter++; - if (this.iter > 5) - { - print("Saving environemnt map."); - if (this.irradiance_only) - { - let path_sh = "assets/sh.json"; - if (props.hasOwnProperty('path_sh')) - { - path_sh = props.path_sh; - } - - let text = JSON.stringify(envLight.shCoefficients); - let res = fileSaver.saveTextFile(path_sh, text); - - if (!res) - { - print("Failed to save enviroment map."); - } - } - else - { - let url = "assets/textures"; - let posx = "env_face0.jpg"; - let negx = "env_face1.jpg"; - let posy = "env_face2.jpg"; - let negy = "env_face3.jpg"; - let posz = "env_face4.jpg"; - let negz = "env_face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - if (posx.split('.').pop()=="hdr") - { - let down_img = this.cube_target.getHDRCubeImage(); - - let res = HDRImageSaver.saveCubeToFile(down_img, - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - if (!res) - { - print("Failed to save enviroment map."); - } - - } - else - { - let down_img = this.cube_target.getCubeImage(); - - let res = imageSaver.saveCubeToFile(down_img, - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - if (!res) - { - print("Failed to save enviroment map."); - } - } - } - - this.doc.env_gen = null; - } - } - -} - -class ProbeGridBaker -{ - constructor(doc, proxy, xml_node, iterations) - { - this.doc = doc; - this.xml_node = xml_node; - - this.cube_target = new CubeRenderTarget(64,64); - this.probe_grid = new ProbeGrid(); - this.probe_grid.setDivisions(proxy.divisions); - this.probe_grid.setCoverageMin(proxy.coverageMin); - this.probe_grid.setCoverageMax(proxy.coverageMax); - this.probe_grid.ypower = proxy.ypower; - - print("Constructing visibility information..."); - this.probe_grid.constructVisibility(doc.scene); - - let props = this.xml_node.attributes; - if (props.hasOwnProperty('dynamic_map')) - { - this.probe_grid.dynamicMap = string_to_boolean(props.dynamic_map); - } - if (props.hasOwnProperty('normal_bias')) - { - this.probe_grid.normalBias = parseFloat(props.normal_bias); - } - if (props.hasOwnProperty('per_primitive')) - { - this.probe_grid.perPrimitive = string_to_boolean(props.per_primitive); - } - this.doc.scene.indirectLight = this.probe_grid; - - let divisions = this.probe_grid.divisions; - this.probe_count = divisions.x*divisions.y*divisions.z; - - this.update_lst = []; - this.diff_stack = []; - - for (let i=0; i< this.probe_count; i++) - { - this.update_lst.push(i); - } - this.update_count = this.update_lst.length; - this.probe_idx = 0; - - this.iterations = iterations; - this.iter = 0; - this.check_time = now(); - - } - - render(renderer) - { - let frame_time = now(); - - if (frame_time - this.check_time>=500) - { - print(`Building probe-grid, iteration: ${this.iter+1}/${this.iterations}, probe: ${this.probe_idx +1}/${this.update_count}`); - this.check_time = frame_time; - } - - let divisions = this.probe_grid.divisions; - this.probe_grid.recordReferences = true; - while(now()-frame_time<10) - { - if (this.doc.probe_grid_bake == null) break; - - let x = this.update_lst[this.probe_idx]; - let y = x / divisions.x; - let z = y / divisions.y; - y = y % divisions.y; - x = x % divisions.x; - let v_idx = new Vector3(x,y,z); - - renderer.updateProbe(this.doc.scene, this.cube_target, this.probe_grid, v_idx); - this.probe_idx++; - if (this.probe_idx>=this.update_count) - { - this.probe_idx = 0; - this.iter++; - - if (this.iter < this.iterations) - { - let ref_arr = this.probe_grid.getReferences(); - let new_lst = []; - let diff_lst = []; - for (let i of this.update_lst) - { - if (ref_arr[i]) - { - new_lst.push(i); - } - else - { - diff_lst.push(i); - } - } - - if (diff_lst.length>0) - { - this.diff_stack.push(diff_lst); - } - - if (this.iter == this.iterations -1) - { - for(let j = this.diff_stack.length-1; j>=0; j--) - { - new_lst = new_lst.concat(this.diff_stack[j]); - } - } - - this.update_lst = new_lst; - this.update_count = this.update_lst.length; - } - else - { - print("Saving probe-grid."); - let props = this.xml_node.attributes; - let probe_data = "assets/probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let res = probeGridSaver.saveFile(this.probe_grid, probe_data); - if (!res) - { - print("Failed to save probe-grid."); - } - this.doc.probe_grid_bake = null; - } - } - } - this.probe_grid.recordReferences = false; - } - -} - -class LODProbeGridBaker -{ - constructor(doc, proxy, xml_node, iterations) - { - this.doc = doc; - this.xml_node = xml_node; - - this.cube_target = new CubeRenderTarget(64,64); - this.probe_grid = this.doc.scene.indirectLight; - - print("Constructing visibility information..."); - this.probe_grid.constructVisibility(doc.scene); - - this.probe_count = this.probe_grid.numberOfProbes; - this.probe_idx = 0; - - this.iterations = iterations; - this.iter = 0; - this.check_time = now(); - - } - - render(renderer) - { - let frame_time = now(); - - if (frame_time - this.check_time>=500) - { - print(`Building LOD Probe-Grid, iteration: ${this.iter+1}/${this.iterations}, probe: ${this.probe_idx +1}/${this.probe_count}`); - this.check_time = frame_time; - } - while(now()-frame_time<10) - { - if (this.doc.lod_probe_grid_bake == null) break; - renderer.updateProbe(this.doc.scene, this.cube_target, this.probe_grid, this.probe_idx); - this.probe_idx++; - if (this.probe_idx>=this.probe_count) - { - this.probe_idx = 0; - this.iter++; - - if (this.iter >= this.iterations) - { - print("Saving LOD Probe-Grid."); - let props = this.xml_node.attributes; - let probe_data = "assets/lod_probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let res = LODProbeGridSaver.saveFile(this.probe_grid, probe_data); - if (!res) - { - print("Failed to save probe-grid."); - } - this.doc.lod_probe_grid_bake = null; - } - } - } - } - -} - -class GPUProbeGridBaker -{ - constructor(doc, proxy, xml_node, iterations, num_rays) - { - this.doc = doc; - this.xml_node = xml_node; - - this.probe_grid = new ProbeGrid(); - this.probe_grid.setDivisions(proxy.divisions); - this.probe_grid.setCoverageMin(proxy.coverageMin); - this.probe_grid.setCoverageMax(proxy.coverageMax); - this.probe_grid.ypower = proxy.ypower; - - print("Constructing visibility information..."); - this.probe_grid.constructVisibility(doc.scene); - - let props = this.xml_node.attributes; - if (props.hasOwnProperty('dynamic_map')) - { - this.probe_grid.dynamicMap = string_to_boolean(props.dynamic_map); - } - if (props.hasOwnProperty('normal_bias')) - { - this.probe_grid.normalBias = parseFloat(props.normal_bias); - } - if (props.hasOwnProperty('per_primitive')) - { - this.probe_grid.perPrimitive = string_to_boolean(props.per_primitive); - } - this.doc.scene.indirectLight = this.probe_grid; - - let divisions = this.probe_grid.divisions; - this.probe_count = divisions.x*divisions.y*divisions.z; - - this.probe_idx = 0; - this.iterations = iterations; - this.num_rays_final = num_rays; - this.iter = 0; - this.check_time = now(); - } - - render(renderer) - { - let frame_time = now(); - - if (frame_time - this.check_time>=500) - { - print(`Building probe-grid, iteration: ${this.iter+1}/${this.iterations}, probe: ${this.probe_idx +1}/${this.probe_count}`); - this.check_time = frame_time; - } - - while(now()-frame_time<10) - { - if (this.doc.probe_grid_bake == null) break; - let num_rays = (this.num_rays_final >> (this.iterations - this.iter)); - let num_probes = renderer.updateProbes(this.doc.scene, this.probe_grid, this.probe_idx, num_rays, 0.5, 1.0); - this.probe_idx += num_probes; - if (this.probe_idx>=this.probe_count) - { - this.probe_idx = 0; - this.iter++; - - if (this.iter >= this.iterations) - { - print("Saving probe-grid."); - let props = this.xml_node.attributes; - let probe_data = "assets/probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let res = probeGridSaver.saveFile(this.probe_grid, probe_data); - if (!res) - { - print("Failed to save probe-grid."); - } - this.doc.probe_grid_bake = null; - } - } - } - } -} - -class GPULODProbeGridBaker -{ - constructor(doc, proxy, xml_node, iterations, num_rays) - { - this.doc = doc; - this.xml_node = xml_node; - - this.cube_target = new CubeRenderTarget(64,64); - this.probe_grid = this.doc.scene.indirectLight; - - print("Constructing visibility information..."); - this.probe_grid.constructVisibility(doc.scene); - - this.probe_count = this.probe_grid.numberOfProbes; - this.probe_idx = 0; - - this.iterations = iterations; - this.num_rays_final = num_rays; - this.iter = 0; - this.check_time = now(); - - } - - render(renderer) - { - let frame_time = now(); - - if (frame_time - this.check_time>=500) - { - print(`Building LOD Probe-Grid, iteration: ${this.iter+1}/${this.iterations}, probe: ${this.probe_idx +1}/${this.probe_count}`); - this.check_time = frame_time; - } - - while(now()-frame_time<10) - { - if (this.doc.lod_probe_grid_bake == null) break; - let num_rays = (this.num_rays_final >> (this.iterations - this.iter)); - let num_probes = renderer.updateProbes(this.doc.scene, this.probe_grid, this.probe_idx, num_rays, 0.5, 1.0); - this.probe_idx += num_probes; - if (this.probe_idx>=this.probe_count) - { - this.probe_idx = 0; - this.iter++; - - if (this.iter >= this.iterations) - { - print("Saving probe-grid."); - let props = this.xml_node.attributes; - let probe_data = "assets/lod_probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - let res = LODProbeGridSaver.saveFile(this.probe_grid, probe_data); - if (!res) - { - print("Failed to save probe-grid."); - } - this.doc.lod_probe_grid_bake = null; - } - } - } - - } - -} - -// Tags -const create_default_controls = (doc)=>{ - if (doc.controls) - doc.controls.dispose(); - doc.controls = new OrbitControls(doc.camera, doc.view); - doc.controls.enableDamping = true; - doc.controls.target.set(0, 1.5, 0); -} - -const create_default_sky = (doc)=>{ - let bg = new HemisphereBackground(); - bg.setSkyColor(0.318, 0.318, 0.318); - bg.setGroundColor(0.01, 0.025, 0.025); - doc.scene.background = bg; -} - -const create_default_env_light = (doc) =>{ - let envLight = new HemisphereLight(); - envLight.setSkyColor(0.318, 0.318, 0.318); - envLight.setGroundColor(0.01, 0.025, 0.025); - doc.scene.indirectLight = envLight; -} - -const scene = { - reset: (doc) => { - doc.scene = new Scene(); - }, - create: (doc, props, mode, parent) => { - doc.scene = new Scene(); - create_default_sky(doc); - create_default_env_light(doc); - return doc.scene; - }, - generate: (doc, obj, input) =>{ - generate_lightmap(doc, input); - } -} - -const camera = { - reset: (doc) => { - doc.camera = new PerspectiveCamera(45, doc.width / doc.height, 0.1, 100); - doc.camera.setPosition(0, 1.5, 5.0); - }, - - create: (doc, props, mode, parent) => { - let fov = 50.0; - let near = 0.1; - let far = 200.0; - if (props.hasOwnProperty("fov")) - { - fov = parseFloat(props.fov); - } - if (props.hasOwnProperty("near")) - { - near = parseFloat(props.near); - } - if (props.hasOwnProperty("far")) - { - far = parseFloat(props.far); - } - doc.camera = new PerspectiveCamera(fov, doc.width / doc.height, near, far); - create_default_controls(doc); - return doc.camera; - }, - - remove: (doc, obj) => { - camera.reset(doc); - create_default_controls(doc); - } -} - -const control = { - reset: (doc) => { - create_default_controls(doc); - }, - create: (doc, props, mode, parent) =>{ - let type = 'orbit'; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == 'orbit') - { - let from_x = 0.0; - let from_y = 1.5; - let from_z = 5.0; - if (props.hasOwnProperty("look_from")) - { - let look_from = props.look_from.split(','); - from_x = parseFloat(look_from[0]); - from_y = parseFloat(look_from[1]); - from_z = parseFloat(look_from[2]); - } - - let to_x = 0.0; - let to_y = 1.5; - let to_z = 0.0; - if (props.hasOwnProperty("look_at")) - { - let look_at = props.look_at.split(','); - to_x = parseFloat(look_at[0]); - to_y = parseFloat(look_at[1]); - to_z = parseFloat(look_at[2]); - } - - doc.camera.setPosition(from_x, from_y, from_z); - if (doc.controls != null) - doc.controls.dispose(); - doc.controls = new OrbitControls(doc.camera, doc.view); - doc.controls.enableDamping = true; - doc.controls.target.set(to_x, to_y, to_z); - } - return doc.controls; - }, - remove: (doc, obj) => { - create_default_controls(doc); - } - -} - -const fog = { - create: (doc, props, mode, parent) =>{ - doc.scene.fog = new Fog(); - if (props.hasOwnProperty("density")) - { - doc.scene.fog.density = parseFloat(props.density); - } - return doc.scene.fog; - }, - tuning: (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("density" in input) - { - let density = input.density; - props.density = density; - obj.density = parseFloat(density); - } - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - return ""; - }, - remove: (doc, fog) => { - doc.scene.fog = null; - } -} - -const create_uniform_sky = (doc, props) => { - let bg = new ColorBackground(); - let envLight = null; - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setColor(r,g,b); - } - doc.scene.background = bg; - return bg; -} - -const create_hemisphere_sky = (doc, props)=>{ - let bg = new HemisphereBackground(); - - if (props.hasOwnProperty('skyColor')) - { - const color = props.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setSkyColor(r,g,b); - } - - if (props.hasOwnProperty('groundColor')) - { - const color = props.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - bg.setGroundColor(r,g,b); - - } - - doc.scene.background = bg; - return bg; -} - -const create_cube_sky = (doc, props)=>{ - let bg = new CubeBackground(); - - let url = "assets/textures"; - let posx = "face0.jpg"; - let negx = "face1.jpg"; - let posy = "face2.jpg"; - let negy = "face3.jpg"; - let posz = "face4.jpg"; - let negz = "face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - if (cube_img!=null) - { - bg.setCubemap(cube_img); - } - doc.scene.background = bg; - - return bg; -} - -const create_background_scene = (doc, props)=>{ - let path_scene = "terrain.xml"; - if (props.hasOwnProperty('scene')) - { - path_scene = props.scene; - } - - let near = 10.0; - let far = 10000.0; - if (props.hasOwnProperty('near')) - { - near = parseFloat(props.near); - } - if (props.hasOwnProperty('far')) - { - far = parseFloat(props.far); - } - - let bg_doc = new BackgroundDocument(near, far); - bg_doc.load_local_xml(path_scene); - doc.scene.background = bg_doc; - - return bg_doc; -} - -const tuning_uniform_sky = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } -} - -const tuning_hemisphere_sky = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("skyColor" in input) - { - props.skyColor = input.skyColor; - const color = input.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setSkyColor(r,g,b); - } - - if ("groundColor" in input) - { - props.groundColor = input.groundColor; - const color = input.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setGroundColor(r,g,b); - } -} - -const tuning_cube_sky = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - let reload = false; - if ("path" in input) - { - props.path = input.path; - reload = true; - } - if ("posx" in input) - { - props.posx = input.posx; - reload = true; - } - if ("negx" in input) - { - props.negx = input.negx; - reload = true; - } - if ("posy" in input) - { - props.posy = input.posy; - reload = true; - } - if ("negy" in input) - { - props.negy = input.negy; - reload = true; - } - if ("posz" in input) - { - props.posz = input.posz; - reload = true; - } - if ("negz" in input) - { - props.negz = input.negz; - reload = true; - } - if (reload) - { - const url = props.path; - - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+props.posx, url+"/"+props.negx, - url+"/"+props.posy, url+"/"+props.negy, - url+"/"+props.posz, url+"/"+props.negz); - - obj.setCubemap(cube_img); - } -} - -const tuning_background_scene = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("scene" in input) - { - props.scene = input.scene; - obj.load_local_xml(input.scene); - } - if ("near" in input) - { - props.near = input.near; - obj.near = parseFloat(input.near); - } - if ("far" in input) - { - props.far = input.far; - obj.far = parseFloat(input.far); - } -} - -const sky = { - reset: (doc) => { - create_default_sky(doc); - }, - create: (doc, props, mode, parent) => { - let type = "hemisphere" - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == "uniform") - { - return create_uniform_sky(doc,props); - } - else if (type == "hemisphere") - { - return create_hemisphere_sky(doc,props); - } - else if (type == "cube") - { - return create_cube_sky(doc,props); - } - else if (type == "scene") - { - return create_background_scene(doc,props); - } - }, - remove: (doc, obj) => { - create_default_sky(doc); - }, - tuning: (doc, obj, input) => { - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - if (input.hasOwnProperty('type')) - { - node.attributes = {}; - node.attributes.type = input.type; - doc.external_index.index[key].attributes = node.attributes; - let obj_new = sky.create(doc, node.attributes, "local", doc.scene); - obj_new.uuid = key; - obj_new.tag = "sky"; - doc.internal_index[key].obj = obj_new; - return JSON.stringify(node.attributes); - } - else - { - let props = node.attributes; - let type = "hemisphere"; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == "uniform") - { - tuning_uniform_sky(doc, obj, input); - } - else if (type=="hemisphere") - { - tuning_hemisphere_sky(doc, obj, input); - } - else if (type=="cube") - { - tuning_cube_sky(doc, obj, input); - } - else if (type=="scene") - { - tuning_background_scene(doc, obj, input); - } - } - return "" - } -} - -const create_uniform_env_light = (doc, props) => { - let envLight = new AmbientLight(); - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setColor(r,g,b); - } - doc.scene.indirectLight = envLight; - return envLight; -} - -const create_hemisphere_env_light = (doc, props) => { - let envLight = new HemisphereLight(); - - if (props.hasOwnProperty('skyColor')) - { - const color = props.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setSkyColor(r,g,b); - } - - if (props.hasOwnProperty('groundColor')) - { - const color = props.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - envLight.setGroundColor(r,g,b); - } - doc.scene.indirectLight = envLight; - return envLight; -} - -const create_cube_env_light = (doc, props) => { - const proxy = new SimpleModel(); - proxy.createBox(0.3, 0.3, 0.3); - - if (props.hasOwnProperty('probe_position')) - { - const position = props.probe_position.split(','); - proxy.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - proxy.setColor(0.7,0.0,0.7); - doc.scene.addWidget(proxy); - - let irradiance_only = false; - if (props.hasOwnProperty('irradiance_only')) - { - irradiance_only = string_to_boolean(props.irradiance_only); - } - - if (irradiance_only) - { - let path_sh = "assets/sh.json"; - if (props.hasOwnProperty('path_sh')) - { - path_sh = props.path_sh; - } - - let envLight = new EnvironmentMap(); - let text = fileLoader.loadTextFile(path_sh); - if (text!=null) - { - envLight.shCoefficients = JSON.parse(text); - } - doc.scene.indirectLight = envLight; - } - else - { - let url = "assets/textures"; - let posx = "env_face0.jpg"; - let negx = "env_face1.jpg"; - let posy = "env_face2.jpg"; - let negy = "env_face3.jpg"; - let posz = "env_face4.jpg"; - let negz = "env_face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - if (posx.split('.').pop()=="hdr") - { - let cube_img = HDRImageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - doc.scene.indirectLight = envLight; - } - else - { - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - doc.scene.indirectLight = envLight; - } - } - - return proxy; -} - -const create_probe_grid = (doc, props) => { - const proxy = new ProbeGridWidget(); - if (props.hasOwnProperty('divisions')) - { - const divisions = props.divisions.split(','); - proxy.setDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - if (props.hasOwnProperty('coverage_min')) - { - const coverage_min = props.coverage_min.split(','); - proxy.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - if (props.hasOwnProperty('coverage_max')) - { - const coverage_max = props.coverage_max.split(','); - proxy.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - if (props.hasOwnProperty('ypower')) - { - proxy.ypower = parseFloat(props.ypower); - } - doc.scene.addWidget(proxy); - - let probe_data = "assets/probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - - let probe_grid = probeGridLoader.loadFile(probe_data); - if (probe_grid == null) - { - probe_grid = new ProbeGrid(); - probe_grid.setDivisions(proxy.divisions); - probe_grid.setCoverageMin(proxy.coverageMin); - probe_grid.setCoverageMax(proxy.coverageMax); - probe_grid.ypower = proxy.ypower; - } - else - { - proxy.setDivisions(probe_grid.divisions); - proxy.setCoverageMin(probe_grid.coverageMin); - proxy.setCoverageMax(probe_grid.coverageMax); - proxy.ypower = probe_grid.ypower; - - props.divisions = `${probe_grid.divisions.x}, ${probe_grid.divisions.y}, ${probe_grid.divisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.ypower = `${probe_grid.ypower}`; - } - - if (props.hasOwnProperty('normal_bias')) - { - probe_grid.normalBias = parseFloat(props.normal_bias); - } - - if (props.hasOwnProperty('per_primitive')) - { - probe_grid.perPrimitive =string_to_boolean(props.per_primitive); - } - - doc.scene.indirectLight = probe_grid; - - return proxy; -} - -const create_lod_probe_grid = (doc, props) => { - const proxy = new LODProbeGridWidget(); - if (props.hasOwnProperty('base_divisions')) - { - const divisions = props.base_divisions.split(','); - proxy.setBaseDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - if (props.hasOwnProperty('coverage_min')) - { - const coverage_min = props.coverage_min.split(','); - proxy.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - if (props.hasOwnProperty('coverage_max')) - { - const coverage_max = props.coverage_max.split(','); - proxy.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - proxy.subDivisionLevel = 2; - if (props.hasOwnProperty('sub_division_level')) - { - proxy.subDivisionLevel = parseInt(props.sub_division_level); - } - - doc.scene.addWidget(proxy); - - let probe_data = "assets/lod_probes.dat"; - if (props.hasOwnProperty('probe_data')) - { - probe_data = props.probe_data; - } - - let probe_grid = LODProbeGridLoader.loadFile(probe_data); - if (probe_grid == null) - { - probe_grid = new LODProbeGrid(); - probe_grid.setBaseDivisions(proxy.baseDivisions); - probe_grid.setCoverageMin(proxy.coverageMin); - probe_grid.setCoverageMax(proxy.coverageMax); - probe_grid.subDivisionLevel = proxy.subDivisionLevel; - } - else - { - proxy.setBaseDivisions(probe_grid.baseDivisions); - proxy.setCoverageMin(probe_grid.coverageMin); - proxy.setCoverageMax(probe_grid.coverageMax); - proxy.subDivisionLevel = probe_grid.subDivisionLevel; - - props.base_divisions = `${probe_grid.baseDivisions.x}, ${probe_grid.baseDivisions.y}, ${probe_grid.baseDivisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.sub_division_level = `${probe_grid.subDivisionLevel}`; - } - proxy.probeGrid = probe_grid; - - if (props.hasOwnProperty('normal_bias')) - { - probe_grid.normalBias = parseFloat(props.normal_bias); - } - - if (props.hasOwnProperty('per_primitive')) - { - probe_grid.perPrimitive =string_to_boolean(props.per_primitive); - } - - doc.scene.indirectLight = probe_grid; - - return proxy; -} - -const tuning_ambient_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - return ""; -} - - -const tuning_hemisphere_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("skyColor" in input) - { - props.skyColor = input.skyColor; - const color = input.skyColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setSkyColor(r,g,b); - } - - if ("groundColor" in input) - { - props.groundColor = input.groundColor; - const color = input.groundColor.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setGroundColor(r,g,b); - } - - return "" -} - -const tuning_cube_env_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("probe_position" in input) - { - let probe_position = input.probe_position; - props.probe_position = probe_position; - let position = probe_position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - let reload = false; - - if ("irradiance_only" in input) - { - props.irradiance_only = input.irradiance_only; - reload = true; - } - - if ("path" in input) - { - props.path = input.path; - reload = true; - } - if ("posx" in input) - { - props.posx = input.posx; - reload = true; - } - if ("negx" in input) - { - props.negx = input.negx; - reload = true; - } - if ("posy" in input) - { - props.posy = input.posy; - reload = true; - } - if ("negy" in input) - { - props.negy = input.negy; - reload = true; - } - if ("posz" in input) - { - props.posz = input.posz; - reload = true; - } - if ("negz" in input) - { - props.negz = input.negz; - reload = true; - } - - if ("path_sh" in input) - { - props.path_sh = input.path_sh; - reload = true; - } - - if (reload) - { - let irradiance_only = false; - if (props.hasOwnProperty('irradiance_only')) - { - irradiance_only = string_to_boolean(props.irradiance_only); - } - - if (irradiance_only ) - { - let path_sh = "assets/sh.json"; - if (props.hasOwnProperty('path_sh')) - { - path_sh = props.path_sh; - } - - let envLight = new EnvironmentMap(); - let text = fileLoader.loadTextFile(path_sh); - if (text!=null) - { - envLight.shCoefficients = JSON.parse(text); - } - doc.scene.indirectLight = envLight; - } - else - { - let url = "assets/textures"; - let posx = "env_face0.jpg"; - let negx = "env_face1.jpg"; - let posy = "env_face2.jpg"; - let negy = "env_face3.jpg"; - let posz = "env_face4.jpg"; - let negz = "env_face5.jpg"; - - if (props.hasOwnProperty('path')) - { - url = props.path; - } - if (props.hasOwnProperty('posx')) - { - posx = props.posx; - } - if (props.hasOwnProperty('negx')) - { - negx = props.negx; - } - if (props.hasOwnProperty('posy')) - { - posy = props.posy; - } - if (props.hasOwnProperty('negy')) - { - negy = props.negy; - } - if (props.hasOwnProperty('posz')) - { - posz = props.posz; - } - if (props.hasOwnProperty('negz')) - { - negz = props.negz; - } - - if (posx.split('.').pop()=="hdr") - { - let cube_img = HDRImageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - - if (props.hasOwnProperty('dynamic_map')) - { - envLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = envLight; - } - else - { - - let cube_img = imageLoader.loadCubeFromFile( - url+"/"+posx, url+"/"+negx, - url+"/"+posy, url+"/"+negy, - url+"/"+posz, url+"/"+negz); - - let envLight = null; - if (cube_img!=null) - { - let envMapCreator = new EnvironmentMapCreator(); - envLight = envMapCreator.create(cube_img); - } - else - { - envLight = new EnvironmentMap(); - } - - if (props.hasOwnProperty('dynamic_map')) - { - envLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = envLight; - } - } - } - return ""; -} - -const tuning_probe_grid = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("probe_data" in input) - { - props.probe_data = input.probe_data; - - let probe_grid = probeGridLoader.loadFile(input.probe_data); - if (probe_grid == null) - { - probe_grid = new ProbeGrid(); - probe_grid.setDivisions(obj.divisions); - probe_grid.setCoverageMin(obj.coverageMin); - probe_grid.setCoverageMax(obj.coverageMax); - probe_grid.ypower = obj.ypower; - } - else - { - obj.setDivisions(probe_grid.divisions); - obj.setCoverageMin(probe_grid.coverageMin); - obj.setCoverageMax(probe_grid.coverageMax); - obj.ypower = probe_grid.ypower; - - props.divisions = `${probe_grid.divisions.x}, ${probe_grid.divisions.y}, ${probe_grid.divisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.ypower = `${probe_grid.ypower}`; - } - - if (props.hasOwnProperty('dynamic_map')) - { - probe_grid.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = probe_grid; - - return JSON.stringify(props); - } - - if ("divisions" in input) - { - props.divisions = input.divisions; - let divisions = input.divisions.split(','); - obj.setDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - - if ("coverage_min" in input) - { - props.coverage_min = input.coverage_min; - let coverage_min = input.coverage_min.split(','); - obj.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - - if ("coverage_max" in input) - { - props.coverage_max = input.coverage_max; - let coverage_max = input.coverage_max.split(','); - obj.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - - if ("ypower" in input) - { - props.ypower = input.ypower; - obj.ypower = parseFloat(input.ypower); - } - - if ("normal_bias" in input) - { - props.normal_bias = input.normal_bias; - doc.scene.indirectLight.normalBias = parseFloat(input.normal_bias); - } - - if ("per_primitive" in input) - { - props.per_primitive = input.per_primitive; - doc.scene.indirectLight.perPrimitive =string_to_boolean(input.per_primitive); - } - - if ("auto_area" in input) - { - let aabb = doc.scene.getBoundingBox(); - let minPos = aabb.minPos; - let maxPos = aabb.maxPos; - let size_x = maxPos.x - minPos.x; - let size_y = maxPos.y - minPos.y; - let size_z = maxPos.z - minPos.z; - let div_x = Math.ceil(size_x); if (div_x<2) div_x = 2; - let div_y = Math.ceil(size_y); if (div_y<2) div_y = 2; - let div_z = Math.ceil(size_z); if (div_z<2) div_z = 2; - obj.setDivisions(div_x, div_y, div_z); - obj.setCoverageMin(minPos); - obj.setCoverageMax(maxPos); - props.divisions = `${div_x}, ${div_y}, ${div_z}`; - props.coverage_min = `${minPos.x}, ${minPos.y}, ${minPos.z}`; - props.coverage_max = `${maxPos.x}, ${maxPos.y}, ${maxPos.z}`; - let ret = { divisions: props.divisions, coverage_min: props.coverage_min, coverage_max: props.coverage_max }; - return JSON.stringify(ret); - } - - return ""; - -} - -const tuning_lod_probe_grid = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("probe_data" in input) - { - props.probe_data = input.probe_data; - - let probe_grid = LODProbeGridLoader.loadFile(input.probe_data); - if (probe_grid == null) - { - probe_grid = new LODProbeGrid(); - probe_grid.setBaseDivisions(obj.baseDivisions); - probe_grid.setCoverageMin(obj.coverageMin); - probe_grid.setCoverageMax(obj.coverageMax); - probe_grid.subDivisionLevel = obj.subDivisionLevel; - } - else - { - obj.setBaseDivisions(probe_grid.baseDivisions); - obj.setCoverageMin(probe_grid.coverageMin); - obj.setCoverageMax(probe_grid.coverageMax); - obj.subDivisionLevel = probe_grid.subDivisionLevel; - - props.base_divisions = `${probe_grid.baseDivisions.x}, ${probe_grid.baseDivisions.y}, ${probe_grid.baseDivisions.z}`; - props.coverage_min = `${probe_grid.coverageMin.x}, ${probe_grid.coverageMin.y}, ${probe_grid.coverageMin.z}`; - props.coverage_max = `${probe_grid.coverageMax.x}, ${probe_grid.coverageMax.y}, ${probe_grid.coverageMax.z}`; - props.sub_division_level = `${probe_grid.subDivisionLevel}`; - } - obj.probeGrid = probe_grid; - - if (props.hasOwnProperty('dynamic_map')) - { - probe_grid.dynamicMap = string_to_boolean(props.dynamic_map); - } - - doc.scene.indirectLight = probe_grid; - - return JSON.stringify(props); - } - - if ("base_divisions" in input) - { - props.base_divisions = input.base_divisions; - let divisions = input.base_divisions.split(','); - obj.setBaseDivisions(parseInt(divisions[0]), parseInt(divisions[1]), parseInt(divisions[2])); - } - - if ("coverage_min" in input) - { - props.coverage_min = input.coverage_min; - let coverage_min = input.coverage_min.split(','); - obj.setCoverageMin(parseFloat(coverage_min[0]), parseFloat(coverage_min[1]), parseFloat(coverage_min[2])); - } - - if ("coverage_max" in input) - { - props.coverage_max = input.coverage_max; - let coverage_max = input.coverage_max.split(','); - obj.setCoverageMax(parseFloat(coverage_max[0]), parseFloat(coverage_max[1]), parseFloat(coverage_max[2])); - } - - if ("sub_division_level" in input) - { - props.sub_division_level = input.sub_division_level; - obj.subDivisionLevel = parseInt(input.sub_division_level); - } - - if ("normal_bias" in input) - { - props.normal_bias = input.normal_bias; - obj.probeGrid.normalBias = parseFloat(input.normal_bias); - } - - if ("per_primitive" in input) - { - props.per_primitive = input.per_primitive; - obj.probeGrid.perPrimitive =string_to_boolean(input.per_primitive); - } - - if ("auto_area" in input) - { - let aabb = doc.scene.getBoundingBox(); - let minPos = aabb.minPos; - let maxPos = aabb.maxPos; - let size_x = maxPos.x - minPos.x; - let size_y = maxPos.y - minPos.y; - let size_z = maxPos.z - minPos.z; - let div_x = Math.ceil(size_x / 4); if (div_x<2) div_x = 2; - let div_y = Math.ceil(size_y / 4); if (div_y<2) div_y = 2; - let div_z = Math.ceil(size_z / 4); if (div_z<2) div_z = 2; - obj.setBaseDivisions(div_x, div_y, div_z); - obj.setCoverageMin(minPos); - obj.setCoverageMax(maxPos); - obj.subDivisionLevel = 2; - props.base_divisions = `${div_x}, ${div_y}, ${div_z}`; - props.coverage_min = `${minPos.x}, ${minPos.y}, ${minPos.z}`; - props.coverage_max = `${maxPos.x}, ${maxPos.y}, ${maxPos.z}`; - props.sub_division_level = "2"; - let ret = { base_divisions: props.base_divisions, coverage_min: props.coverage_min, coverage_max: props.coverage_max, sub_division_level: "2" }; - return JSON.stringify(ret); - } - - return ""; - -} - -const initialize_lod_probe_grid = (doc, obj, input) =>{ - let probe_grid = obj.probeGrid; - - doc.lod_probe_grid_bake = null; - probe_grid.setBaseDivisions(obj.baseDivisions); - probe_grid.setCoverageMin(obj.coverageMin); - probe_grid.setCoverageMax(obj.coverageMax); - probe_grid.subDivisionLevel = obj.subDivisionLevel; - probe_grid.initialize(doc.renderer, doc.scene); - return probe_grid.numberOfProbes; -} - - -const generate_lightmap = (doc, input) =>{ - let iterations = parseInt(input.iterations); - let num_rays = parseInt(input.num_rays); - doc.lightmap_bake = new LightmapBaker(doc, iterations, num_rays) -} - -const generate_cube_env_light = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - let irradiance_only = false; - if (props.hasOwnProperty('irradiance_only')) - { - irradiance_only = string_to_boolean(props.irradiance_only); - } - - if (!irradiance_only) - { - props.path = input.path; - props.posx = input.posx; - props.negx = input.negx; - props.posy = input.posy; - props.negy = input.negy; - props.posz = input.posz; - props.negz = input.negz; - } - doc.env_gen = new EnvMapGen(doc, obj, node, irradiance_only); -} - -const generate_probe_grid = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let iterations = parseInt(input.iterations); - let num_rays = parseInt(input.num_rays); - doc.probe_grid_bake = new GPUProbeGridBaker(doc, obj, node, iterations, num_rays); -} - - -const generate_lod_probe_grid = (doc, obj, input) =>{ - initialize_lod_probe_grid(doc, obj, input); - let node = doc.internal_index[obj.uuid].xml_node; - let iterations = parseInt(input.iterations); - let num_rays = parseInt(input.num_rays); - doc.lod_probe_grid_bake = new GPULODProbeGridBaker(doc, obj, node, iterations, num_rays); -} - -const env_light = { - reset: (doc) => { - create_default_env_light(doc); - }, - create: (doc, props, mode, parent) => { - let type = "hemisphere" - if (props.hasOwnProperty("type")) - { - type = props.type; - } - - let ret = null; - - if (type == "uniform") - { - ret = create_uniform_env_light(doc,props); - } - else if (type == "hemisphere") - { - ret = create_hemisphere_env_light(doc,props); - } - else if (type == "cube") - { - ret = create_cube_env_light(doc,props); - } - else if (type == "probe_grid") - { - ret = create_probe_grid(doc, props); - } - else if (type == "lod_probe_grid") - { - ret = create_lod_probe_grid(doc, props); - } - - if (props.hasOwnProperty('dynamic_map')) - { - doc.scene.indirectLight.dynamicMap = string_to_boolean(props.dynamic_map); - } - return ret; - }, - remove: (doc, obj) => { - create_default_env_light(doc); - - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - let props = node.attributes; - let type = "hemisphere" - if (props.hasOwnProperty("type")) - { - type = props.type; - } - - if (type == "cube" || type =="probe_grid" || type == "lod_probe_grid") - { - doc.scene.removeWidget(obj); - } - - }, - - tuning: (doc, obj, input) => { - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - if (input.hasOwnProperty('type')) - { - doc.remove(obj); - node.attributes = {}; - node.attributes.type = input.type; - doc.external_index.index[key].attributes = node.attributes; - let obj_new = env_light.create(doc, node.attributes, "local", doc.scene); - obj_new.uuid = key; - obj_new.tag = "env_light"; - doc.internal_index[key].obj = obj_new; - return JSON.stringify(node.attributes); - } - else - { - let props = node.attributes; - - if (input.hasOwnProperty('dynamic_map')) - { - props.dynamic_map = input.dynamic_map; - doc.scene.indirectLight.dynamicMap = string_to_boolean(input.dynamic_map); - return "" - } - - let type = "hemisphere"; - if (props.hasOwnProperty("type")) - { - type = props.type; - } - if (type == "uniform") - { - return tuning_ambient_light(doc, obj, input); - } - else if (type=="hemisphere") - { - return tuning_hemisphere_light(doc, obj, input); - } - else if (type=="cube") - { - return tuning_cube_env_light(doc,obj,input); - } - else if (type == "probe_grid") - { - return tuning_probe_grid(doc,obj,input); - } - else if (type == "lod_probe_grid") - { - return tuning_lod_probe_grid(doc,obj,input); - } - } - - }, - - initialize: (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if (props.type == "lod_probe_grid") - { - return initialize_lod_probe_grid(doc,obj,input); - } - return ""; - }, - - generate: (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if (props.type == "cube") - { - generate_cube_env_light(doc,obj,input); - } - else if (props.type == "probe_grid") - { - generate_probe_grid(doc,obj,input); - } - else if (props.type == "lod_probe_grid") - { - generate_lod_probe_grid(doc,obj,input); - } - } - -} - - -const tuning_object3d = (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("name" in input) - { - props.name = input.name; - obj.name = input.name; - } - if ("position" in input) - { - props.position = input.position; - let position = input.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - if ("rotation" in input) - { - props.rotation = input.rotation; - let rotation = input.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - if ("scale" in input) - { - props.scale = input.scale; - let scale = input.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - if ('is_building' in input) - { - props.is_building = input.is_building; - obj.isBuilding = string_to_boolean(input.is_building); - } -} - -const tuning_material = (doc, obj, input) =>{ - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if ("texture" in input) - { - props.texture = input.texture; - let img = imageLoader.loadFile(input.texture); - obj.setColorTexture(img); - } - - if ("metalness" in input) - { - let metalness = input.metalness; - props.metalness = metalness; - obj.metalness = parseFloat(metalness); - } - - if ("roughness" in input) - { - let roughness = input.roughness; - props.roughness = roughness; - obj.roughness = parseFloat(roughness); - } -} - -const group = { - create: (doc, props, mode, parent) => { - const group = new Object3D(); - if (parent != null) { - parent.add(group); - } - else { - doc.scene.add(group); - } - return group; - }, - - tuning: (doc, obj, input) => { - tuning_object3d(doc, obj, input); - return ""; - } -} - -const plane = { - create: (doc, props, mode, parent) => { - let width = 1.0; - let height = 1.0; - if (props.hasOwnProperty('size')) - { - let size = props.size.split(','); - width = parseFloat(size[0]); - height = parseFloat(size[1]); - } - - const plane = new SimpleModel(); - plane.createPlane(width, height); - - if (parent != null) { - parent.add(plane); - } - else { - doc.scene.add(plane); - } - return plane; - }, - - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("size" in input) - { - props.size = input.size; - let size = input.size.split(','); - let width = parseFloat(size[0]); - let height = parseFloat(size[1]); - obj.createPlane(width, height); - } - tuning_object3d(doc, obj, input); - tuning_material(doc, obj, input); - return ""; - } -} - - -const box = { - create: (doc, props, mode, parent) => { - let width = 1.0; - let height = 1.0; - let depth = 1.0; - if (props.hasOwnProperty('size')) - { - let size = props.size.split(','); - width = parseFloat(size[0]); - height = parseFloat(size[1]); - depth = parseFloat(size[2]); - } - - const box = new SimpleModel(); - box.createBox(width, height, depth); - - if (parent != null) { - parent.add(box); - } - else { - doc.scene.add(box); - } - return box; - }, - - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - if ("size" in input) - { - props.size = input.size; - let size = input.size.split(','); - let width = parseFloat(size[0]); - let height = parseFloat(size[1]); - let depth = parseFloat(size[2]); - obj.createBox(width, height, depth); - } - tuning_object3d(doc, obj, input); - tuning_material(doc, obj, input); - return ""; - } -} - -const sphere = { - create: (doc, props, mode, parent) => { - let radius = 1.0; - if (props.hasOwnProperty('radius')) - { - radius = parseFloat(props.radius); - } - let widthSegments = 32; - if (props.hasOwnProperty('widthSegments')) - { - widthSegments = parseInt(props.widthSegments); - } - let heightSegments = 16; - if (props.hasOwnProperty('heightSegments')) - { - heightSegments = parseInt(props.heightSegments); - } - - const sphere = new SimpleModel(); - sphere.createSphere(radius, widthSegments, heightSegments); - - if (parent != null) { - parent.add(sphere); - } - else { - doc.scene.add(sphere); - } - return sphere; - }, - - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - let to_create = false; - - let radius = 1.0; - if ("radius" in input) - { - props.radius = input.radius; - radius = parseFloat(input.radius); - to_create = true; - } - - let widthSegments = 32; - if ("widthSegments" in input) - { - props.widthSegments = input.widthSegments; - widthSegments = parseInt(input.widthSegments); - to_create = true; - } - - let heightSegments = 16; - if ("heightSegments" in input) - { - props.heightSegments = input.heightSegments; - heightSegments = parseInt(input.heightSegments); - to_create = true; - } - - if (to_create) - { - obj.createSphere(radius, widthSegments, heightSegments); - } - - tuning_object3d(doc, obj, input); - tuning_material(doc, obj, input); - return ""; - } -} - -const model = { - create: (doc, props, mode, parent) => { - let url = "assets/models/model.glb"; - if (props.hasOwnProperty('src')) - { - url = props.src; - } - let model = gltfLoader.loadModelFromFile(url); - if (model == null) - { - model= new SimpleModel(); - model.createBox(0.5, 1.5, 0.5); - model.setColor(0.7,0.0,0.7); - } - else - { - if (props.hasOwnProperty('is_building') && string_to_boolean(props.is_building)) - { - model.batchPrimitives(); - } - - if (model.isBakable) - { - doc.bakables.push(model); - - if (props.hasOwnProperty('lightmap')) - { - let filename = props.lightmap; - let ext = filename.split('.').pop().toLowerCase(); - if (ext=="hdr") - { - let hdr_img = HDRImageLoader.loadFile(filename); - if (hdr_img!=null) - { - model.setLightmap(hdr_img); - } - } - else if (ext=="dds") - { - let dds_img = DDSImageLoader.loadFile(filename); - if (dds_img!=null) - { - model.setLightmap(dds_img); - } - } - else if (ext=="png" || ext == "webp") - { - let img = imageLoader.loadFile(filename); - if (img!=null) - { - let hdr_img = HDRImageLoader.fromRGBM(img); - model.setLightmap(hdr_img); - } - } - else if (ext=="csv") - { - let text = fileLoader.loadTextFile(filename); - if (text!=null) - { - let path = filename.match(/(.*)[\/\\]/)[1]||''; - let images = []; - let ranges = []; - let lines = text.split(/\r?\n/); - for(let line of lines) - { - let fields = line.split(","); - if (fields.length<7) continue; - let fn_img = fields[0]; - let img = imageLoader.loadFile(path + "/" + fn_img); - if (img == null) continue; - let low = new Vector3(parseFloat(fields[1]), parseFloat(fields[2]), parseFloat(fields[3])); - let high = new Vector3(parseFloat(fields[4]), parseFloat(fields[5]), parseFloat(fields[6])); - images.push(img); - ranges.push({low, high}); - } - let hdr_img = HDRImageLoader.fromImages(images, ranges); - model.setLightmap(hdr_img); - } - } - } - } - } - - - if (parent != null) { - parent.add(model); - } - else { - doc.scene.add(model); - } - return model; - }, - - tuning: (doc, obj, input) => { - let key = obj.uuid; - let node = doc.internal_index[key].xml_node; - let props = node.attributes; - if (input.hasOwnProperty('src')) - { - doc.remove(obj); - props.src = input.src; - let obj_new = model.create(doc, props, "local", obj.parent); - obj_new.uuid = key; - obj_new.tag = "model"; - - if (props.hasOwnProperty('name')) - { - obj_new.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj_new.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj_new.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj_new.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - obj_new.setToonShading(16, 5.0, new Vector3(1.0, 1.0, 0.2)); - - doc.internal_index[key].obj = obj_new; - } - else - { - if ("is_building" in input) - { - props.is_building = input.is_building; - if (string_to_boolean(props.is_building)) - { - obj.batchPrimitives(); - } - } - - if ("lightmap" in input) - { - props.lightmap = input.lightmap; - if (obj.isBakable) - { - let filename = input.lightmap; - let ext = filename.split('.').pop().toLowerCase(); - if (ext=="hdr") - { - let hdr_img = HDRImageLoader.loadFile(filename); - if (hdr_img!=null) - { - obj.setLightmap(hdr_img); - } - } - else if (ext=="dds") - { - let dds_img = DDSImageLoader.loadFile(filename); - if (dds_img!=null) - { - obj.setLightmap(dds_img); - } - } - else if (ext=="png" || ext == "webp") - { - let img = imageLoader.loadFile(filename); - if (img!=null) - { - let hdr_img = HDRImageLoader.fromRGBM(img); - obj.setLightmap(hdr_img); - } - } - else if (ext=="csv") - { - let text = fileLoader.loadTextFile(filename); - if (text!=null) - { - let path = filename.match(/(.*)[\/\\]/)[1]||''; - let images = []; - let ranges = []; - let lines = text.split(/\r?\n/); - for(let line of lines) - { - let fields = line.split(","); - if (fields.length<7) continue; - let fn_img = fields[0]; - let img = imageLoader.loadFile(path + "/" + fn_img); - if (img == null) continue; - let low = new Vector3(parseFloat(fields[1]), parseFloat(fields[2]), parseFloat(fields[3])); - let high = new Vector3(parseFloat(fields[4]), parseFloat(fields[5]), parseFloat(fields[6])); - images.push(img); - ranges.push({low, high}); - } - let hdr_img = HDRImageLoader.fromImages(images, ranges); - obj.setLightmap(hdr_img); - } - } - } - - } - tuning_object3d(doc, obj, input); - } - return ""; - }, - - generate: (doc, obj, input) =>{ - if (doc.renderer.compressLightmap(doc.scene, obj)) - { - doc.renderer.decompressLightmap(doc.scene, obj); - } - } -} - -const avatar = { - create: (doc, props, mode, parent) => { - let avatar = model.create(doc, { ...props}, mode, parent); - return avatar; - }, - - tuning: (doc, obj, input) => { - model.tuning(doc,obj,input); - return ""; - } -} - - -const directional_light = { - create: (doc, props, mode, parent) => { - const light = new DirectionalLight(); - - if (props.hasOwnProperty('intensity')) { - light.intensity = parseFloat(props.intensity); - } - - if (props.hasOwnProperty('target')){ - let target = doc.scene.getObjectByName(props.target); - light.target = target; - } - - if (props.hasOwnProperty('castShadow') && string_to_boolean(props.castShadow)) - { - let width = 512; - let height = 512; - if (props.hasOwnProperty('size')) { - const size = props.size.split(','); - width = parseInt(size[0]); - height = parseInt(size[1]); - } - light.setShadow(true, width, height); - - if (props.hasOwnProperty('area')) { - const area = props.area.split(','); - let left = parseFloat(area[0]); - let right = parseFloat(area[1]); - let bottom = parseFloat(area[2]); - let top = parseFloat(area[3]); - let near = parseFloat(area[4]); - let far = parseFloat(area[5]); - light.setShadowProjection(left, right, bottom, top, near, far); - } - - if (props.hasOwnProperty('radius')) - { - let radius = parseFloat(props.radius); - light.setShadowRadius(radius); - } - - if (props.hasOwnProperty('bias')) - { - light.bias = parseFloat(props.bias); - } - - if (props.hasOwnProperty('force_cull')) - { - light.forceCull = string_to_boolean(props.force_cull); - } - } - - if (parent != null) { - parent.add(light); - } - else { - doc.scene.add(light); - } - doc.scene.addWidget(light); - return light; - }, - remove: (doc, obj) => { - doc.scene.removeWidget(obj); - }, - tuning: (doc, obj, input) => { - let node = doc.internal_index[obj.uuid].xml_node; - let props = node.attributes; - - if ("intensity" in input) - { - let intensity = input.intensity; - props.intensity = intensity; - obj.intensity = parseFloat(intensity); - } - - if ("color" in input) - { - props.color = input.color; - const color = input.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if ("target" in input) - { - props.target = input.target; - let target = doc.scene.getObjectByName(input.target); - obj.target = target; - } - - if ("castShadow" in input) - { - props.castShadow = input.castShadow; - - let castShadow = string_to_boolean(input.castShadow); - let width = 512; - let height = 512; - if (input.hasOwnProperty('size')) { - props.size = input.size; - let size = input.size.split(','); - width = parseInt(size[0]); - height = parseInt(size[1]); - } - obj.setShadow(castShadow, width, height); - } - - if ("area" in input) - { - props.area = input.area; - const area = input.area.split(','); - let left = parseFloat(area[0]); - let right = parseFloat(area[1]); - let bottom = parseFloat(area[2]); - let top = parseFloat(area[3]); - let near = parseFloat(area[4]); - let far = parseFloat(area[5]); - obj.setShadowProjection(left, right, bottom, top, near, far); - } - - if ("radius" in input) - { - props.radius = input.radius; - let radius = parseFloat(input.radius); - obj.setShadowRadius(radius); - } - - if ("bias" in input) - { - props.bias = input.bias; - obj.bias = parseFloat(input.bias); - } - - if ("force_cull" in input) - { - props.force_cull = input.force_cull; - obj.forceCull = string_to_boolean(input.force_cull); - } - - if ("auto_area" in input) - { - let aabb = obj.getBoundingBox(doc.scene); - let minPos = aabb.minPos; - let maxPos = aabb.maxPos; - obj.setShadowProjection(minPos.x, maxPos.x, minPos.y, maxPos.y, -maxPos.z, -minPos.z); - props.area = `${minPos.x}, ${maxPos.x}, ${minPos.y}, ${maxPos.y}, ${-maxPos.z}, ${-minPos.z}`; - let ret = { area: props.area }; - return JSON.stringify(ret); - } - - tuning_object3d(doc, obj, input); - - return ""; - } -} - -class BackgroundDocument extends BackgroundScene -{ - constructor(near, far) - { - super(null, near, far); - - this.Tags = { scene, sky, env_light, group, plane, box, sphere, model, directional_light }; - this.reset(); - } - - reset() - { - for (let tag in this.Tags) - { - if (this.Tags[tag].hasOwnProperty('reset')) - { - this.Tags[tag].reset(this); - } - } - } - - create(tag, props, mode, parent = null) - { - if (!(tag in this.Tags)) return null; - - const obj = this.Tags[tag].create(this, props, mode, parent); - if (obj == null) return null; - - if (Object.isExtensible(obj)) - { - obj.tag = tag; - } - - if (props.hasOwnProperty('name')) - { - obj.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if (props.hasOwnProperty('texture')) - { - let img = imageLoader.loadFile(props.texture); - if (img!=null) - { - obj.setColorTexture(img); - } - } - - if (props.hasOwnProperty('metalness')) - { - obj.metalness = parseFloat(props.metalness); - } - - if (props.hasOwnProperty('roughness')) - { - obj.roughness = parseFloat(props.roughness); - } - - if (props.hasOwnProperty('is_building')) - { - obj.isBuilding = string_to_boolean(props.is_building); - } - - return obj; - } - - load_xml_node(xmlNode, mode, parent = null) - { - if (parent == null) { - parent = this; - } - for (let child of xmlNode.children) { - const obj = this.create(child.tagName, child.attributes, mode, parent); - if (obj===null) continue; - this.load_xml_node(child, mode, obj); - } - - } - - load_xml(xmlText, mode) - { - const parsed = txml.parse(xmlText); - let root = null; - for (let top of parsed) - { - if (top.tagName == 'document') - { - root = top; - break; - } - } - if (root) - { - this.load_xml_node(root, mode); - } - } - - load_local_xml(filename) - { - const xmlText = fileLoader.loadTextFile(filename); - if (xmlText!=null) - { - this.load_xml(xmlText, "local"); - } - } -} - -export class Document -{ - constructor(view) - { - this.view = view; - this.width = view.clientWidth; - this.height = view.clientHeight; - this.Tags = { scene, camera, fog, sky, env_light, control, group, plane, box, sphere, model, avatar, directional_light }; - this.picked_key = ""; - this.reset(); - } - - setSize(width, height) - { - this.width = width; - this.height = height; - - if (this.camera) - { - this.camera.aspect = width / height; - this.camera.updateProjectionMatrix(); - } - } - - reset() - { - this.saved_text = ""; - - if (this.picked_key!="") - { - gamePlayer.message("object_picked", ""); - this.picked_key = ""; - } - - for (let tag in this.Tags) - { - if (this.Tags[tag].hasOwnProperty('reset')) - { - this.Tags[tag].reset(this); - } - } - - this.internal_index = {}; - this.external_index = {}; - this.external_index.index = {}; - this.bakables = []; - - this.lightmap_bake = null; - this.env_gen = null; - this.probe_grid_bake = null; - this.lod_probe_grid_bake = null; - } - - tick(delta) - { - if (this.controls) - { - if (this.controls.hasOwnProperty('update')) - { - this.controls.update(); - } - } - } - - render(renderer) - { - this.renderer = renderer; - - if (this.lightmap_bake!=null) - { - this.lightmap_bake.render(renderer); - } - - if (this.env_gen!=null) - { - this.env_gen.render(renderer); - } - - if (this.probe_grid_bake!=null) - { - this.probe_grid_bake.render(renderer); - } - - if (this.lod_probe_grid_bake!=null) - { - this.lod_probe_grid_bake.render(renderer); - } - - if (this.scene && this.camera) - { - renderer.render(this.scene, this.camera); - } - } - - create(tag, props, mode, parent = null) - { - if (!(tag in this.Tags)) return null; - - const obj = this.Tags[tag].create(this, props, mode, parent); - if (obj == null) return null; - - obj.uuid = uuid(); - obj.tag = tag; - - if (props.hasOwnProperty('name')) - { - obj.name = props.name; - } - - if (props.hasOwnProperty('position')) - { - const position = props.position.split(','); - obj.setPosition(parseFloat(position[0]), parseFloat(position[1]), parseFloat(position[2])); - } - - if (props.hasOwnProperty('rotation')) - { - const rotation = props.rotation.split(','); - obj.setRotation(parseFloat(rotation[0])* Math.PI / 180.0, parseFloat(rotation[1])* Math.PI / 180.0, parseFloat(rotation[2])* Math.PI / 180.0); - } - - if (props.hasOwnProperty('scale')) - { - const scale = props.scale.split(','); - obj.setScale(parseFloat(scale[0]), parseFloat(scale[1]), parseFloat(scale[2])); - } - - if (props.hasOwnProperty('color')) - { - const color = props.color.split(','); - const r = parseFloat(color[0]); - const g = parseFloat(color[1]); - const b = parseFloat(color[2]); - obj.setColor(r,g,b); - } - - if (props.hasOwnProperty('texture')) - { - let img = imageLoader.loadFile(props.texture); - if (img!=null) - { - obj.setColorTexture(img); - } - } - - if (props.hasOwnProperty('metalness')) - { - obj.metalness = parseFloat(props.metalness); - } - - if (props.hasOwnProperty('roughness')) - { - obj.roughness = parseFloat(props.roughness); - } - - if (props.hasOwnProperty('is_building')) - { - obj.isBuilding = string_to_boolean(props.is_building); - } - - return obj; - } - - remove(obj) - { - if (obj.hasOwnProperty('tag')) { - const tag = this.Tags[obj.tag]; - if (tag.hasOwnProperty('remove')) { - tag.remove(this, obj); - } - } - - { - let index = this.bakables.indexOf(obj); - if (index>=0) - { - this.bakables.splice(index, 1); - } - } - - if (obj.parent) - { - obj.parent.remove(obj); - } - } - - load_xml_node(xmlNode, mode, parent = null) - { - for (let child of xmlNode.children) { - let obj = null; - if (parent == null) - { - obj = this.create(child.tagName, child.attributes, mode, this); - } - else - { - obj = this.create(child.tagName, child.attributes, mode, parent); - } - if (obj===null) continue; - - let key = obj.uuid; - - let internal_node = {}; - internal_node.obj = obj; - internal_node.xml_node = child; - this.internal_index[key] = internal_node; - - let external_node = {}; - external_node.tagName = child.tagName; - external_node.attributes = child.attributes; - external_node.children = []; - - if(child.tagName == "scene") - { - this.external_index.root = key; - } - else if (parent!=null) - { - let parent_key = parent.uuid; - let external_node_parent = this.external_index.index[parent.uuid]; - external_node.parent = parent_key; - external_node_parent.children.push(key); - } - this.external_index.index[key] = external_node; - - this.load_xml_node(child, mode, obj); - } - } - - - load_xml(xmlText, mode) - { - this.xml_nodes = txml.parse(xmlText, {keepComments: true}); - this.saved_text = genXML(this.xml_nodes); - - let root = null; - for (let top of this.xml_nodes) - { - if (top.tagName == 'document') - { - root = top; - break; - } - } - if (root) - { - this.load_xml_node(root, mode); - } - - gamePlayer.message("index_loaded", JSON.stringify(this.external_index)); - } - - is_modified() - { - let gen_xml = genXML(this.xml_nodes); - return gen_xml != this.saved_text; - } - - get_xml() - { - this.saved_text = genXML(this.xml_nodes); - return this.saved_text; - } - - picking(state) - { - if (state) - { - this.controls.enabled = false; - view.addEventListener("pointerdown", picking_pointerdown); - } - else - { - this.controls.enabled = true; - view.removeEventListener("pointerdown", picking_pointerdown); - } - } - - pick_obj(key) - { - let obj = null; - if (key!="") - { - obj = this.internal_index[key].obj; - } - - if (this.picked_key != "") - { - if (this.picked_key in this.internal_index) - { - let picked_obj = this.internal_index[this.picked_key].obj; - if (picked_obj.hasOwnProperty("setToonShading")) - { - picked_obj.setToonShading(0); - } - } - } - - this.picked_key = key; - - if (obj!=null) - { - if (obj.hasOwnProperty("setToonShading")) - { - obj.setToonShading(16, 5.0, new Vector3(1.0, 1.0, 0.2)); - } - } - gamePlayer.message("object_picked", key); - } - - tuning(input) - { - if (this.picked_key=="") return ""; - let picked_obj = this.internal_index[this.picked_key].obj; - let node = this.internal_index[this.picked_key].xml_node; - let tag = node.tagName; - - if (!(tag in this.Tags)) return ""; - return this.Tags[tag].tuning(this, picked_obj, input); - } - - initialize(input) - { - if (this.picked_key=="") return ""; - let picked_obj = this.internal_index[this.picked_key].obj; - let node = this.internal_index[this.picked_key].xml_node; - let tag = node.tagName; - - if (!(tag in this.Tags)) return ""; - return this.Tags[tag].initialize(this, picked_obj, input); - } - - generate(input) - { - if (this.picked_key=="") return; - let picked_obj = this.internal_index[this.picked_key].obj; - let node = this.internal_index[this.picked_key].xml_node; - let tag = node.tagName; - - if (!(tag in this.Tags)) return; - this.Tags[tag].generate(this, picked_obj, input); - } - - req_create(base_key, tag) - { - let internal_node_base = this.internal_index[base_key]; - let external_node_base = this.external_index.index[base_key]; - - let xmlNode = internal_node_base.xml_node; - let parent = internal_node_base.obj; - - let child = {tagName:tag, attributes: {}, children: []}; - xmlNode.children.push(child); - - let obj = this.create(tag, {}, "local", parent); - let key = obj.uuid; - - let internal_node = {}; - internal_node.obj = obj; - internal_node.xml_node = child; - this.internal_index[key] = internal_node; - - let external_node = {tagName:tag, attributes: {}, children: []}; - external_node.parent = base_key; - external_node_base.children.push(key); - this.external_index.index[key] = external_node; - - let msg = {}; - msg[key] = external_node; - - gamePlayer.message("object_created", JSON.stringify(msg)); - - this.pick_obj(key); - } - - req_remove(key) - { - let internal_node = this.internal_index[key]; - let external_node = this.external_index.index[key]; - - let base_key = external_node.parent; - let internal_node_base = this.internal_index[base_key]; - let external_node_base = this.external_index.index[base_key]; - - let xmlNode = internal_node.xml_node; - let xmlNode_parent = internal_node_base.xml_node; - { - let idx = xmlNode_parent.children.indexOf(xmlNode); - if (idx>-1) - { - xmlNode_parent.children.splice(idx, 1); - } - } - - let obj = internal_node.obj; - this.remove(obj); - - { - let idx = external_node_base.children.indexOf(key); - if (idx>-1) - { - external_node_base.children.splice(idx,1); - } - } - - delete this.internal_index[key]; - delete this.external_index.index[key]; - - gamePlayer.message("object_removed", key); - - this.pick_obj(""); - } -} - -function picking_pointerdown(event) -{ - let x = event.clientX; - let y = event.clientY; - - let intersect = gamePlayer.pickObject(x,y); - if (intersect!=null) - { - doc.pick_obj(intersect.uuid); - } - else if (doc.scene.background!=null) - { - doc.pick_obj(doc.scene.background.uuid); - } - else - { - doc.pick_obj(doc.scene.uuid); - } -} - - - diff --git a/GameDev/bin/Release/xmleditor/genXML.js b/GameDev/bin/Release/xmleditor/genXML.js deleted file mode 100644 index 236b355e..00000000 --- a/GameDev/bin/Release/xmleditor/genXML.js +++ /dev/null @@ -1,64 +0,0 @@ -function genNode(node, level) -{ - let code = ""; - for(let i=0;i\n`; - return code; - } - else - { - code += ">\n"; - } - - for (let child of children) - { - code += genNode(child, level+1); - } - - for(let i=0;i\n`; - - return code; -} - -export function genXML(nodes) -{ - let xml = ""; - for (let top of nodes) - { - if (top.tagName =="?xml") - { - let version = top.attributes.version; - xml += `\n`; - } - else - { - xml += genNode(top, 0); - } - - } - return xml; - -} - diff --git a/GameDev/bin/Release/xmleditor/index.js b/GameDev/bin/Release/xmleditor/index.js deleted file mode 100644 index ea979654..00000000 --- a/GameDev/bin/Release/xmleditor/index.js +++ /dev/null @@ -1,105 +0,0 @@ -import { Document } from "./editor_document.js"; -import { Clock } from "./utils/Clock.js"; -import { view } from "./view.js"; - -function isModified(x) -{ - return JSON.stringify(doc.is_modified()); -} - -function setXML(xml) -{ - doc.reset(); - doc.load_xml(xml, "local"); - return ""; -} - -function getXML(x) -{ - return doc.get_xml(); -} - -function picking(state) -{ - let bstate = state=="on"; - gamePlayer.picking = bstate; - doc.picking(bstate); - return ""; -} - -function pick_obj(key) -{ - doc.pick_obj(key); - return ""; -} - -function tuning(args) -{ - let input = JSON.parse(args); - return doc.tuning(input); -} - -function initialize(args) -{ - let input = JSON.parse(args); - return doc.initialize(input); -} - -function generate(args) -{ - let input = JSON.parse(args); - doc.generate(input); - return ""; -} - -function create(args) -{ - let input = JSON.parse(args); - let base_key = input.base_key; - let tag = input.tag; - doc.req_create(base_key, tag); - return ""; -} - -function remove(key) -{ - doc.req_remove(key); - return ""; -} - -function init(width, height) -{ - renderer = new GLRenderer(); - doc = new Document(view); - clock = new Clock(); - - message_map = { isModified, setXML, getXML, picking, pick_obj, tuning, initialize, generate, create, remove}; -} - -function render(width, height, size_changed) -{ - if (size_changed) - { - doc.setSize(width, height); - } - let delta = clock.getDelta(); - doc.tick(delta); - doc.render(renderer); - -} - -function message_handling(name, msg) -{ - if (name in message_map) - { - return message_map[name](msg); - } - return ""; -} - -setCallback('init', init); -setCallback('render', render); -setCallback('message', message_handling); - - - diff --git a/GameDev/bin/Release/xmleditor/math/Box2.js b/GameDev/bin/Release/xmleditor/math/Box2.js deleted file mode 100644 index 02dcaa92..00000000 --- a/GameDev/bin/Release/xmleditor/math/Box2.js +++ /dev/null @@ -1,203 +0,0 @@ -import { Vector2 } from './Vector2.js'; - -const _vector = /*@__PURE__*/ new Vector2(); - -class Box2 { - - constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { - - this.min = min; - this.max = max; - - } - - set( min, max ) { - - this.min.copy( min ); - this.max.copy( max ); - - return this; - - } - - setFromPoints( points ) { - - this.makeEmpty(); - - for ( let i = 0, il = points.length; i < il; i ++ ) { - - this.expandByPoint( points[ i ] ); - - } - - return this; - - } - - setFromCenterAndSize( center, size ) { - - const halfSize = _vector.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - } - - makeEmpty() { - - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; - - return this; - - } - - isEmpty() { - - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - - } - - getCenter( target ) { - - return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - - } - - getSize( target ) { - - return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); - - } - - expandByPoint( point ) { - - this.min.min( point ); - this.max.max( point ); - - return this; - - } - - expandByVector( vector ) { - - this.min.sub( vector ); - this.max.add( vector ); - - return this; - - } - - expandByScalar( scalar ) { - - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); - - return this; - - } - - containsPoint( point ) { - - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ? false : true; - - } - - containsBox( box ) { - - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y; - - } - - getParameter( point, target ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - - return target.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); - - } - - intersectsBox( box ) { - - // using 4 splitting planes to rule out intersections - - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ? false : true; - - } - - clampPoint( point, target ) { - - return target.copy( point ).clamp( this.min, this.max ); - - } - - distanceToPoint( point ) { - - const clampedPoint = _vector.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); - - } - - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); - - return this; - - } - - union( box ) { - - this.min.min( box.min ); - this.max.max( box.max ); - - return this; - - } - - translate( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; - - } - - equals( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - } - -} - -Box2.prototype.isBox2 = true; - -export { Box2 }; diff --git a/GameDev/bin/Release/xmleditor/math/Box3.js b/GameDev/bin/Release/xmleditor/math/Box3.js deleted file mode 100644 index 1a5e4ffd..00000000 --- a/GameDev/bin/Release/xmleditor/math/Box3.js +++ /dev/null @@ -1,518 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -class Box3 { - - constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { - - this.min = min; - this.max = max; - - } - - set( min, max ) { - - this.min.copy( min ); - this.max.copy( max ); - - return this; - - } - - setFromArray( array ) { - - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; - - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; - - for ( let i = 0, l = array.length; i < l; i += 3 ) { - - const x = array[ i ]; - const y = array[ i + 1 ]; - const z = array[ i + 2 ]; - - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; - - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; - - } - - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); - - return this; - - } - - setFromBufferAttribute( attribute ) { - - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; - - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; - - for ( let i = 0, l = attribute.count; i < l; i ++ ) { - - const x = attribute.getX( i ); - const y = attribute.getY( i ); - const z = attribute.getZ( i ); - - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; - - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; - - } - - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); - - return this; - - } - - setFromPoints( points ) { - - this.makeEmpty(); - - for ( let i = 0, il = points.length; i < il; i ++ ) { - - this.expandByPoint( points[ i ] ); - - } - - return this; - - } - - setFromCenterAndSize( center, size ) { - - const halfSize = _vector.copy( size ).multiplyScalar( 0.5 ); - - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - - return this; - - } - - setFromObject( object ) { - - this.makeEmpty(); - - return this.expandByObject( object ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - } - - makeEmpty() { - - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; - - return this; - - } - - isEmpty() { - - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - - } - - getCenter( target ) { - - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - - } - - getSize( target ) { - - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); - - } - - expandByPoint( point ) { - - this.min.min( point ); - this.max.max( point ); - - return this; - - } - - expandByVector( vector ) { - - this.min.sub( vector ); - this.max.add( vector ); - - return this; - - } - - expandByScalar( scalar ) { - - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); - - return this; - - } - - expandByObject( object ) { - - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms - - object.updateWorldMatrix( false, false ); - - const geometry = object.geometry; - - if ( geometry !== undefined ) { - - if ( geometry.boundingBox === null ) { - - geometry.computeBoundingBox(); - - } - - _box.copy( geometry.boundingBox ); - _box.applyMatrix4( object.matrixWorld ); - - this.union( _box ); - - } - - const children = object.children; - - for ( let i = 0, l = children.length; i < l; i ++ ) { - - this.expandByObject( children[ i ] ); - - } - - return this; - - } - - containsPoint( point ) { - - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ? false : true; - - } - - containsBox( box ) { - - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y && - this.min.z <= box.min.z && box.max.z <= this.max.z; - - } - - getParameter( point, target ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - - return target.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ), - ( point.z - this.min.z ) / ( this.max.z - this.min.z ) - ); - - } - - intersectsBox( box ) { - - // using 6 splitting planes to rule out intersections. - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y || - box.max.z < this.min.z || box.min.z > this.max.z ? false : true; - - } - - intersectsSphere( sphere ) { - - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, _vector ); - - // If that point is inside the sphere, the AABB and sphere intersect. - return _vector.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - - } - - intersectsPlane( plane ) { - - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. - - let min, max; - - if ( plane.normal.x > 0 ) { - - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; - - } else { - - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; - - } - - if ( plane.normal.y > 0 ) { - - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; - - } else { - - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; - - } - - if ( plane.normal.z > 0 ) { - - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; - - } else { - - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; - - } - - return ( min <= - plane.constant && max >= - plane.constant ); - - } - - intersectsTriangle( triangle ) { - - if ( this.isEmpty() ) { - - return false; - - } - - // compute box center and extents - this.getCenter( _center ); - _extents.subVectors( this.max, _center ); - - // translate triangle to aabb origin - _v0.subVectors( triangle.a, _center ); - _v1.subVectors( triangle.b, _center ); - _v2.subVectors( triangle.c, _center ); - - // compute edge vectors for triangle - _f0.subVectors( _v1, _v0 ); - _f1.subVectors( _v2, _v1 ); - _f2.subVectors( _v0, _v2 ); - - // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb - // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation - // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) - let axes = [ - 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, - _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, - - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 - ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { - - return false; - - } - - // test 3 face normals from the aabb - axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { - - return false; - - } - - // finally testing the face normal of the triangle - // use already existing triangle edge vectors here - _triangleNormal.crossVectors( _f0, _f1 ); - axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; - - return satForAxes( axes, _v0, _v1, _v2, _extents ); - - } - - clampPoint( point, target ) { - - return target.copy( point ).clamp( this.min, this.max ); - - } - - distanceToPoint( point ) { - - const clampedPoint = _vector.copy( point ).clamp( this.min, this.max ); - - return clampedPoint.sub( point ).length(); - - } - - getBoundingSphere( target ) { - - this.getCenter( target.center ); - - target.radius = this.getSize( _vector ).length() * 0.5; - - return target; - - } - - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); - - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if ( this.isEmpty() ) this.makeEmpty(); - - return this; - - } - - union( box ) { - - this.min.min( box.min ); - this.max.max( box.max ); - - return this; - - } - - applyMatrix4( matrix ) { - - // transform of empty box is an empty box. - if ( this.isEmpty() ) return this; - - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - - this.setFromPoints( _points ); - - return this; - - } - - translate( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; - - } - - equals( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - } - -} - -Box3.prototype.isBox3 = true; - -const _points = [ - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3() -]; - -const _vector = /*@__PURE__*/ new Vector3(); - -const _box = /*@__PURE__*/ new Box3(); - -// triangle centered vertices - -const _v0 = /*@__PURE__*/ new Vector3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _v2 = /*@__PURE__*/ new Vector3(); - -// triangle edge vectors - -const _f0 = /*@__PURE__*/ new Vector3(); -const _f1 = /*@__PURE__*/ new Vector3(); -const _f2 = /*@__PURE__*/ new Vector3(); - -const _center = /*@__PURE__*/ new Vector3(); -const _extents = /*@__PURE__*/ new Vector3(); -const _triangleNormal = /*@__PURE__*/ new Vector3(); -const _testAxis = /*@__PURE__*/ new Vector3(); - -function satForAxes( axes, v0, v1, v2, extents ) { - - for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { - - _testAxis.fromArray( axes, i ); - // project the aabb onto the seperating axis - const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); - // project all 3 vertices of the triangle onto the seperating axis - const p0 = v0.dot( _testAxis ); - const p1 = v1.dot( _testAxis ); - const p2 = v2.dot( _testAxis ); - // actual test, basically see if either of the most extreme of the triangle points intersects r - if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { - - // points of the projected triangle are outside the projected half-length of the aabb - // the axis is seperating and we can exit - return false; - - } - - } - - return true; - -} - -export { Box3 }; diff --git a/GameDev/bin/Release/xmleditor/math/Color.js b/GameDev/bin/Release/xmleditor/math/Color.js deleted file mode 100644 index 295c60e1..00000000 --- a/GameDev/bin/Release/xmleditor/math/Color.js +++ /dev/null @@ -1,604 +0,0 @@ -import * as MathUtils from './MathUtils.js'; - -const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, - 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, - 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, - 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, - 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, - 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, - 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, - 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, - 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, - 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, - 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, - 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, - 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, - 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, - 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, - 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, - 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, - 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, - 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, - 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, - 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, - 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, - 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, - 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - -const _hslA = { h: 0, s: 0, l: 0 }; -const _hslB = { h: 0, s: 0, l: 0 }; - -function hue2rgb( p, q, t ) { - - if ( t < 0 ) t += 1; - if ( t > 1 ) t -= 1; - if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; - if ( t < 1 / 2 ) return q; - if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); - return p; - -} - -function SRGBToLinear( c ) { - - return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); - -} - -function LinearToSRGB( c ) { - - return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; - -} - -class Color { - - constructor( r, g, b ) { - - if ( g === undefined && b === undefined ) { - - // r is THREE.Color, hex or string - return this.set( r ); - - } - - return this.setRGB( r, g, b ); - - } - - set( value ) { - - if ( value && value.isColor ) { - - this.copy( value ); - - } else if ( typeof value === 'number' ) { - - this.setHex( value ); - - } else if ( typeof value === 'string' ) { - - this.setStyle( value ); - - } - - return this; - - } - - setScalar( scalar ) { - - this.r = scalar; - this.g = scalar; - this.b = scalar; - - return this; - - } - - setHex( hex ) { - - hex = Math.floor( hex ); - - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; - - return this; - - } - - setRGB( r, g, b ) { - - this.r = r; - this.g = g; - this.b = b; - - return this; - - } - - setHSL( h, s, l ) { - - // h,s,l ranges are in 0.0 - 1.0 - h = MathUtils.euclideanModulo( h, 1 ); - s = MathUtils.clamp( s, 0, 1 ); - l = MathUtils.clamp( l, 0, 1 ); - - if ( s === 0 ) { - - this.r = this.g = this.b = l; - - } else { - - const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - const q = ( 2 * l ) - p; - - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); - - } - - return this; - - } - - setStyle( style ) { - - function handleAlpha( string ) { - - if ( string === undefined ) return; - - if ( parseFloat( string ) < 1 ) { - - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - - } - - } - - - let m; - - if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { - - // rgb / hsl - - let color; - const name = m[ 1 ]; - const components = m[ 2 ]; - - switch ( name ) { - - case 'rgb': - case 'rgba': - - if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - - // rgb(255,0,0) rgba(255,0,0,0.5) - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - - handleAlpha( color[ 4 ] ); - - return this; - - } - - if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - - handleAlpha( color[ 4 ] ); - - return this; - - } - - break; - - case 'hsl': - case 'hsla': - - if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - const h = parseFloat( color[ 1 ] ) / 360; - const s = parseInt( color[ 2 ], 10 ) / 100; - const l = parseInt( color[ 3 ], 10 ) / 100; - - handleAlpha( color[ 4 ] ); - - return this.setHSL( h, s, l ); - - } - - break; - - } - - } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { - - // hex color - - const hex = m[ 1 ]; - const size = hex.length; - - if ( size === 3 ) { - - // #ff0 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; - - return this; - - } else if ( size === 6 ) { - - // #ff0000 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - - return this; - - } - - } - - if ( style && style.length > 0 ) { - - return this.setColorName( style ); - - } - - return this; - - } - - setColorName( style ) { - - // color keywords - const hex = _colorKeywords[ style.toLowerCase() ]; - - if ( hex !== undefined ) { - - // red - this.setHex( hex ); - - } else { - - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); - - } - - return this; - - } - - clone() { - - return new this.constructor( this.r, this.g, this.b ); - - } - - copy( color ) { - - this.r = color.r; - this.g = color.g; - this.b = color.b; - - return this; - - } - - copyGammaToLinear( color, gammaFactor = 2.0 ) { - - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); - - return this; - - } - - copyLinearToGamma( color, gammaFactor = 2.0 ) { - - const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); - - return this; - - } - - convertGammaToLinear( gammaFactor ) { - - this.copyGammaToLinear( this, gammaFactor ); - - return this; - - } - - convertLinearToGamma( gammaFactor ) { - - this.copyLinearToGamma( this, gammaFactor ); - - return this; - - } - - copySRGBToLinear( color ) { - - this.r = SRGBToLinear( color.r ); - this.g = SRGBToLinear( color.g ); - this.b = SRGBToLinear( color.b ); - - return this; - - } - - copyLinearToSRGB( color ) { - - this.r = LinearToSRGB( color.r ); - this.g = LinearToSRGB( color.g ); - this.b = LinearToSRGB( color.b ); - - return this; - - } - - convertSRGBToLinear() { - - this.copySRGBToLinear( this ); - - return this; - - } - - convertLinearToSRGB() { - - this.copyLinearToSRGB( this ); - - return this; - - } - - getHex() { - - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - - } - - getHexString() { - - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - - } - - getHSL( target ) { - - // h,s,l ranges are in 0.0 - 1.0 - - const r = this.r, g = this.g, b = this.b; - - const max = Math.max( r, g, b ); - const min = Math.min( r, g, b ); - - let hue, saturation; - const lightness = ( min + max ) / 2.0; - - if ( min === max ) { - - hue = 0; - saturation = 0; - - } else { - - const delta = max - min; - - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - - switch ( max ) { - - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; - - } - - hue /= 6; - - } - - target.h = hue; - target.s = saturation; - target.l = lightness; - - return target; - - } - - getStyle() { - - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - - } - - offsetHSL( h, s, l ) { - - this.getHSL( _hslA ); - - _hslA.h += h; _hslA.s += s; _hslA.l += l; - - this.setHSL( _hslA.h, _hslA.s, _hslA.l ); - - return this; - - } - - add( color ) { - - this.r += color.r; - this.g += color.g; - this.b += color.b; - - return this; - - } - - addColors( color1, color2 ) { - - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; - - return this; - - } - - addScalar( s ) { - - this.r += s; - this.g += s; - this.b += s; - - return this; - - } - - sub( color ) { - - this.r = Math.max( 0, this.r - color.r ); - this.g = Math.max( 0, this.g - color.g ); - this.b = Math.max( 0, this.b - color.b ); - - return this; - - } - - multiply( color ) { - - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; - - return this; - - } - - multiplyScalar( s ) { - - this.r *= s; - this.g *= s; - this.b *= s; - - return this; - - } - - lerp( color, alpha ) { - - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; - - return this; - - } - - lerpColors( color1, color2, alpha ) { - - this.r = color1.r + ( color2.r - color1.r ) * alpha; - this.g = color1.g + ( color2.g - color1.g ) * alpha; - this.b = color1.b + ( color2.b - color1.b ) * alpha; - - return this; - - } - - lerpHSL( color, alpha ) { - - this.getHSL( _hslA ); - color.getHSL( _hslB ); - - const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha ); - const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha ); - const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha ); - - this.setHSL( h, s, l ); - - return this; - - } - - equals( c ) { - - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - - } - - fromArray( array, offset = 0 ) { - - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; - - return array; - - } - - fromBufferAttribute( attribute, index ) { - - this.r = attribute.getX( index ); - this.g = attribute.getY( index ); - this.b = attribute.getZ( index ); - - if ( attribute.normalized === true ) { - - // assuming Uint8Array - - this.r /= 255; - this.g /= 255; - this.b /= 255; - - } - - return this; - - } - - toJSON() { - - return this.getHex(); - - } - -} - -Color.NAMES = _colorKeywords; - -Color.prototype.isColor = true; -Color.prototype.r = 1; -Color.prototype.g = 1; -Color.prototype.b = 1; - -export { Color }; diff --git a/GameDev/bin/Release/xmleditor/math/Cylindrical.js b/GameDev/bin/Release/xmleditor/math/Cylindrical.js deleted file mode 100644 index d1288244..00000000 --- a/GameDev/bin/Release/xmleditor/math/Cylindrical.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system - */ - -class Cylindrical { - - constructor( radius = 1, theta = 0, y = 0 ) { - - this.radius = radius; // distance from the origin to a point in the x-z plane - this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis - this.y = y; // height above the x-z plane - - return this; - - } - - set( radius, theta, y ) { - - this.radius = radius; - this.theta = theta; - this.y = y; - - return this; - - } - - copy( other ) { - - this.radius = other.radius; - this.theta = other.theta; - this.y = other.y; - - return this; - - } - - setFromVector3( v ) { - - return this.setFromCartesianCoords( v.x, v.y, v.z ); - - } - - setFromCartesianCoords( x, y, z ) { - - this.radius = Math.sqrt( x * x + z * z ); - this.theta = Math.atan2( x, z ); - this.y = y; - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Cylindrical }; diff --git a/GameDev/bin/Release/xmleditor/math/Euler.js b/GameDev/bin/Release/xmleditor/math/Euler.js deleted file mode 100644 index 74c93a8a..00000000 --- a/GameDev/bin/Release/xmleditor/math/Euler.js +++ /dev/null @@ -1,322 +0,0 @@ -import { Quaternion } from './Quaternion.js'; -import { Vector3 } from './Vector3.js'; -import { Matrix4 } from './Matrix4.js'; -import { clamp } from './MathUtils.js'; - -const _matrix = /*@__PURE__*/ new Matrix4(); -const _quaternion = /*@__PURE__*/ new Quaternion(); - -class Euler { - - constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { - - this._x = x; - this._y = y; - this._z = z; - this._order = order; - - } - - get x() { - - return this._x; - - } - - set x( value ) { - - this._x = value; - this._onChangeCallback(); - - } - - get y() { - - return this._y; - - } - - set y( value ) { - - this._y = value; - this._onChangeCallback(); - - } - - get z() { - - return this._z; - - } - - set z( value ) { - - this._z = value; - this._onChangeCallback(); - - } - - get order() { - - return this._order; - - } - - set order( value ) { - - this._order = value; - this._onChangeCallback(); - - } - - set( x, y, z, order = this._order ) { - - this._x = x; - this._y = y; - this._z = z; - this._order = order; - - this._onChangeCallback(); - - return this; - - } - - clone() { - - return new this.constructor( this._x, this._y, this._z, this._order ); - - } - - copy( euler ) { - - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; - - this._onChangeCallback(); - - return this; - - } - - setFromRotationMatrix( m, order = this._order, update = true ) { - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - const te = m.elements; - const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - - switch ( order ) { - - case 'XYZ': - - this._y = Math.asin( clamp( m13, - 1, 1 ) ); - - if ( Math.abs( m13 ) < 0.9999999 ) { - - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); - - } else { - - this._x = Math.atan2( m32, m22 ); - this._z = 0; - - } - - break; - - case 'YXZ': - - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - - if ( Math.abs( m23 ) < 0.9999999 ) { - - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); - - } else { - - this._y = Math.atan2( - m31, m11 ); - this._z = 0; - - } - - break; - - case 'ZXY': - - this._x = Math.asin( clamp( m32, - 1, 1 ) ); - - if ( Math.abs( m32 ) < 0.9999999 ) { - - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); - - } else { - - this._y = 0; - this._z = Math.atan2( m21, m11 ); - - } - - break; - - case 'ZYX': - - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - - if ( Math.abs( m31 ) < 0.9999999 ) { - - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); - - } else { - - this._x = 0; - this._z = Math.atan2( - m12, m22 ); - - } - - break; - - case 'YZX': - - this._z = Math.asin( clamp( m21, - 1, 1 ) ); - - if ( Math.abs( m21 ) < 0.9999999 ) { - - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); - - } else { - - this._x = 0; - this._y = Math.atan2( m13, m33 ); - - } - - break; - - case 'XZY': - - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - - if ( Math.abs( m12 ) < 0.9999999 ) { - - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); - - } else { - - this._x = Math.atan2( - m23, m33 ); - this._y = 0; - - } - - break; - - default: - - console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); - - } - - this._order = order; - - if ( update === true ) this._onChangeCallback(); - - return this; - - } - - setFromQuaternion( q, order, update ) { - - _matrix.makeRotationFromQuaternion( q ); - - return this.setFromRotationMatrix( _matrix, order, update ); - - } - - setFromVector3( v, order = this._order ) { - - return this.set( v.x, v.y, v.z, order ); - - } - - reorder( newOrder ) { - - // WARNING: this discards revolution information -bhouston - - _quaternion.setFromEuler( this ); - - return this.setFromQuaternion( _quaternion, newOrder ); - - } - - equals( euler ) { - - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - - } - - fromArray( array ) { - - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - - this._onChangeCallback(); - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; - - return array; - - } - - toVector3( optionalResult ) { - - if ( optionalResult ) { - - return optionalResult.set( this._x, this._y, this._z ); - - } else { - - return new Vector3( this._x, this._y, this._z ); - - } - - } - - _onChange( callback ) { - - this._onChangeCallback = callback; - - return this; - - } - - _onChangeCallback() {} - -} - -Euler.prototype.isEuler = true; - -Euler.DefaultOrder = 'XYZ'; -Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - -export { Euler }; diff --git a/GameDev/bin/Release/xmleditor/math/Frustum.js b/GameDev/bin/Release/xmleditor/math/Frustum.js deleted file mode 100644 index fc6b928a..00000000 --- a/GameDev/bin/Release/xmleditor/math/Frustum.js +++ /dev/null @@ -1,162 +0,0 @@ -import { Vector3 } from './Vector3.js'; -import { Sphere } from './Sphere.js'; -import { Plane } from './Plane.js'; - -const _sphere = /*@__PURE__*/ new Sphere(); -const _vector = /*@__PURE__*/ new Vector3(); - -class Frustum { - - constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { - - this.planes = [ p0, p1, p2, p3, p4, p5 ]; - - } - - set( p0, p1, p2, p3, p4, p5 ) { - - const planes = this.planes; - - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); - - return this; - - } - - copy( frustum ) { - - const planes = this.planes; - - for ( let i = 0; i < 6; i ++ ) { - - planes[ i ].copy( frustum.planes[ i ] ); - - } - - return this; - - } - - setFromProjectionMatrix( m ) { - - const planes = this.planes; - const me = m.elements; - const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; - const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; - const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; - const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; - - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - - return this; - - } - - intersectsObject( object ) { - - const geometry = object.geometry; - - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - - _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); - - return this.intersectsSphere( _sphere ); - - } - - intersectsSprite( sprite ) { - - _sphere.center.set( 0, 0, 0 ); - _sphere.radius = 0.7071067811865476; - _sphere.applyMatrix4( sprite.matrixWorld ); - - return this.intersectsSphere( _sphere ); - - } - - intersectsSphere( sphere ) { - - const planes = this.planes; - const center = sphere.center; - const negRadius = - sphere.radius; - - for ( let i = 0; i < 6; i ++ ) { - - const distance = planes[ i ].distanceToPoint( center ); - - if ( distance < negRadius ) { - - return false; - - } - - } - - return true; - - } - - intersectsBox( box ) { - - const planes = this.planes; - - for ( let i = 0; i < 6; i ++ ) { - - const plane = planes[ i ]; - - // corner at max distance - - _vector.x = plane.normal.x > 0 ? box.max.x : box.min.x; - _vector.y = plane.normal.y > 0 ? box.max.y : box.min.y; - _vector.z = plane.normal.z > 0 ? box.max.z : box.min.z; - - if ( plane.distanceToPoint( _vector ) < 0 ) { - - return false; - - } - - } - - return true; - - } - - containsPoint( point ) { - - const planes = this.planes; - - for ( let i = 0; i < 6; i ++ ) { - - if ( planes[ i ].distanceToPoint( point ) < 0 ) { - - return false; - - } - - } - - return true; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - - -export { Frustum }; diff --git a/GameDev/bin/Release/xmleditor/math/Interpolant.js b/GameDev/bin/Release/xmleditor/math/Interpolant.js deleted file mode 100644 index dcc550f5..00000000 --- a/GameDev/bin/Release/xmleditor/math/Interpolant.js +++ /dev/null @@ -1,246 +0,0 @@ -/** - * Abstract base class of interpolants over parametric samples. - * - * The parameter domain is one dimensional, typically the time or a path - * along a curve defined by the data. - * - * The sample values can have any dimensionality and derived classes may - * apply special interpretations to the data. - * - * This class provides the interval seek in a Template Method, deferring - * the actual interpolation to derived classes. - * - * Time complexity is O(1) for linear access crossing at most two points - * and O(log N) for random access, where N is the number of positions. - * - * References: - * - * http://www.oodesign.com/template-method-pattern.html - * - */ - -class Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; - - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; - - this.settings = null; - this.DefaultSettings_ = {}; - - } - - evaluate( t ) { - - const pp = this.parameterPositions; - let i1 = this._cachedIndex, - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; - - validate_interval: { - - seek: { - - let right; - - linear_scan: { - - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { - - for ( let giveUpAt = i1 + 2; ; ) { - - if ( t1 === undefined ) { - - if ( t < t0 ) break forward_scan; - - // after end - - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); - - } - - if ( i1 === giveUpAt ) break; // this loop - - t0 = t1; - t1 = pp[ ++ i1 ]; - - if ( t < t1 ) { - - // we have arrived at the sought interval - break seek; - - } - - } - - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; - - } - - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { - - // looping? - - const t1global = pp[ 1 ]; - - if ( t < t1global ) { - - i1 = 2; // + 1, using the scan for the details - t0 = t1global; - - } - - // linear reverse scan - - for ( let giveUpAt = i1 - 2; ; ) { - - if ( t0 === undefined ) { - - // before start - - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); - - } - - if ( i1 === giveUpAt ) break; // this loop - - t1 = t0; - t0 = pp[ -- i1 - 1 ]; - - if ( t >= t0 ) { - - // we have arrived at the sought interval - break seek; - - } - - } - - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; - - } - - // the interval is valid - - break validate_interval; - - } // linear scan - - // binary search - - while ( i1 < right ) { - - const mid = ( i1 + right ) >>> 1; - - if ( t < pp[ mid ] ) { - - right = mid; - - } else { - - i1 = mid + 1; - - } - - } - - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; - - // check boundary cases, again - - if ( t0 === undefined ) { - - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); - - } - - if ( t1 === undefined ) { - - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); - - } - - } // seek - - this._cachedIndex = i1; - - this.intervalChanged_( i1, t0, t1 ); - - } // validate_interval - - return this.interpolate_( i1, t0, t, t1 ); - - } - - getSettings_() { - - return this.settings || this.DefaultSettings_; - - } - - copySampleValue_( index ) { - - // copies a sample value to the result buffer - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; - - for ( let i = 0; i !== stride; ++ i ) { - - result[ i ] = values[ offset + i ]; - - } - - return result; - - } - - // Template methods for derived classes: - - interpolate_( /* i1, t0, t, t1 */ ) { - - throw new Error( 'call to abstract method' ); - // implementations shall return this.resultBuffer - - } - - intervalChanged_( /* i1, t0, t1 */ ) { - - // empty - - } - -} - -// ALIAS DEFINITIONS - -Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_; -Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_; - -export { Interpolant }; diff --git a/GameDev/bin/Release/xmleditor/math/Line3.js b/GameDev/bin/Release/xmleditor/math/Line3.js deleted file mode 100644 index bd41206e..00000000 --- a/GameDev/bin/Release/xmleditor/math/Line3.js +++ /dev/null @@ -1,115 +0,0 @@ -import { Vector3 } from './Vector3.js'; -import * as MathUtils from './MathUtils.js'; - -const _startP = /*@__PURE__*/ new Vector3(); -const _startEnd = /*@__PURE__*/ new Vector3(); - -class Line3 { - - constructor( start = new Vector3(), end = new Vector3() ) { - - this.start = start; - this.end = end; - - } - - set( start, end ) { - - this.start.copy( start ); - this.end.copy( end ); - - return this; - - } - - copy( line ) { - - this.start.copy( line.start ); - this.end.copy( line.end ); - - return this; - - } - - getCenter( target ) { - - return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - - } - - delta( target ) { - - return target.subVectors( this.end, this.start ); - - } - - distanceSq() { - - return this.start.distanceToSquared( this.end ); - - } - - distance() { - - return this.start.distanceTo( this.end ); - - } - - at( t, target ) { - - return this.delta( target ).multiplyScalar( t ).add( this.start ); - - } - - closestPointToPointParameter( point, clampToLine ) { - - _startP.subVectors( point, this.start ); - _startEnd.subVectors( this.end, this.start ); - - const startEnd2 = _startEnd.dot( _startEnd ); - const startEnd_startP = _startEnd.dot( _startP ); - - let t = startEnd_startP / startEnd2; - - if ( clampToLine ) { - - t = MathUtils.clamp( t, 0, 1 ); - - } - - return t; - - } - - closestPointToPoint( point, clampToLine, target ) { - - const t = this.closestPointToPointParameter( point, clampToLine ); - - return this.delta( target ).multiplyScalar( t ).add( this.start ); - - } - - applyMatrix4( matrix ) { - - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); - - return this; - - } - - equals( line ) { - - return line.start.equals( this.start ) && line.end.equals( this.end ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Line3 }; diff --git a/GameDev/bin/Release/xmleditor/math/MathUtils.js b/GameDev/bin/Release/xmleditor/math/MathUtils.js deleted file mode 100644 index 3de8f5ff..00000000 --- a/GameDev/bin/Release/xmleditor/math/MathUtils.js +++ /dev/null @@ -1,258 +0,0 @@ -const _lut = []; - -for ( let i = 0; i < 256; i ++ ) { - - _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); - -} - -let _seed = 1234567; - - -const DEG2RAD = Math.PI / 180; -const RAD2DEG = 180 / Math.PI; - -// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 -function generateUUID() { - - const d0 = Math.random() * 0xffffffff | 0; - const d1 = Math.random() * 0xffffffff | 0; - const d2 = Math.random() * 0xffffffff | 0; - const d3 = Math.random() * 0xffffffff | 0; - const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + - _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + - _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + - _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; - - // .toUpperCase() here flattens concatenated strings to save heap memory space. - return uuid.toUpperCase(); - -} - -function clamp( value, min, max ) { - - return Math.max( min, Math.min( max, value ) ); - -} - -// compute euclidian modulo of m % n -// https://en.wikipedia.org/wiki/Modulo_operation -function euclideanModulo( n, m ) { - - return ( ( n % m ) + m ) % m; - -} - -// Linear mapping from range to range -function mapLinear( x, a1, a2, b1, b2 ) { - - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - -} - -// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ -function inverseLerp( x, y, value ) { - - if ( x !== y ) { - - return ( value - x ) / ( y - x ); - - } else { - - return 0; - - } - -} - -// https://en.wikipedia.org/wiki/Linear_interpolation -function lerp( x, y, t ) { - - return ( 1 - t ) * x + t * y; - -} - -// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ -function damp( x, y, lambda, dt ) { - - return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); - -} - -// https://www.desmos.com/calculator/vcsjnyz7x4 -function pingpong( x, length = 1 ) { - - return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); - -} - -// http://en.wikipedia.org/wiki/Smoothstep -function smoothstep( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min ) / ( max - min ); - - return x * x * ( 3 - 2 * x ); - -} - -function smootherstep( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min ) / ( max - min ); - - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - -} - -// Random integer from interval -function randInt( low, high ) { - - return low + Math.floor( Math.random() * ( high - low + 1 ) ); - -} - -// Random float from interval -function randFloat( low, high ) { - - return low + Math.random() * ( high - low ); - -} - -// Random float from <-range/2, range/2> interval -function randFloatSpread( range ) { - - return range * ( 0.5 - Math.random() ); - -} - -// Deterministic pseudo-random float in the interval [ 0, 1 ] -function seededRandom( s ) { - - if ( s !== undefined ) _seed = s % 2147483647; - - // Park-Miller algorithm - - _seed = _seed * 16807 % 2147483647; - - return ( _seed - 1 ) / 2147483646; - -} - -function degToRad( degrees ) { - - return degrees * DEG2RAD; - -} - -function radToDeg( radians ) { - - return radians * RAD2DEG; - -} - -function isPowerOfTwo( value ) { - - return ( value & ( value - 1 ) ) === 0 && value !== 0; - -} - -function ceilPowerOfTwo( value ) { - - return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); - -} - -function floorPowerOfTwo( value ) { - - return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); - -} - -function setQuaternionFromProperEuler( q, a, b, c, order ) { - - // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles - - // rotations are applied to the axes in the order specified by 'order' - // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' - // angles are in radians - - const cos = Math.cos; - const sin = Math.sin; - - const c2 = cos( b / 2 ); - const s2 = sin( b / 2 ); - - const c13 = cos( ( a + c ) / 2 ); - const s13 = sin( ( a + c ) / 2 ); - - const c1_3 = cos( ( a - c ) / 2 ); - const s1_3 = sin( ( a - c ) / 2 ); - - const c3_1 = cos( ( c - a ) / 2 ); - const s3_1 = sin( ( c - a ) / 2 ); - - switch ( order ) { - - case 'XYX': - q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); - break; - - case 'YZY': - q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); - break; - - case 'ZXZ': - q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); - break; - - case 'XZX': - q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); - break; - - case 'YXY': - q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); - break; - - case 'ZYZ': - q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); - break; - - default: - console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); - - } - -} - - - - -export { - DEG2RAD, - RAD2DEG, - generateUUID, - clamp, - euclideanModulo, - mapLinear, - inverseLerp, - lerp, - damp, - pingpong, - smoothstep, - smootherstep, - randInt, - randFloat, - randFloatSpread, - seededRandom, - degToRad, - radToDeg, - isPowerOfTwo, - ceilPowerOfTwo, - floorPowerOfTwo, - setQuaternionFromProperEuler, -}; diff --git a/GameDev/bin/Release/xmleditor/math/Matrix3.js b/GameDev/bin/Release/xmleditor/math/Matrix3.js deleted file mode 100644 index 9005740e..00000000 --- a/GameDev/bin/Release/xmleditor/math/Matrix3.js +++ /dev/null @@ -1,339 +0,0 @@ -class Matrix3 { - - constructor() { - - this.elements = [ - - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - - ]; - - if ( arguments.length > 0 ) { - - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - - } - - } - - set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - - const te = this.elements; - - te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; - te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; - te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; - - return this; - - } - - identity() { - - this.set( - - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - - ); - - return this; - - } - - copy( m ) { - - const te = this.elements; - const me = m.elements; - - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; - te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; - te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; - - return this; - - } - - extractBasis( xAxis, yAxis, zAxis ) { - - xAxis.setFromMatrix3Column( this, 0 ); - yAxis.setFromMatrix3Column( this, 1 ); - zAxis.setFromMatrix3Column( this, 2 ); - - return this; - - } - - setFromMatrix4( m ) { - - const me = m.elements; - - this.set( - - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] - - ); - - return this; - - } - - multiply( m ) { - - return this.multiplyMatrices( this, m ); - - } - - premultiply( m ) { - - return this.multiplyMatrices( m, this ); - - } - - multiplyMatrices( a, b ) { - - const ae = a.elements; - const be = b.elements; - const te = this.elements; - - const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; - const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; - const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; - - const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; - const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; - const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; - - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; - te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; - te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; - - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; - te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; - te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; - - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; - te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; - te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; - - return this; - - } - - multiplyScalar( s ) { - - const te = this.elements; - - te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; - te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; - te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; - - return this; - - } - - determinant() { - - const te = this.elements; - - const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], - d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], - g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - - } - - invert() { - - const te = this.elements, - - n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], - n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ], - n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ], - - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, - - det = n11 * t11 + n21 * t12 + n31 * t13; - - if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - const detInv = 1 / det; - - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; - - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; - - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - - return this; - - } - - transpose() { - - let tmp; - const m = this.elements; - - tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; - tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; - tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; - - return this; - - } - - getNormalMatrix( matrix4 ) { - - return this.setFromMatrix4( matrix4 ).invert().transpose(); - - } - - transposeIntoArray( r ) { - - const m = this.elements; - - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; - - return this; - - } - - setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) { - - const c = Math.cos( rotation ); - const s = Math.sin( rotation ); - - this.set( - sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, - - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, - 0, 0, 1 - ); - - return this; - - } - - scale( sx, sy ) { - - const te = this.elements; - - te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx; - te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy; - - return this; - - } - - rotate( theta ) { - - const c = Math.cos( theta ); - const s = Math.sin( theta ); - - const te = this.elements; - - const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ]; - const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ]; - - te[ 0 ] = c * a11 + s * a21; - te[ 3 ] = c * a12 + s * a22; - te[ 6 ] = c * a13 + s * a23; - - te[ 1 ] = - s * a11 + c * a21; - te[ 4 ] = - s * a12 + c * a22; - te[ 7 ] = - s * a13 + c * a23; - - return this; - - } - - translate( tx, ty ) { - - const te = this.elements; - - te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ]; - te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ]; - - return this; - - } - - equals( matrix ) { - - const te = this.elements; - const me = matrix.elements; - - for ( let i = 0; i < 9; i ++ ) { - - if ( te[ i ] !== me[ i ] ) return false; - - } - - return true; - - } - - fromArray( array, offset = 0 ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.elements[ i ] = array[ i + offset ]; - - } - - return this; - - } - - toArray( array = [], offset = 0 ) { - - const te = this.elements; - - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; - - return array; - - } - - clone() { - - return new this.constructor().fromArray( this.elements ); - - } - -} - -Matrix3.prototype.isMatrix3 = true; - -export { Matrix3 }; diff --git a/GameDev/bin/Release/xmleditor/math/Matrix4.js b/GameDev/bin/Release/xmleditor/math/Matrix4.js deleted file mode 100644 index 5383e24c..00000000 --- a/GameDev/bin/Release/xmleditor/math/Matrix4.js +++ /dev/null @@ -1,885 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -class Matrix4 { - - constructor() { - - this.elements = [ - - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ]; - - if ( arguments.length > 0 ) { - - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - - } - - } - - set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - - const te = this.elements; - - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - - return this; - - } - - identity() { - - this.set( - - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - clone() { - - return new Matrix4().fromArray( this.elements ); - - } - - copy( m ) { - - const te = this.elements; - const me = m.elements; - - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; - te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; - te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; - te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; - - return this; - - } - - copyPosition( m ) { - - const te = this.elements, me = m.elements; - - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; - - return this; - - } - - setFromMatrix3( m ) { - - const me = m.elements; - - this.set( - - me[ 0 ], me[ 3 ], me[ 6 ], 0, - me[ 1 ], me[ 4 ], me[ 7 ], 0, - me[ 2 ], me[ 5 ], me[ 8 ], 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - extractBasis( xAxis, yAxis, zAxis ) { - - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); - - return this; - - } - - makeBasis( xAxis, yAxis, zAxis ) { - - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 - ); - - return this; - - } - - extractRotation( m ) { - - // this method does not support reflection matrices - - const te = this.elements; - const me = m.elements; - - const scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length(); - const scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length(); - const scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length(); - - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; - te[ 3 ] = 0; - - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; - te[ 7 ] = 0; - - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; - te[ 11 ] = 0; - - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; - - return this; - - } - - makeRotationFromEuler( euler ) { - - if ( ! ( euler && euler.isEuler ) ) { - - console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - - } - - const te = this.elements; - - const x = euler.x, y = euler.y, z = euler.z; - const a = Math.cos( x ), b = Math.sin( x ); - const c = Math.cos( y ), d = Math.sin( y ); - const e = Math.cos( z ), f = Math.sin( z ); - - if ( euler.order === 'XYZ' ) { - - const ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; - - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; - - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; - - } else if ( euler.order === 'YXZ' ) { - - const ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; - - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; - - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; - - } else if ( euler.order === 'ZXY' ) { - - const ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; - - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; - - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; - - } else if ( euler.order === 'ZYX' ) { - - const ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; - - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; - - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; - - } else if ( euler.order === 'YZX' ) { - - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; - - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; - - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; - - } else if ( euler.order === 'XZY' ) { - - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; - - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; - - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; - - } - - // bottom row - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; - - // last column - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; - - return this; - - } - - makeRotationFromQuaternion( q ) { - - return this.compose( _zero, q, _one ); - - } - - lookAt( eye, target, up ) { - - const te = this.elements; - - _z.subVectors( eye, target ); - - if ( _z.lengthSq() === 0 ) { - - // eye and target are in the same position - - _z.z = 1; - - } - - _z.normalize(); - _x.crossVectors( up, _z ); - - if ( _x.lengthSq() === 0 ) { - - // up and z are parallel - - if ( Math.abs( up.z ) === 1 ) { - - _z.x += 0.0001; - - } else { - - _z.z += 0.0001; - - } - - _z.normalize(); - _x.crossVectors( up, _z ); - - } - - _x.normalize(); - _y.crossVectors( _z, _x ); - - te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; - te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; - te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; - - return this; - - } - - multiply( m, n ) { - - if ( n !== undefined ) { - - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); - - } - - return this.multiplyMatrices( this, m ); - - } - - premultiply( m ) { - - return this.multiplyMatrices( m, this ); - - } - - multiplyMatrices( a, b ) { - - const ae = a.elements; - const be = b.elements; - const te = this.elements; - - const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - - const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - - return this; - - } - - multiplyScalar( s ) { - - const te = this.elements; - - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; - - return this; - - } - - determinant() { - - const te = this.elements; - - const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) - - ); - - } - - transpose() { - - const te = this.elements; - let tmp; - - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - - return this; - - } - - setPosition( x, y, z ) { - - const te = this.elements; - - if ( x.isVector3 ) { - - te[ 12 ] = x.x; - te[ 13 ] = x.y; - te[ 14 ] = x.z; - - } else { - - te[ 12 ] = x; - te[ 13 ] = y; - te[ 14 ] = z; - - } - - return this; - - } - - invert() { - - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - const te = this.elements, - - n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], - n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], - n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], - n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], - - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - - const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - - if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - const detInv = 1 / det; - - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; - - return this; - - } - - scale( v ) { - - const te = this.elements; - const x = v.x, y = v.y, z = v.z; - - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; - - return this; - - } - - getMaxScaleOnAxis() { - - const te = this.elements; - - const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; - - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - - } - - makeTranslation( x, y, z ) { - - this.set( - - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationX( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationY( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationZ( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeRotationAxis( axis, angle ) { - - // Based on http://www.gamedev.net/reference/articles/article1199.asp - - const c = Math.cos( angle ); - const s = Math.sin( angle ); - const t = 1 - c; - const x = axis.x, y = axis.y, z = axis.z; - const tx = t * x, ty = t * y; - - this.set( - - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeScale( x, y, z ) { - - this.set( - - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - makeShear( xy, xz, yx, yz, zx, zy ) { - - this.set( - - 1, yx, zx, 0, - xy, 1, zy, 0, - xz, yz, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - } - - compose( position, quaternion, scale ) { - - const te = this.elements; - - const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; - const x2 = x + x, y2 = y + y, z2 = z + z; - const xx = x * x2, xy = x * y2, xz = x * z2; - const yy = y * y2, yz = y * z2, zz = z * z2; - const wx = w * x2, wy = w * y2, wz = w * z2; - - const sx = scale.x, sy = scale.y, sz = scale.z; - - te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; - te[ 1 ] = ( xy + wz ) * sx; - te[ 2 ] = ( xz - wy ) * sx; - te[ 3 ] = 0; - - te[ 4 ] = ( xy - wz ) * sy; - te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; - te[ 6 ] = ( yz + wx ) * sy; - te[ 7 ] = 0; - - te[ 8 ] = ( xz + wy ) * sz; - te[ 9 ] = ( yz - wx ) * sz; - te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; - te[ 11 ] = 0; - - te[ 12 ] = position.x; - te[ 13 ] = position.y; - te[ 14 ] = position.z; - te[ 15 ] = 1; - - return this; - - } - - decompose( position, quaternion, scale ) { - - const te = this.elements; - - let sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - const sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - const sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - - // if determine is negative, we need to invert one scale - const det = this.determinant(); - if ( det < 0 ) sx = - sx; - - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; - - // scale the rotation part - _m1.copy( this ); - - const invSX = 1 / sx; - const invSY = 1 / sy; - const invSZ = 1 / sz; - - _m1.elements[ 0 ] *= invSX; - _m1.elements[ 1 ] *= invSX; - _m1.elements[ 2 ] *= invSX; - - _m1.elements[ 4 ] *= invSY; - _m1.elements[ 5 ] *= invSY; - _m1.elements[ 6 ] *= invSY; - - _m1.elements[ 8 ] *= invSZ; - _m1.elements[ 9 ] *= invSZ; - _m1.elements[ 10 ] *= invSZ; - - quaternion.setFromRotationMatrix( _m1 ); - - scale.x = sx; - scale.y = sy; - scale.z = sz; - - return this; - - } - - makePerspective( left, right, top, bottom, near, far ) { - - if ( far === undefined ) { - - console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); - - } - - const te = this.elements; - const x = 2 * near / ( right - left ); - const y = 2 * near / ( top - bottom ); - - const a = ( right + left ) / ( right - left ); - const b = ( top + bottom ) / ( top - bottom ); - const c = - ( far + near ) / ( far - near ); - const d = - 2 * far * near / ( far - near ); - - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - - return this; - - } - - makeOrthographic( left, right, top, bottom, near, far ) { - - const te = this.elements; - const w = 1.0 / ( right - left ); - const h = 1.0 / ( top - bottom ); - const p = 1.0 / ( far - near ); - - const x = ( right + left ) * w; - const y = ( top + bottom ) * h; - const z = ( far + near ) * p; - - te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; - - return this; - - } - - equals( matrix ) { - - const te = this.elements; - const me = matrix.elements; - - for ( let i = 0; i < 16; i ++ ) { - - if ( te[ i ] !== me[ i ] ) return false; - - } - - return true; - - } - - fromArray( array, offset = 0 ) { - - for ( let i = 0; i < 16; i ++ ) { - - this.elements[ i ] = array[ i + offset ]; - - } - - return this; - - } - - toArray( array = [], offset = 0 ) { - - const te = this.elements; - - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; - - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; - - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; - - return array; - - } - -} - -Matrix4.prototype.isMatrix4 = true; - -const _v1 = /*@__PURE__*/ new Vector3(); -const _m1 = /*@__PURE__*/ new Matrix4(); -const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); -const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); -const _x = /*@__PURE__*/ new Vector3(); -const _y = /*@__PURE__*/ new Vector3(); -const _z = /*@__PURE__*/ new Vector3(); - -export { Matrix4 }; diff --git a/GameDev/bin/Release/xmleditor/math/Plane.js b/GameDev/bin/Release/xmleditor/math/Plane.js deleted file mode 100644 index fc8a471b..00000000 --- a/GameDev/bin/Release/xmleditor/math/Plane.js +++ /dev/null @@ -1,205 +0,0 @@ -import { Matrix3 } from './Matrix3.js'; -import { Vector3 } from './Vector3.js'; - -const _vector1 = /*@__PURE__*/ new Vector3(); -const _vector2 = /*@__PURE__*/ new Vector3(); -const _normalMatrix = /*@__PURE__*/ new Matrix3(); - -class Plane { - - constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { - - // normal is assumed to be normalized - - this.normal = normal; - this.constant = constant; - - } - - set( normal, constant ) { - - this.normal.copy( normal ); - this.constant = constant; - - return this; - - } - - setComponents( x, y, z, w ) { - - this.normal.set( x, y, z ); - this.constant = w; - - return this; - - } - - setFromNormalAndCoplanarPoint( normal, point ) { - - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); - - return this; - - } - - setFromCoplanarPoints( a, b, c ) { - - const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); - - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - - this.setFromNormalAndCoplanarPoint( normal, a ); - - return this; - - } - - copy( plane ) { - - this.normal.copy( plane.normal ); - this.constant = plane.constant; - - return this; - - } - - normalize() { - - // Note: will lead to a divide by zero if the plane is invalid. - - const inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; - - return this; - - } - - negate() { - - this.constant *= - 1; - this.normal.negate(); - - return this; - - } - - distanceToPoint( point ) { - - return this.normal.dot( point ) + this.constant; - - } - - distanceToSphere( sphere ) { - - return this.distanceToPoint( sphere.center ) - sphere.radius; - - } - - projectPoint( point, target ) { - - return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); - - } - - intersectLine( line, target ) { - - const direction = line.delta( _vector1 ); - - const denominator = this.normal.dot( direction ); - - if ( denominator === 0 ) { - - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { - - return target.copy( line.start ); - - } - - // Unsure if this is the correct method to handle this case. - return null; - - } - - const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - - if ( t < 0 || t > 1 ) { - - return null; - - } - - return target.copy( direction ).multiplyScalar( t ).add( line.start ); - - } - - intersectsLine( line ) { - - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - - const startSign = this.distanceToPoint( line.start ); - const endSign = this.distanceToPoint( line.end ); - - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - - } - - intersectsBox( box ) { - - return box.intersectsPlane( this ); - - } - - intersectsSphere( sphere ) { - - return sphere.intersectsPlane( this ); - - } - - coplanarPoint( target ) { - - return target.copy( this.normal ).multiplyScalar( - this.constant ); - - } - - applyMatrix4( matrix, optionalNormalMatrix ) { - - const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); - - const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); - - const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - - this.constant = - referencePoint.dot( normal ); - - return this; - - } - - translate( offset ) { - - this.constant -= offset.dot( this.normal ); - - return this; - - } - - equals( plane ) { - - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -Plane.prototype.isPlane = true; - -export { Plane }; diff --git a/GameDev/bin/Release/xmleditor/math/Quaternion.js b/GameDev/bin/Release/xmleditor/math/Quaternion.js deleted file mode 100644 index 485fe865..00000000 --- a/GameDev/bin/Release/xmleditor/math/Quaternion.js +++ /dev/null @@ -1,689 +0,0 @@ -import * as MathUtils from './MathUtils.js'; - -class Quaternion { - - constructor( x = 0, y = 0, z = 0, w = 1 ) { - - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - } - - static slerp( qa, qb, qm, t ) { - - console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' ); - return qm.slerpQuaternions( qa, qb, t ); - - } - - static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - - // fuzz-free, array-based Quaternion SLERP operation - - let x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ]; - - const x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; - - if ( t === 0 ) { - - dst[ dstOffset + 0 ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - return; - - } - - if ( t === 1 ) { - - dst[ dstOffset + 0 ] = x1; - dst[ dstOffset + 1 ] = y1; - dst[ dstOffset + 2 ] = z1; - dst[ dstOffset + 3 ] = w1; - return; - - } - - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - - let s = 1 - t; - const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; - - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { - - const sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); - - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; - - } - - const tDir = t * dir; - - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; - - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { - - const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; - - } - - } - - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - - } - - static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { - - const x0 = src0[ srcOffset0 ]; - const y0 = src0[ srcOffset0 + 1 ]; - const z0 = src0[ srcOffset0 + 2 ]; - const w0 = src0[ srcOffset0 + 3 ]; - - const x1 = src1[ srcOffset1 ]; - const y1 = src1[ srcOffset1 + 1 ]; - const z1 = src1[ srcOffset1 + 2 ]; - const w1 = src1[ srcOffset1 + 3 ]; - - dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; - dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; - dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; - dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; - - return dst; - - } - - get x() { - - return this._x; - - } - - set x( value ) { - - this._x = value; - this._onChangeCallback(); - - } - - get y() { - - return this._y; - - } - - set y( value ) { - - this._y = value; - this._onChangeCallback(); - - } - - get z() { - - return this._z; - - } - - set z( value ) { - - this._z = value; - this._onChangeCallback(); - - } - - get w() { - - return this._w; - - } - - set w( value ) { - - this._w = value; - this._onChangeCallback(); - - } - - set( x, y, z, w ) { - - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - this._onChangeCallback(); - - return this; - - } - - clone() { - - return new this.constructor( this._x, this._y, this._z, this._w ); - - } - - copy( quaternion ) { - - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; - - this._onChangeCallback(); - - return this; - - } - - setFromEuler( euler, update ) { - - if ( ! ( euler && euler.isEuler ) ) { - - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - - } - - const x = euler._x, y = euler._y, z = euler._z, order = euler._order; - - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m - - const cos = Math.cos; - const sin = Math.sin; - - const c1 = cos( x / 2 ); - const c2 = cos( y / 2 ); - const c3 = cos( z / 2 ); - - const s1 = sin( x / 2 ); - const s2 = sin( y / 2 ); - const s3 = sin( z / 2 ); - - switch ( order ) { - - case 'XYZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'YXZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - case 'ZXY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'ZYX': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - case 'YZX': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - - case 'XZY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - - default: - console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); - - } - - if ( update !== false ) this._onChangeCallback(); - - return this; - - } - - setFromAxisAngle( axis, angle ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - - // assumes axis is normalized - - const halfAngle = angle / 2, s = Math.sin( halfAngle ); - - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); - - this._onChangeCallback(); - - return this; - - } - - setFromRotationMatrix( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - const te = m.elements, - - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - - trace = m11 + m22 + m33; - - if ( trace > 0 ) { - - const s = 0.5 / Math.sqrt( trace + 1.0 ); - - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; - - } else if ( m11 > m22 && m11 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; - - } else if ( m22 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; - - } else { - - const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; - - } - - this._onChangeCallback(); - - return this; - - } - - setFromUnitVectors( vFrom, vTo ) { - - // assumes direction vectors vFrom and vTo are normalized - - let r = vFrom.dot( vTo ) + 1; - - if ( r < Number.EPSILON ) { - - // vFrom and vTo point in opposite directions - - r = 0; - - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - - this._x = - vFrom.y; - this._y = vFrom.x; - this._z = 0; - this._w = r; - - } else { - - this._x = 0; - this._y = - vFrom.z; - this._z = vFrom.y; - this._w = r; - - } - - } else { - - // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 - - this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; - this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; - this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; - this._w = r; - - } - - return this.normalize(); - - } - - angleTo( q ) { - - return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) ); - - } - - rotateTowards( q, step ) { - - const angle = this.angleTo( q ); - - if ( angle === 0 ) return this; - - const t = Math.min( 1, step / angle ); - - this.slerp( q, t ); - - return this; - - } - - identity() { - - return this.set( 0, 0, 0, 1 ); - - } - - invert() { - - // quaternion is assumed to have unit length - - return this.conjugate(); - - } - - conjugate() { - - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; - - this._onChangeCallback(); - - return this; - - } - - dot( v ) { - - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - - } - - lengthSq() { - - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - - } - - length() { - - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - - } - - normalize() { - - let l = this.length(); - - if ( l === 0 ) { - - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; - - } else { - - l = 1 / l; - - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; - - } - - this._onChangeCallback(); - - return this; - - } - - multiply( q, p ) { - - if ( p !== undefined ) { - - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); - - } - - return this.multiplyQuaternions( this, q ); - - } - - premultiply( q ) { - - return this.multiplyQuaternions( q, this ); - - } - - multiplyQuaternions( a, b ) { - - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - - const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - - this._onChangeCallback(); - - return this; - - } - - slerp( qb, t ) { - - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); - - const x = this._x, y = this._y, z = this._z, w = this._w; - - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - - let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - - if ( cosHalfTheta < 0 ) { - - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; - - cosHalfTheta = - cosHalfTheta; - - } else { - - this.copy( qb ); - - } - - if ( cosHalfTheta >= 1.0 ) { - - this._w = w; - this._x = x; - this._y = y; - this._z = z; - - return this; - - } - - const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; - - if ( sqrSinHalfTheta <= Number.EPSILON ) { - - const s = 1 - t; - this._w = s * w + t * this._w; - this._x = s * x + t * this._x; - this._y = s * y + t * this._y; - this._z = s * z + t * this._z; - - this.normalize(); - this._onChangeCallback(); - - return this; - - } - - const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); - const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); - - this._onChangeCallback(); - - return this; - - } - - slerpQuaternions( qa, qb, t ) { - - this.copy( qa ).slerp( qb, t ); - - } - - random() { - - // Derived from http://planning.cs.uiuc.edu/node198.html - // Note, this source uses w, x, y, z ordering, - // so we swap the order below. - - const u1 = Math.random(); - const sqrt1u1 = Math.sqrt( 1 - u1 ); - const sqrtu1 = Math.sqrt( u1 ); - - const u2 = 2 * Math.PI * Math.random(); - - const u3 = 2 * Math.PI * Math.random(); - - return this.set( - sqrt1u1 * Math.cos( u2 ), - sqrtu1 * Math.sin( u3 ), - sqrtu1 * Math.cos( u3 ), - sqrt1u1 * Math.sin( u2 ), - ); - - } - - equals( quaternion ) { - - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - - } - - fromArray( array, offset = 0 ) { - - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; - - this._onChangeCallback(); - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; - - return array; - - } - - fromBufferAttribute( attribute, index ) { - - this._x = attribute.getX( index ); - this._y = attribute.getY( index ); - this._z = attribute.getZ( index ); - this._w = attribute.getW( index ); - - return this; - - } - - _onChange( callback ) { - - this._onChangeCallback = callback; - - return this; - - } - - _onChangeCallback() {} - -} - -Quaternion.prototype.isQuaternion = true; - -export { Quaternion }; diff --git a/GameDev/bin/Release/xmleditor/math/Ray.js b/GameDev/bin/Release/xmleditor/math/Ray.js deleted file mode 100644 index 5798c7bf..00000000 --- a/GameDev/bin/Release/xmleditor/math/Ray.js +++ /dev/null @@ -1,496 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -const _vector = /*@__PURE__*/ new Vector3(); -const _segCenter = /*@__PURE__*/ new Vector3(); -const _segDir = /*@__PURE__*/ new Vector3(); -const _diff = /*@__PURE__*/ new Vector3(); - -const _edge1 = /*@__PURE__*/ new Vector3(); -const _edge2 = /*@__PURE__*/ new Vector3(); -const _normal = /*@__PURE__*/ new Vector3(); - -class Ray { - - constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { - - this.origin = origin; - this.direction = direction; - - } - - set( origin, direction ) { - - this.origin.copy( origin ); - this.direction.copy( direction ); - - return this; - - } - - copy( ray ) { - - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); - - return this; - - } - - at( t, target ) { - - return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - - } - - lookAt( v ) { - - this.direction.copy( v ).sub( this.origin ).normalize(); - - return this; - - } - - recast( t ) { - - this.origin.copy( this.at( t, _vector ) ); - - return this; - - } - - closestPointToPoint( point, target ) { - - target.subVectors( point, this.origin ); - - const directionDistance = target.dot( this.direction ); - - if ( directionDistance < 0 ) { - - return target.copy( this.origin ); - - } - - return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - - } - - distanceToPoint( point ) { - - return Math.sqrt( this.distanceSqToPoint( point ) ); - - } - - distanceSqToPoint( point ) { - - const directionDistance = _vector.subVectors( point, this.origin ).dot( this.direction ); - - // point behind the ray - - if ( directionDistance < 0 ) { - - return this.origin.distanceToSquared( point ); - - } - - _vector.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - - return _vector.distanceToSquared( point ); - - } - - distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment - - _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - _segDir.copy( v1 ).sub( v0 ).normalize(); - _diff.copy( this.origin ).sub( _segCenter ); - - const segExtent = v0.distanceTo( v1 ) * 0.5; - const a01 = - this.direction.dot( _segDir ); - const b0 = _diff.dot( this.direction ); - const b1 = - _diff.dot( _segDir ); - const c = _diff.lengthSq(); - const det = Math.abs( 1 - a01 * a01 ); - let s0, s1, sqrDist, extDet; - - if ( det > 0 ) { - - // The ray and segment are not parallel. - - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; - - if ( s0 >= 0 ) { - - if ( s1 >= - extDet ) { - - if ( s1 <= extDet ) { - - // region 0 - // Minimum at interior points of ray and segment. - - const invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - - } else { - - // region 1 - - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } else { - - // region 5 - - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } else { - - if ( s1 <= - extDet ) { - - // region 4 - - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } else if ( s1 <= extDet ) { - - // region 3 - - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; - - } else { - - // region 2 - - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } - - } else { - - // Ray and segment are parallel. - - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - if ( optionalPointOnRay ) { - - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - - } - - if ( optionalPointOnSegment ) { - - optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); - - } - - return sqrDist; - - } - - intersectSphere( sphere, target ) { - - _vector.subVectors( sphere.center, this.origin ); - const tca = _vector.dot( this.direction ); - const d2 = _vector.dot( _vector ) - tca * tca; - const radius2 = sphere.radius * sphere.radius; - - if ( d2 > radius2 ) return null; - - const thc = Math.sqrt( radius2 - d2 ); - - // t0 = first intersect point - entrance on front of sphere - const t0 = tca - thc; - - // t1 = second intersect point - exit point on back of sphere - const t1 = tca + thc; - - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; - - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if ( t0 < 0 ) return this.at( t1, target ); - - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, target ); - - } - - intersectsSphere( sphere ) { - - return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); - - } - - distanceToPlane( plane ) { - - const denominator = plane.normal.dot( this.direction ); - - if ( denominator === 0 ) { - - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { - - return 0; - - } - - // Null is preferable to undefined since undefined means.... it is undefined - - return null; - - } - - const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - - // Return if the ray never intersects the plane - - return t >= 0 ? t : null; - - } - - intersectPlane( plane, target ) { - - const t = this.distanceToPlane( plane ); - - if ( t === null ) { - - return null; - - } - - return this.at( t, target ); - - } - - intersectsPlane( plane ) { - - // check if the ray lies on the plane first - - const distToPoint = plane.distanceToPoint( this.origin ); - - if ( distToPoint === 0 ) { - - return true; - - } - - const denominator = plane.normal.dot( this.direction ); - - if ( denominator * distToPoint < 0 ) { - - return true; - - } - - // ray origin is behind the plane (and is pointing behind it) - - return false; - - } - - intersectBox( box, target ) { - - let tmin, tmax, tymin, tymax, tzmin, tzmax; - - const invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; - - const origin = this.origin; - - if ( invdirx >= 0 ) { - - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; - - } else { - - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; - - } - - if ( invdiry >= 0 ) { - - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; - - } else { - - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; - - } - - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN - - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - - if ( invdirz >= 0 ) { - - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; - - } else { - - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; - - } - - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - - //return point closest to the ray (positive side) - - if ( tmax < 0 ) return null; - - return this.at( tmin >= 0 ? tmin : tmax, target ); - - } - - intersectsBox( box ) { - - return this.intersectBox( box, _vector ) !== null; - - } - - intersectTriangle( a, b, c, backfaceCulling, target ) { - - // Compute the offset origin, edges, and normal. - - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - - _edge1.subVectors( b, a ); - _edge2.subVectors( c, a ); - _normal.crossVectors( _edge1, _edge2 ); - - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - let DdN = this.direction.dot( _normal ); - let sign; - - if ( DdN > 0 ) { - - if ( backfaceCulling ) return null; - sign = 1; - - } else if ( DdN < 0 ) { - - sign = - 1; - DdN = - DdN; - - } else { - - return null; - - } - - _diff.subVectors( this.origin, a ); - const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); - - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { - - return null; - - } - - const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); - - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { - - return null; - - } - - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { - - return null; - - } - - // Line intersects triangle, check if ray does. - const QdN = - sign * _diff.dot( _normal ); - - // t < 0, no intersection - if ( QdN < 0 ) { - - return null; - - } - - // Ray intersects triangle. - return this.at( QdN / DdN, target ); - - } - - applyMatrix4( matrix4 ) { - - this.origin.applyMatrix4( matrix4 ); - this.direction.transformDirection( matrix4 ); - - return this; - - } - - equals( ray ) { - - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Ray }; diff --git a/GameDev/bin/Release/xmleditor/math/Sphere.js b/GameDev/bin/Release/xmleditor/math/Sphere.js deleted file mode 100644 index 657335ba..00000000 --- a/GameDev/bin/Release/xmleditor/math/Sphere.js +++ /dev/null @@ -1,219 +0,0 @@ -import { Box3 } from './Box3.js'; -import { Vector3 } from './Vector3.js'; - -const _box = /*@__PURE__*/ new Box3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _toFarthestPoint = /*@__PURE__*/ new Vector3(); -const _toPoint = /*@__PURE__*/ new Vector3(); - -class Sphere { - - constructor( center = new Vector3(), radius = - 1 ) { - - this.center = center; - this.radius = radius; - - } - - set( center, radius ) { - - this.center.copy( center ); - this.radius = radius; - - return this; - - } - - setFromPoints( points, optionalCenter ) { - - const center = this.center; - - if ( optionalCenter !== undefined ) { - - center.copy( optionalCenter ); - - } else { - - _box.setFromPoints( points ).getCenter( center ); - - } - - let maxRadiusSq = 0; - - for ( let i = 0, il = points.length; i < il; i ++ ) { - - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - - } - - this.radius = Math.sqrt( maxRadiusSq ); - - return this; - - } - - copy( sphere ) { - - this.center.copy( sphere.center ); - this.radius = sphere.radius; - - return this; - - } - - isEmpty() { - - return ( this.radius < 0 ); - - } - - makeEmpty() { - - this.center.set( 0, 0, 0 ); - this.radius = - 1; - - return this; - - } - - containsPoint( point ) { - - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - - } - - distanceToPoint( point ) { - - return ( point.distanceTo( this.center ) - this.radius ); - - } - - intersectsSphere( sphere ) { - - const radiusSum = this.radius + sphere.radius; - - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - - } - - intersectsBox( box ) { - - return box.intersectsSphere( this ); - - } - - intersectsPlane( plane ) { - - return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; - - } - - clampPoint( point, target ) { - - const deltaLengthSq = this.center.distanceToSquared( point ); - - target.copy( point ); - - if ( deltaLengthSq > ( this.radius * this.radius ) ) { - - target.sub( this.center ).normalize(); - target.multiplyScalar( this.radius ).add( this.center ); - - } - - return target; - - } - - getBoundingBox( target ) { - - if ( this.isEmpty() ) { - - // Empty sphere produces empty bounding box - target.makeEmpty(); - return target; - - } - - target.set( this.center, this.center ); - target.expandByScalar( this.radius ); - - return target; - - } - - applyMatrix4( matrix ) { - - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); - - return this; - - } - - translate( offset ) { - - this.center.add( offset ); - - return this; - - } - - expandByPoint( point ) { - - // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671 - - _toPoint.subVectors( point, this.center ); - - const lengthSq = _toPoint.lengthSq(); - - if ( lengthSq > ( this.radius * this.radius ) ) { - - const length = Math.sqrt( lengthSq ); - const missingRadiusHalf = ( length - this.radius ) * 0.5; - - // Nudge this sphere towards the target point. Add half the missing distance to radius, - // and the other half to position. This gives a tighter enclosure, instead of if - // the whole missing distance were just added to radius. - - this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) ); - this.radius += missingRadiusHalf; - - } - - return this; - - } - - union( sphere ) { - - // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769 - - // To enclose another sphere into this sphere, we only need to enclose two points: - // 1) Enclose the farthest point on the other sphere into this sphere. - // 2) Enclose the opposite point of the farthest point into this sphere. - - _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius ); - - this.expandByPoint( _v1.copy( sphere.center ).add( _toFarthestPoint ) ); - this.expandByPoint( _v1.copy( sphere.center ).sub( _toFarthestPoint ) ); - - return this; - - } - - equals( sphere ) { - - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Sphere }; diff --git a/GameDev/bin/Release/xmleditor/math/Spherical.js b/GameDev/bin/Release/xmleditor/math/Spherical.js deleted file mode 100644 index 9b7bb6c6..00000000 --- a/GameDev/bin/Release/xmleditor/math/Spherical.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. - * The azimuthal angle (theta) is measured from the positive z-axis. - */ - -import * as MathUtils from './MathUtils.js'; - -class Spherical { - - constructor( radius = 1, phi = 0, theta = 0 ) { - - this.radius = radius; - this.phi = phi; // polar angle - this.theta = theta; // azimuthal angle - - return this; - - } - - set( radius, phi, theta ) { - - this.radius = radius; - this.phi = phi; - this.theta = theta; - - return this; - - } - - copy( other ) { - - this.radius = other.radius; - this.phi = other.phi; - this.theta = other.theta; - - return this; - - } - - // restrict phi to be betwee EPS and PI-EPS - makeSafe() { - - const EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - - return this; - - } - - setFromVector3( v ) { - - return this.setFromCartesianCoords( v.x, v.y, v.z ); - - } - - setFromCartesianCoords( x, y, z ) { - - this.radius = Math.sqrt( x * x + y * y + z * z ); - - if ( this.radius === 0 ) { - - this.theta = 0; - this.phi = 0; - - } else { - - this.theta = Math.atan2( x, z ); - this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) ); - - } - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - -} - -export { Spherical }; diff --git a/GameDev/bin/Release/xmleditor/math/SphericalHarmonics3.js b/GameDev/bin/Release/xmleditor/math/SphericalHarmonics3.js deleted file mode 100644 index 2d8796fb..00000000 --- a/GameDev/bin/Release/xmleditor/math/SphericalHarmonics3.js +++ /dev/null @@ -1,243 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -/** - * Primary reference: - * https://graphics.stanford.edu/papers/envmap/envmap.pdf - * - * Secondary reference: - * https://www.ppsloan.org/publications/StupidSH36.pdf - */ - -// 3-band SH defined by 9 coefficients - -class SphericalHarmonics3 { - - constructor() { - - this.coefficients = []; - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients.push( new Vector3() ); - - } - - } - - set( coefficients ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].copy( coefficients[ i ] ); - - } - - return this; - - } - - zero() { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].set( 0, 0, 0 ); - - } - - return this; - - } - - // get the radiance in the direction of the normal - // target is a Vector3 - getAt( normal, target ) { - - // normal is assumed to be unit length - - const x = normal.x, y = normal.y, z = normal.z; - - const coeff = this.coefficients; - - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); - - // band 1 - target.addScaledVector( coeff[ 1 ], 0.488603 * y ); - target.addScaledVector( coeff[ 2 ], 0.488603 * z ); - target.addScaledVector( coeff[ 3 ], 0.488603 * x ); - - // band 2 - target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); - target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); - target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); - target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); - target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); - - return target; - - } - - // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal - // target is a Vector3 - // https://graphics.stanford.edu/papers/envmap/envmap.pdf - getIrradianceAt( normal, target ) { - - // normal is assumed to be unit length - - const x = normal.x, y = normal.y, z = normal.z; - - const coeff = this.coefficients; - - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 - - // band 1 - target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 - target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); - target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); - - // band 2 - target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 - target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); - target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 - target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); - target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 - - return target; - - } - - add( sh ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].add( sh.coefficients[ i ] ); - - } - - return this; - - } - - addScaledSH( sh, s ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); - - } - - return this; - - } - - scale( s ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].multiplyScalar( s ); - - } - - return this; - - } - - lerp( sh, alpha ) { - - for ( let i = 0; i < 9; i ++ ) { - - this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); - - } - - return this; - - } - - equals( sh ) { - - for ( let i = 0; i < 9; i ++ ) { - - if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { - - return false; - - } - - } - - return true; - - } - - copy( sh ) { - - return this.set( sh.coefficients ); - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - fromArray( array, offset = 0 ) { - - const coefficients = this.coefficients; - - for ( let i = 0; i < 9; i ++ ) { - - coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); - - } - - return this; - - } - - toArray( array = [], offset = 0 ) { - - const coefficients = this.coefficients; - - for ( let i = 0; i < 9; i ++ ) { - - coefficients[ i ].toArray( array, offset + ( i * 3 ) ); - - } - - return array; - - } - - // evaluate the basis functions - // shBasis is an Array[ 9 ] - static getBasisAt( normal, shBasis ) { - - // normal is assumed to be unit length - - const x = normal.x, y = normal.y, z = normal.z; - - // band 0 - shBasis[ 0 ] = 0.282095; - - // band 1 - shBasis[ 1 ] = 0.488603 * y; - shBasis[ 2 ] = 0.488603 * z; - shBasis[ 3 ] = 0.488603 * x; - - // band 2 - shBasis[ 4 ] = 1.092548 * x * y; - shBasis[ 5 ] = 1.092548 * y * z; - shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); - shBasis[ 7 ] = 1.092548 * x * z; - shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); - - } - -} - -SphericalHarmonics3.prototype.isSphericalHarmonics3 = true; - -export { SphericalHarmonics3 }; diff --git a/GameDev/bin/Release/xmleditor/math/Triangle.js b/GameDev/bin/Release/xmleditor/math/Triangle.js deleted file mode 100644 index 617ca629..00000000 --- a/GameDev/bin/Release/xmleditor/math/Triangle.js +++ /dev/null @@ -1,299 +0,0 @@ -import { Vector3 } from './Vector3.js'; - -const _v0 = /*@__PURE__*/ new Vector3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _v2 = /*@__PURE__*/ new Vector3(); -const _v3 = /*@__PURE__*/ new Vector3(); - -const _vab = /*@__PURE__*/ new Vector3(); -const _vac = /*@__PURE__*/ new Vector3(); -const _vbc = /*@__PURE__*/ new Vector3(); -const _vap = /*@__PURE__*/ new Vector3(); -const _vbp = /*@__PURE__*/ new Vector3(); -const _vcp = /*@__PURE__*/ new Vector3(); - -class Triangle { - - constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { - - this.a = a; - this.b = b; - this.c = c; - - } - - static getNormal( a, b, c, target ) { - - target.subVectors( c, b ); - _v0.subVectors( a, b ); - target.cross( _v0 ); - - const targetLengthSq = target.lengthSq(); - if ( targetLengthSq > 0 ) { - - return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); - - } - - return target.set( 0, 0, 0 ); - - } - - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - static getBarycoord( point, a, b, c, target ) { - - _v0.subVectors( c, a ); - _v1.subVectors( b, a ); - _v2.subVectors( point, a ); - - const dot00 = _v0.dot( _v0 ); - const dot01 = _v0.dot( _v1 ); - const dot02 = _v0.dot( _v2 ); - const dot11 = _v1.dot( _v1 ); - const dot12 = _v1.dot( _v2 ); - - const denom = ( dot00 * dot11 - dot01 * dot01 ); - - // collinear or singular triangle - if ( denom === 0 ) { - - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return target.set( - 2, - 1, - 1 ); - - } - - const invDenom = 1 / denom; - const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - - // barycentric coordinates must always sum to 1 - return target.set( 1 - u - v, v, u ); - - } - - static containsPoint( point, a, b, c ) { - - this.getBarycoord( point, a, b, c, _v3 ); - - return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); - - } - - static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { - - this.getBarycoord( point, p1, p2, p3, _v3 ); - - target.set( 0, 0 ); - target.addScaledVector( uv1, _v3.x ); - target.addScaledVector( uv2, _v3.y ); - target.addScaledVector( uv3, _v3.z ); - - return target; - - } - - static isFrontFacing( a, b, c, direction ) { - - _v0.subVectors( c, b ); - _v1.subVectors( a, b ); - - // strictly front facing - return ( _v0.cross( _v1 ).dot( direction ) < 0 ) ? true : false; - - } - - set( a, b, c ) { - - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); - - return this; - - } - - setFromPointsAndIndices( points, i0, i1, i2 ) { - - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); - - return this; - - } - - setFromAttributeAndIndices( attribute, i0, i1, i2 ) { - - this.a.fromBufferAttribute( attribute, i0 ); - this.b.fromBufferAttribute( attribute, i1 ); - this.c.fromBufferAttribute( attribute, i2 ); - - return this; - - } - - clone() { - - return new this.constructor().copy( this ); - - } - - copy( triangle ) { - - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); - - return this; - - } - - getArea() { - - _v0.subVectors( this.c, this.b ); - _v1.subVectors( this.a, this.b ); - - return _v0.cross( _v1 ).length() * 0.5; - - } - - getMidpoint( target ) { - - return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - - } - - getNormal( target ) { - - return Triangle.getNormal( this.a, this.b, this.c, target ); - - } - - getPlane( target ) { - - return target.setFromCoplanarPoints( this.a, this.b, this.c ); - - } - - getBarycoord( point, target ) { - - return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); - - } - - getUV( point, uv1, uv2, uv3, target ) { - - return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); - - } - - containsPoint( point ) { - - return Triangle.containsPoint( point, this.a, this.b, this.c ); - - } - - isFrontFacing( direction ) { - - return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); - - } - - intersectsBox( box ) { - - return box.intersectsTriangle( this ); - - } - - closestPointToPoint( p, target ) { - - const a = this.a, b = this.b, c = this.c; - let v, w; - - // algorithm thanks to Real-Time Collision Detection by Christer Ericson, - // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., - // under the accompanying license; see chapter 5.1.5 for detailed explanation. - // basically, we're distinguishing which of the voronoi regions of the triangle - // the point lies in with the minimum amount of redundant computation. - - _vab.subVectors( b, a ); - _vac.subVectors( c, a ); - _vap.subVectors( p, a ); - const d1 = _vab.dot( _vap ); - const d2 = _vac.dot( _vap ); - if ( d1 <= 0 && d2 <= 0 ) { - - // vertex region of A; barycentric coords (1, 0, 0) - return target.copy( a ); - - } - - _vbp.subVectors( p, b ); - const d3 = _vab.dot( _vbp ); - const d4 = _vac.dot( _vbp ); - if ( d3 >= 0 && d4 <= d3 ) { - - // vertex region of B; barycentric coords (0, 1, 0) - return target.copy( b ); - - } - - const vc = d1 * d4 - d3 * d2; - if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { - - v = d1 / ( d1 - d3 ); - // edge region of AB; barycentric coords (1-v, v, 0) - return target.copy( a ).addScaledVector( _vab, v ); - - } - - _vcp.subVectors( p, c ); - const d5 = _vab.dot( _vcp ); - const d6 = _vac.dot( _vcp ); - if ( d6 >= 0 && d5 <= d6 ) { - - // vertex region of C; barycentric coords (0, 0, 1) - return target.copy( c ); - - } - - const vb = d5 * d2 - d1 * d6; - if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { - - w = d2 / ( d2 - d6 ); - // edge region of AC; barycentric coords (1-w, 0, w) - return target.copy( a ).addScaledVector( _vac, w ); - - } - - const va = d3 * d6 - d5 * d4; - if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { - - _vbc.subVectors( c, b ); - w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); - // edge region of BC; barycentric coords (0, 1-w, w) - return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC - - } - - // face region - const denom = 1 / ( va + vb + vc ); - // u = va * denom - v = vb * denom; - w = vc * denom; - - return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); - - } - - equals( triangle ) { - - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - - } - -} - -export { Triangle }; diff --git a/GameDev/bin/Release/xmleditor/math/Vector2.js b/GameDev/bin/Release/xmleditor/math/Vector2.js deleted file mode 100644 index 88592aa3..00000000 --- a/GameDev/bin/Release/xmleditor/math/Vector2.js +++ /dev/null @@ -1,484 +0,0 @@ -class Vector2 { - - constructor( x = 0, y = 0 ) { - - this.x = x; - this.y = y; - - } - - get width() { - - return this.x; - - } - - set width( value ) { - - this.x = value; - - } - - get height() { - - return this.y; - - } - - set height( value ) { - - this.y = value; - - } - - set( x, y ) { - - this.x = x; - this.y = y; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - - return this; - - } - - multiply( v ) { - - this.x *= v.x; - this.y *= v.y; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - - return this; - - } - - divide( v ) { - - this.x /= v.x; - this.y /= v.y; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - applyMatrix3( m ) { - - const x = this.x, y = this.y; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; - - return this; - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y; - - } - - cross( v ) { - - return this.x * v.y - this.y * v.x; - - } - - lengthSq() { - - return this.x * this.x + this.y * this.y; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - angle() { - - // computes the angle in radians with respect to the positive x-axis - - const angle = Math.atan2( - this.y, - this.x ) + Math.PI; - - return angle; - - } - - distanceTo( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - } - - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; - - } - - manhattanDistanceTo( v ) { - - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - - return this; - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - - return this; - - } - - rotateAround( center, angle ) { - - const c = Math.cos( angle ), s = Math.sin( angle ); - - const x = this.x - center.x; - const y = this.y - center.y; - - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - - } - -} - -Vector2.prototype.isVector2 = true; - -export { Vector2 }; diff --git a/GameDev/bin/Release/xmleditor/math/Vector3.js b/GameDev/bin/Release/xmleditor/math/Vector3.js deleted file mode 100644 index d3303860..00000000 --- a/GameDev/bin/Release/xmleditor/math/Vector3.js +++ /dev/null @@ -1,745 +0,0 @@ -import * as MathUtils from './MathUtils.js'; -import { Quaternion } from './Quaternion.js'; - -class Vector3 { - - constructor( x = 0, y = 0, z = 0 ) { - - this.x = x; - this.y = y; - this.z = z; - - } - - set( x, y, z ) { - - if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) - - this.x = x; - this.y = y; - this.z = z; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - this.z = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setZ( z ) { - - this.z = z; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y, this.z ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - this.z += v.z; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - this.z += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - this.z -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - - return this; - - } - - multiply( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); - - } - - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - - return this; - - } - - multiplyVectors( a, b ) { - - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; - - return this; - - } - - applyEuler( euler ) { - - if ( ! ( euler && euler.isEuler ) ) { - - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - - } - - return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); - - } - - applyAxisAngle( axis, angle ) { - - return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); - - } - - applyMatrix3( m ) { - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; - this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; - - return this; - - } - - applyNormalMatrix( m ) { - - return this.applyMatrix3( m ).normalize(); - - } - - applyMatrix4( m ) { - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); - - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; - this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; - - return this; - - } - - applyQuaternion( q ) { - - const x = this.x, y = this.y, z = this.z; - const qx = q.x, qy = q.y, qz = q.z, qw = q.w; - - // calculate quat * vector - - const ix = qw * x + qy * z - qz * y; - const iy = qw * y + qz * x - qx * z; - const iz = qw * z + qx * y - qy * x; - const iw = - qx * x - qy * y - qz * z; - - // calculate result * inverse quat - - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; - - return this; - - } - - project( camera ) { - - return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); - - } - - unproject( camera ) { - - return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); - - } - - transformDirection( m ) { - - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction - - const x = this.x, y = this.y, z = this.z; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; - - return this.normalize(); - - } - - divide( v ) { - - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z; - - } - - // TODO lengthSquared? - - lengthSq() { - - return this.x * this.x + this.y * this.y + this.z * this.z; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; - - return this; - - } - - cross( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); - - } - - return this.crossVectors( this, v ); - - } - - crossVectors( a, b ) { - - const ax = a.x, ay = a.y, az = a.z; - const bx = b.x, by = b.y, bz = b.z; - - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - - return this; - - } - - projectOnVector( v ) { - - const denominator = v.lengthSq(); - - if ( denominator === 0 ) return this.set( 0, 0, 0 ); - - const scalar = v.dot( this ) / denominator; - - return this.copy( v ).multiplyScalar( scalar ); - - } - - projectOnPlane( planeNormal ) { - - _vector.copy( this ).projectOnVector( planeNormal ); - - return this.sub( _vector ); - - } - - reflect( normal ) { - - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length - - return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - - } - - angleTo( v ) { - - const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); - - if ( denominator === 0 ) return Math.PI / 2; - - const theta = this.dot( v ) / denominator; - - // clamp, to handle numerical problems - - return Math.acos( MathUtils.clamp( theta, - 1, 1 ) ); - - } - - distanceTo( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - } - - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - - return dx * dx + dy * dy + dz * dz; - - } - - manhattanDistanceTo( v ) { - - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - - } - - setFromSpherical( s ) { - - return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); - - } - - setFromSphericalCoords( radius, phi, theta ) { - - const sinPhiRadius = Math.sin( phi ) * radius; - - this.x = sinPhiRadius * Math.sin( theta ); - this.y = Math.cos( phi ) * radius; - this.z = sinPhiRadius * Math.cos( theta ); - - return this; - - } - - setFromCylindrical( c ) { - - return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); - - } - - setFromCylindricalCoords( radius, theta, y ) { - - this.x = radius * Math.sin( theta ); - this.y = y; - this.z = radius * Math.cos( theta ); - - return this; - - } - - setFromMatrixPosition( m ) { - - const e = m.elements; - - this.x = e[ 12 ]; - this.y = e[ 13 ]; - this.z = e[ 14 ]; - - return this; - - } - - setFromMatrixScale( m ) { - - const sx = this.setFromMatrixColumn( m, 0 ).length(); - const sy = this.setFromMatrixColumn( m, 1 ).length(); - const sz = this.setFromMatrixColumn( m, 2 ).length(); - - this.x = sx; - this.y = sy; - this.z = sz; - - return this; - - } - - setFromMatrixColumn( m, index ) { - - return this.fromArray( m.elements, index * 4 ); - - } - - setFromMatrix3Column( m, index ) { - - return this.fromArray( m.elements, index * 3 ); - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - - return this; - - } - - randomDirection() { - - // Derived from https://mathworld.wolfram.com/SpherePointPicking.html - - const u = ( Math.random() - 0.5 ) * 2; - const t = Math.random() * Math.PI * 2; - const f = Math.sqrt( 1 - u ** 2 ); - - this.x = f * Math.cos( t ); - this.y = f * Math.sin( t ); - this.z = u; - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - yield this.z; - - } - -} - -Vector3.prototype.isVector3 = true; - -const _vector = /*@__PURE__*/ new Vector3(); -const _quaternion = /*@__PURE__*/ new Quaternion(); - -export { Vector3 }; diff --git a/GameDev/bin/Release/xmleditor/math/Vector4.js b/GameDev/bin/Release/xmleditor/math/Vector4.js deleted file mode 100644 index c9af047a..00000000 --- a/GameDev/bin/Release/xmleditor/math/Vector4.js +++ /dev/null @@ -1,664 +0,0 @@ -class Vector4 { - - constructor( x = 0, y = 0, z = 0, w = 1 ) { - - this.x = x; - this.y = y; - this.z = z; - this.w = w; - - } - - get width() { - - return this.z; - - } - - set width( value ) { - - this.z = value; - - } - - get height() { - - return this.w; - - } - - set height( value ) { - - this.w = value; - - } - - set( x, y, z, w ) { - - this.x = x; - this.y = y; - this.z = z; - this.w = w; - - return this; - - } - - setScalar( scalar ) { - - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; - - return this; - - } - - setX( x ) { - - this.x = x; - - return this; - - } - - setY( y ) { - - this.y = y; - - return this; - - } - - setZ( z ) { - - this.z = z; - - return this; - - } - - setW( w ) { - - this.w = w; - - return this; - - } - - setComponent( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( 'index is out of range: ' + index ); - - } - - return this; - - } - - getComponent( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( 'index is out of range: ' + index ); - - } - - } - - clone() { - - return new this.constructor( this.x, this.y, this.z, this.w ); - - } - - copy( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; - - return this; - - } - - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; - - return this; - - } - - addScalar( s ) { - - this.x += s; - this.y += s; - this.z += s; - this.w += s; - - return this; - - } - - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; - - return this; - - } - - addScaledVector( v, s ) { - - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; - - return this; - - } - - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; - - return this; - - } - - subScalar( s ) { - - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; - - return this; - - } - - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; - - return this; - - } - - multiply( v ) { - - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - this.w *= v.w; - - return this; - - } - - multiplyScalar( scalar ) { - - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; - - return this; - - } - - applyMatrix4( m ) { - - const x = this.x, y = this.y, z = this.z, w = this.w; - const e = m.elements; - - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; - this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - - return this; - - } - - divideScalar( scalar ) { - - return this.multiplyScalar( 1 / scalar ); - - } - - setAxisAngleFromQuaternion( q ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - - // q is assumed to be normalized - - this.w = 2 * Math.acos( q.w ); - - const s = Math.sqrt( 1 - q.w * q.w ); - - if ( s < 0.0001 ) { - - this.x = 1; - this.y = 0; - this.z = 0; - - } else { - - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; - - } - - return this; - - } - - setAxisAngleFromRotationMatrix( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - let angle, x, y, z; // variables for result - const epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - - te = m.elements, - - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { - - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms - - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - - // this singularity is identity matrix so angle = 0 - - this.set( 1, 0, 0, 0 ); - - return this; // zero angle, arbitrary axis - - } - - // otherwise this singularity is angle = 180 - - angle = Math.PI; - - const xx = ( m11 + 1 ) / 2; - const yy = ( m22 + 1 ) / 2; - const zz = ( m33 + 1 ) / 2; - const xy = ( m12 + m21 ) / 4; - const xz = ( m13 + m31 ) / 4; - const yz = ( m23 + m32 ) / 4; - - if ( ( xx > yy ) && ( xx > zz ) ) { - - // m11 is the largest diagonal term - - if ( xx < epsilon ) { - - x = 0; - y = 0.707106781; - z = 0.707106781; - - } else { - - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; - - } - - } else if ( yy > zz ) { - - // m22 is the largest diagonal term - - if ( yy < epsilon ) { - - x = 0.707106781; - y = 0; - z = 0.707106781; - - } else { - - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; - - } - - } else { - - // m33 is the largest diagonal term so base result on this - - if ( zz < epsilon ) { - - x = 0.707106781; - y = 0.707106781; - z = 0; - - } else { - - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; - - } - - } - - this.set( x, y, z, angle ); - - return this; // return 180 deg rotation - - } - - // as we have reached here there are no singularities so we can handle normally - - let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + - ( m13 - m31 ) * ( m13 - m31 ) + - ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - - if ( Math.abs( s ) < 0.001 ) s = 1; - - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case - - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - - return this; - - } - - min( v ) { - - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - this.w = Math.min( this.w, v.w ); - - return this; - - } - - max( v ) { - - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - this.w = Math.max( this.w, v.w ); - - return this; - - } - - clamp( min, max ) { - - // assumes min < max, componentwise - - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); - - return this; - - } - - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); - - return this; - - } - - clampLength( min, max ) { - - const length = this.length(); - - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - - } - - floor() { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); - - return this; - - } - - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); - - return this; - - } - - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); - - return this; - - } - - roundToZero() { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - - return this; - - } - - negate() { - - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; - - return this; - - } - - dot( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - - } - - lengthSq() { - - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - - } - - length() { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - - } - - manhattanLength() { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - - } - - normalize() { - - return this.divideScalar( this.length() || 1 ); - - } - - setLength( length ) { - - return this.normalize().multiplyScalar( length ); - - } - - lerp( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; - - return this; - - } - - lerpVectors( v1, v2, alpha ) { - - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; - this.w = v1.w + ( v2.w - v1.w ) * alpha; - - return this; - - } - - equals( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - - } - - fromArray( array, offset = 0 ) { - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; - - return this; - - } - - toArray( array = [], offset = 0 ) { - - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; - - return array; - - } - - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - this.w = attribute.getW( index ); - - return this; - - } - - random() { - - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - this.w = Math.random(); - - return this; - - } - - *[ Symbol.iterator ]() { - - yield this.x; - yield this.y; - yield this.z; - yield this.w; - - } - -} - -Vector4.prototype.isVector4 = true; - -export { Vector4 }; diff --git a/GameDev/bin/Release/xmleditor/math/interpolants/CubicInterpolant.js b/GameDev/bin/Release/xmleditor/math/interpolants/CubicInterpolant.js deleted file mode 100644 index 3484dbfa..00000000 --- a/GameDev/bin/Release/xmleditor/math/interpolants/CubicInterpolant.js +++ /dev/null @@ -1,151 +0,0 @@ -import { ZeroCurvatureEnding } from '../../constants.js'; -import { Interpolant } from '../Interpolant.js'; -import { WrapAroundEnding, ZeroSlopeEnding } from '../../constants.js'; - -/** - * Fast and simple cubic spline interpolant. - * - * It was derived from a Hermitian construction setting the first derivative - * at each sample position to the linear slope between neighboring positions - * over their parameter interval. - */ - -class CubicInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - this._weightPrev = - 0; - this._offsetPrev = - 0; - this._weightNext = - 0; - this._offsetNext = - 0; - - this.DefaultSettings_ = { - - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding - - }; - - } - - intervalChanged_( i1, t0, t1 ) { - - const pp = this.parameterPositions; - let iPrev = i1 - 2, - iNext = i1 + 1, - - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; - - if ( tPrev === undefined ) { - - switch ( this.getSettings_().endingStart ) { - - case ZeroSlopeEnding: - - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; - - break; - - case WrapAroundEnding: - - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - - break; - - default: // ZeroCurvatureEnding - - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; - - } - - } - - if ( tNext === undefined ) { - - switch ( this.getSettings_().endingEnd ) { - - case ZeroSlopeEnding: - - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; - - break; - - case WrapAroundEnding: - - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; - - break; - - default: // ZeroCurvatureEnding - - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; - - } - - } - - const halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; - - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; - - } - - interpolate_( i1, t0, t, t1 ) { - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, - - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; - - // evaluate polynomials - - const sP = - wP * ppp + 2 * wP * pp - wP * p; - const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; - const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - const sN = wN * ppp - wN * pp; - - // combine data linearly - - for ( let i = 0; i !== stride; ++ i ) { - - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; - - } - - return result; - - } - -} - -export { CubicInterpolant }; diff --git a/GameDev/bin/Release/xmleditor/math/interpolants/DiscreteInterpolant.js b/GameDev/bin/Release/xmleditor/math/interpolants/DiscreteInterpolant.js deleted file mode 100644 index 38ff2702..00000000 --- a/GameDev/bin/Release/xmleditor/math/interpolants/DiscreteInterpolant.js +++ /dev/null @@ -1,26 +0,0 @@ -import { Interpolant } from '../Interpolant.js'; - -/** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - */ - -class DiscreteInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - } - - interpolate_( i1 /*, t0, t, t1 */ ) { - - return this.copySampleValue_( i1 - 1 ); - - } - -} - - -export { DiscreteInterpolant }; diff --git a/GameDev/bin/Release/xmleditor/math/interpolants/LinearInterpolant.js b/GameDev/bin/Release/xmleditor/math/interpolants/LinearInterpolant.js deleted file mode 100644 index dae736e2..00000000 --- a/GameDev/bin/Release/xmleditor/math/interpolants/LinearInterpolant.js +++ /dev/null @@ -1,38 +0,0 @@ -import { Interpolant } from '../Interpolant.js'; - -class LinearInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - } - - interpolate_( i1, t0, t, t1 ) { - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - - offset1 = i1 * stride, - offset0 = offset1 - stride, - - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; - - for ( let i = 0; i !== stride; ++ i ) { - - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; - - } - - return result; - - } - -} - - -export { LinearInterpolant }; diff --git a/GameDev/bin/Release/xmleditor/math/interpolants/QuaternionLinearInterpolant.js b/GameDev/bin/Release/xmleditor/math/interpolants/QuaternionLinearInterpolant.js deleted file mode 100644 index 3b8bd4f2..00000000 --- a/GameDev/bin/Release/xmleditor/math/interpolants/QuaternionLinearInterpolant.js +++ /dev/null @@ -1,39 +0,0 @@ -import { Interpolant } from '../Interpolant.js'; -import { Quaternion } from '../Quaternion.js'; - -/** - * Spherical linear unit quaternion interpolant. - */ - -class QuaternionLinearInterpolant extends Interpolant { - - constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - - } - - interpolate_( i1, t0, t, t1 ) { - - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - - alpha = ( t - t0 ) / ( t1 - t0 ); - - let offset = i1 * stride; - - for ( let end = offset + stride; offset !== end; offset += 4 ) { - - Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); - - } - - return result; - - } - -} - - -export { QuaternionLinearInterpolant }; diff --git a/GameDev/bin/Release/xmleditor/project.json b/GameDev/bin/Release/xmleditor/project.json deleted file mode 100644 index 0e10adf8..00000000 --- a/GameDev/bin/Release/xmleditor/project.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "project_name": "xmleditor", - "targets": [ - { - "name": "Target", - "input": "index.js", - "output": "bundle_index.js", - "dirty": false - } - ] -} \ No newline at end of file diff --git a/GameDev/bin/Release/xmleditor/txml.js b/GameDev/bin/Release/xmleditor/txml.js deleted file mode 100644 index e1a81018..00000000 --- a/GameDev/bin/Release/xmleditor/txml.js +++ /dev/null @@ -1,482 +0,0 @@ -'use strict'; - -// ==ClosureCompiler== -// @output_file_name default.js -// @compilation_level SIMPLE_OPTIMIZATIONS -// ==/ClosureCompiler== -// module.exports = { -// parse: parse, -// simplify: simplify, -// simplifyLostLess: simplifyLostLess, -// filter: filter, -// stringify: stringify, -// toContentString: toContentString, -// getElementById: getElementById, -// getElementsByClassName: getElementsByClassName, -// transformStream: transformStream, -// }; - -/** - * @author: Tobias Nickel - * @created: 06.04.2015 - * I needed a small xmlparser chat can be used in a worker. - */ - -/** - * @typedef tNode - * @property {string} tagName - * @property {object} attributes - * @property {(tNode|string)[]} children - **/ - -/** - * @typedef TParseOptions - * @property {number} [pos] - * @property {string[]} [noChildNodes] - * @property {boolean} [setPos] - * @property {boolean} [keepComments] - * @property {boolean} [keepWhitespace] - * @property {boolean} [simplify] - * @property {(a: tNode, b: tNode) => boolean} [filter] - */ - -/** - * parseXML / html into a DOM Object. with no validation and some failur tolerance - * @param {string} S your XML to parse - * @param {TParseOptions} [options] all other options: - * @return {(tNode | string)[]} - */ -function parse(S, options) { - "txml"; - options = options || {}; - - var pos = options.pos || 0; - var keepComments = !!options.keepComments; - var keepWhitespace = !!options.keepWhitespace; - - var openBracket = "<"; - var openBracketCC = "<".charCodeAt(0); - var closeBracket = ">"; - var closeBracketCC = ">".charCodeAt(0); - var minusCC = "-".charCodeAt(0); - var slashCC = "/".charCodeAt(0); - var exclamationCC = '!'.charCodeAt(0); - var singleQuoteCC = "'".charCodeAt(0); - var doubleQuoteCC = '"'.charCodeAt(0); - var openCornerBracketCC = '['.charCodeAt(0); - var closeCornerBracketCC = ']'.charCodeAt(0); - - - /** - * parsing a list of entries - */ - function parseChildren(tagName) { - var children = []; - while (S[pos]) { - if (S.charCodeAt(pos) == openBracketCC) { - if (S.charCodeAt(pos + 1) === slashCC) { - var closeStart = pos + 2; - pos = S.indexOf(closeBracket, pos); - - var closeTag = S.substring(closeStart, pos); - if (closeTag.indexOf(tagName) == -1) { - var parsedText = S.substring(0, pos).split('\n'); - throw new Error( - 'Unexpected close tag\nLine: ' + (parsedText.length - 1) + - '\nColumn: ' + (parsedText[parsedText.length - 1].length + 1) + - '\nChar: ' + S[pos] - ); - } - - if (pos + 1) pos += 1; - - return children; - } else if (S.charCodeAt(pos + 1) === exclamationCC) { - if (S.charCodeAt(pos + 2) == minusCC) { - //comment support - const startCommentPos = pos; - while (pos !== -1 && !(S.charCodeAt(pos) === closeBracketCC && S.charCodeAt(pos - 1) == minusCC && S.charCodeAt(pos - 2) == minusCC && pos != -1)) { - pos = S.indexOf(closeBracket, pos + 1); - } - if (pos === -1) { - pos = S.length; - } - if (keepComments) { - children.push(S.substring(startCommentPos, pos + 1)); - } - } else if ( - S.charCodeAt(pos + 2) === openCornerBracketCC && - S.charCodeAt(pos + 8) === openCornerBracketCC && - S.substr(pos + 3, 5).toLowerCase() === 'cdata' - ) { - // cdata - var cdataEndIndex = S.indexOf(']]>', pos); - if (cdataEndIndex == -1) { - children.push(S.substr(pos + 9)); - pos = S.length; - } else { - children.push(S.substring(pos + 9, cdataEndIndex)); - pos = cdataEndIndex + 3; - } - continue; - } else { - // doctypesupport - const startDoctype = pos + 1; - pos += 2; - var encapsuled = false; - while ((S.charCodeAt(pos) !== closeBracketCC || encapsuled === true) && S[pos]) { - if (S.charCodeAt(pos) === openCornerBracketCC) { - encapsuled = true; - } else if (encapsuled === true && S.charCodeAt(pos) === closeCornerBracketCC) { - encapsuled = false; - } - pos++; - } - children.push(S.substring(startDoctype, pos)); - } - pos++; - continue; - } - var node = parseNode(); - children.push(node); - if (node.tagName[0] === '?') { - children.push(...node.children); - node.children = []; - } - } else { - var text = parseText(); - if (keepWhitespace) { - if (text.length > 0) { - children.push(text); - } - } else { - var trimmed = text.trim(); - if (trimmed.length > 0) { - children.push(trimmed); - } - } - pos++; - } - } - return children; - } - - /** - * returns the text outside of texts until the first '<' - */ - function parseText() { - var start = pos; - pos = S.indexOf(openBracket, pos) - 1; - if (pos === -2) - pos = S.length; - return S.slice(start, pos + 1); - } - /** - * returns text until the first nonAlphabetic letter - */ - var nameSpacer = '\r\n\t>/= '; - - function parseName() { - var start = pos; - while (nameSpacer.indexOf(S[pos]) === -1 && S[pos]) { - pos++; - } - return S.slice(start, pos); - } - /** - * is parsing a node, including tagName, Attributes and its children, - * to parse children it uses the parseChildren again, that makes the parsing recursive - */ - var NoChildNodes = options.noChildNodes || ['img', 'br', 'input', 'meta', 'link', 'hr']; - - function parseNode() { - pos++; - const tagName = parseName(); - const attributes = {}; - let children = []; - - // parsing attributes - while (S.charCodeAt(pos) !== closeBracketCC && S[pos]) { - var c = S.charCodeAt(pos); - if ((c > 64 && c < 91) || (c > 96 && c < 123)) { - //if('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(S[pos])!==-1 ){ - var name = parseName(); - // search beginning of the string - var code = S.charCodeAt(pos); - while (code && code !== singleQuoteCC && code !== doubleQuoteCC && !((code > 64 && code < 91) || (code > 96 && code < 123)) && code !== closeBracketCC) { - pos++; - code = S.charCodeAt(pos); - } - if (code === singleQuoteCC || code === doubleQuoteCC) { - var value = parseString(); - if (pos === -1) { - return { - tagName, - attributes, - children, - }; - } - } else { - value = null; - pos--; - } - attributes[name] = value; - } - pos++; - } - // optional parsing of children - if (S.charCodeAt(pos - 1) !== slashCC) { - if (tagName == "script") { - var start = pos + 1; - pos = S.indexOf('', pos); - children = [S.slice(start, pos)]; - pos += 9; - } else if (tagName == "style") { - var start = pos + 1; - pos = S.indexOf('', pos); - children = [S.slice(start, pos)]; - pos += 8; - } else if (NoChildNodes.indexOf(tagName) === -1) { - pos++; - children = parseChildren(tagName); - } else { - pos++; - } - } else { - pos++; - } - return { - tagName, - attributes, - children, - }; - } - - /** - * is parsing a string, that starts with a char and with the same usually ' or " - */ - - function parseString() { - var startChar = S[pos]; - var startpos = pos + 1; - pos = S.indexOf(startChar, startpos); - return S.slice(startpos, pos); - } - - /** - * - */ - function findElements() { - var r = new RegExp('\\s' + options.attrName + '\\s*=[\'"]' + options.attrValue + '[\'"]').exec(S); - if (r) { - return r.index; - } else { - return -1; - } - } - - var out = null; - if (options.attrValue !== undefined) { - options.attrName = options.attrName || 'id'; - var out = []; - - while ((pos = findElements()) !== -1) { - pos = S.lastIndexOf('<', pos); - if (pos !== -1) { - out.push(parseNode()); - } - S = S.substr(pos); - pos = 0; - } - } else if (options.parseNode) { - out = parseNode(); - } else { - out = parseChildren(''); - } - - if (options.filter) { - out = filter(out, options.filter); - } - - if (options.simplify) { - return simplify(Array.isArray(out) ? out : [out]); - } - - if (options.setPos) { - out.pos = pos; - } - - return out; -} - -/** - * transform the DomObject to an object that is like the object of PHP`s simple_xmp_load_*() methods. - * this format helps you to write that is more likely to keep your program working, even if there a small changes in the XML schema. - * be aware, that it is not possible to reproduce the original xml from a simplified version, because the order of elements is not saved. - * therefore your program will be more flexible and easier to read. - * - * @param {tNode[]} children the childrenList - */ -function simplify(children) { - var out = {}; - if (!children.length) { - return ''; - } - - if (children.length === 1 && typeof children[0] == 'string') { - return children[0]; - } - // map each object - children.forEach(function(child) { - if (typeof child !== 'object') { - return; - } - if (!out[child.tagName]) - out[child.tagName] = []; - var kids = simplify(child.children); - out[child.tagName].push(kids); - if (Object.keys(child.attributes).length && typeof kids !== 'string') { - kids._attributes = child.attributes; - } - }); - - for (var i in out) { - if (out[i].length == 1) { - out[i] = out[i][0]; - } - } - - return out; -} - -/** - * similar to simplify, but lost less - * - * @param {tNode[]} children the childrenList - */ -function simplifyLostLess(children, parentAttributes = {}) { - var out = {}; - if (!children.length) { - return out; - } - - if (children.length === 1 && typeof children[0] == 'string') { - return Object.keys(parentAttributes).length ? { - _attributes: parentAttributes, - value: children[0] - } : children[0]; - } - // map each object - children.forEach(function(child) { - if (typeof child !== 'object') { - return; - } - if (!out[child.tagName]) - out[child.tagName] = []; - var kids = simplifyLostLess(child.children || [], child.attributes); - out[child.tagName].push(kids); - if (Object.keys(child.attributes).length) { - kids._attributes = child.attributes; - } - }); - - return out; -} -/** - * behaves the same way as Array.filter, if the filter method return true, the element is in the resultList - * @params children{Array} the children of a node - * @param f{function} the filter method - */ -function filter(children, f, dept = 0, path = '') { - var out = []; - children.forEach(function(child, i) { - if (typeof(child) === 'object' && f(child, i, dept, path)) out.push(child); - if (child.children) { - var kids = filter(child.children, f, dept + 1, (path ? path + '.' : '') + i + '.' + child.tagName); - out = out.concat(kids); - } - }); - return out; -} -/** - * stringify a previously parsed string object. - * this is useful, - * 1. to remove whitespace - * 2. to recreate xml data, with some changed data. - * @param {tNode} O the object to Stringify - */ -function stringify(O) { - var out = ''; - - function writeChildren(O) { - if (O) { - for (var i = 0; i < O.length; i++) { - if (typeof O[i] == 'string') { - out += O[i].trim(); - } else { - writeNode(O[i]); - } - } - } - } - - function writeNode(N) { - out += "<" + N.tagName; - for (var i in N.attributes) { - if (N.attributes[i] === null) { - out += ' ' + i; - } else if (N.attributes[i].indexOf('"') === -1) { - out += ' ' + i + '="' + N.attributes[i].trim() + '"'; - } else { - out += ' ' + i + "='" + N.attributes[i].trim() + "'"; - } - } - if (N.tagName[0] === '?') { - out += '?>'; - return; - } - out += '>'; - writeChildren(N.children); - out += ''; - } - writeChildren(O); - - return out; -} - -/** - * use this method to read the text content, of some node. - * It is great if you have mixed content like: - * this text has some big text and a link - * @return {string} - */ -function toContentString(tDom) { - if (Array.isArray(tDom)) { - var out = ''; - tDom.forEach(function(e) { - out += ' ' + toContentString(e); - out = out.trim(); - }); - return out; - } else if (typeof tDom === 'object') { - return toContentString(tDom.children) - } else { - return ' ' + tDom; - } -} -function getElementById(S, id, simplified) { - var out = parse(S, { - attrValue: id - }); - return simplified ? tXml.simplify(out) : out[0]; -} -function getElementsByClassName(S, classname, simplified) { - const out = parse(S, { - attrName: 'class', - attrValue: '[a-zA-Z0-9- ]*' + classname + '[a-zA-Z0-9- ]*' - }); - return simplified ? tXml.simplify(out) : out; -} - -export { filter, getElementById, getElementsByClassName, parse, simplify, simplifyLostLess, stringify, toContentString }; - diff --git a/GameDev/bin/Release/xmleditor/utils/Clock.js b/GameDev/bin/Release/xmleditor/utils/Clock.js deleted file mode 100644 index 94cae91e..00000000 --- a/GameDev/bin/Release/xmleditor/utils/Clock.js +++ /dev/null @@ -1,68 +0,0 @@ -class Clock { - - constructor( autoStart = true ) { - - this.autoStart = autoStart; - - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; - - this.running = false; - - } - - start() { - - this.startTime = now(); - - this.oldTime = this.startTime; - this.elapsedTime = 0; - this.running = true; - - } - - stop() { - - this.getElapsedTime(); - this.running = false; - this.autoStart = false; - - } - - getElapsedTime() { - - this.getDelta(); - return this.elapsedTime; - - } - - getDelta() { - - let diff = 0; - - if ( this.autoStart && ! this.running ) { - - this.start(); - return 0; - - } - - if ( this.running ) { - - const newTime = now(); - - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; - - this.elapsedTime += diff; - - } - - return diff; - - } - -} - -export { Clock }; diff --git a/GameDev/bin/Release/xmleditor/view.js b/GameDev/bin/Release/xmleditor/view.js deleted file mode 100644 index 6f179efb..00000000 --- a/GameDev/bin/Release/xmleditor/view.js +++ /dev/null @@ -1,155 +0,0 @@ -import { EventDispatcher } from "./controls/EventDispatcher.js"; - -class View extends EventDispatcher { - - get clientWidth() { - return gamePlayer.width; - } - - get clientHeight() { - return gamePlayer.height; - } - - setPointerCapture() { - gamePlayer.message("setPointerCapture", ""); - } - - releasePointerCapture() { - gamePlayer.message("releasePointerCapture", ""); - } -} - -const view = new View(); - -function makeMouseEvent(e, type) { - let event = { - type: type, - pointerType: "mouse", - pointerId: 0, - clientX: e.x, - clientY: e.y, - deltaY: e.delta, - button: e.button - }; - - return event; -} - -function OnMouseDown(e) { - let event = makeMouseEvent(e, "pointerdown"); - view.dispatchEvent(event); -} - -function OnMouseUp(e) { - let event = makeMouseEvent(e, "pointerup"); - view.dispatchEvent(event); -} - -function OnMouseMove(e) { - let event = makeMouseEvent(e, "pointermove"); - view.dispatchEvent(event); -} - -function OnMouseWheel(e) { - let event = makeMouseEvent(e, "wheel"); - view.dispatchEvent(event); -} - -setCallback('OnMouseDown', OnMouseDown); -setCallback('OnMouseUp', OnMouseUp); -setCallback('OnMouseMove', OnMouseMove); -setCallback('OnMouseWheel', OnMouseWheel); - - -function makeTouchEvent(e, type) { - let event = { - type: type, - pointerType: "touch", - pointerId: e.pointerId, - pageX: e.x, - pageY: e.y, - deltaY: 0, - button: -1 - }; - - return event; -} - -function OnTouchDown(e) { - let event = makeTouchEvent(e, "pointerdown"); - view.dispatchEvent(event); -} - -function OnTouchUp(e) { - let event = makeTouchEvent(e, "pointerup"); - view.dispatchEvent(event); -} - -function OnTouchMove(e) { - let event = makeTouchEvent(e, "pointermove"); - view.dispatchEvent(event); -} - -setCallback('OnTouchDown', OnTouchDown); -setCallback('OnTouchUp', OnTouchUp); -setCallback('OnTouchMove', OnTouchMove); - - -class UIViewDispatcher extends EventDispatcher { - - constructor(view3d){ - super(); - this.view = view3d; - view3d.onMouseDown = (e)=>{ - let event = makeMouseEvent(e, "pointerdown"); - this.dispatchEvent(event); - }; - view3d.onMouseUp = (e)=>{ - let event = makeMouseEvent(e, "pointerup"); - this.dispatchEvent(event); - }; - view3d.onMouseMove = (e)=>{ - let event = makeMouseEvent(e, "pointermove"); - this.dispatchEvent(event); - }; - view3d.onMouseWheel = (e)=>{ - let event = makeMouseEvent(e, "wheel"); - this.dispatchEvent(event); - }; - view3d.onTouchDown = (e)=>{ - let event = makeTouchEvent(e, "pointerdown"); - print(JSON.stringify(event)); - this.dispatchEvent(event); - } - view3d.onTouchUp = (e)=>{ - let event = makeTouchEvent(e, "pointerup"); - print(JSON.stringify(event)); - this.dispatchEvent(event); - } - view3d.onTouchMove = (e)=>{ - let event = makeTouchEvent(e, "pointermove"); - print(JSON.stringify(event)); - this.dispatchEvent(event); - } - } - - get clientWidth() { - return this.view.size.x; - } - - get clientHeight() { - return this.view.size.y; - } - - setPointerCapture() { - gamePlayer.message("setPointerCapture", ""); - } - - releasePointerCapture() { - gamePlayer.message("releasePointerCapture", ""); - } -} - - -export { view, UIViewDispatcher }; - diff --git a/GameDev/bin/Release/zlib.dll b/GameDev/bin/Release/zlib.dll deleted file mode 100644 index ebe9bb48..00000000 Binary files a/GameDev/bin/Release/zlib.dll and /dev/null differ diff --git a/GameDev/icons/avatar.png b/GameDev/icons/avatar.png deleted file mode 100644 index 19b0bd42..00000000 Binary files a/GameDev/icons/avatar.png and /dev/null differ diff --git a/GameDev/icons/box.png b/GameDev/icons/box.png deleted file mode 100644 index 3ec13898..00000000 Binary files a/GameDev/icons/box.png and /dev/null differ diff --git a/GameDev/icons/camera.png b/GameDev/icons/camera.png deleted file mode 100644 index b77948e2..00000000 Binary files a/GameDev/icons/camera.png and /dev/null differ diff --git a/GameDev/icons/control.png b/GameDev/icons/control.png deleted file mode 100644 index a8b567ec..00000000 Binary files a/GameDev/icons/control.png and /dev/null differ diff --git a/GameDev/icons/directional_light.png b/GameDev/icons/directional_light.png deleted file mode 100644 index eb69db93..00000000 Binary files a/GameDev/icons/directional_light.png and /dev/null differ diff --git a/GameDev/icons/doc.png b/GameDev/icons/doc.png deleted file mode 100644 index 1d0858a6..00000000 Binary files a/GameDev/icons/doc.png and /dev/null differ diff --git a/GameDev/icons/env_light.png b/GameDev/icons/env_light.png deleted file mode 100644 index 6521cffc..00000000 Binary files a/GameDev/icons/env_light.png and /dev/null differ diff --git a/GameDev/icons/fog.png b/GameDev/icons/fog.png deleted file mode 100644 index ecc7851c..00000000 Binary files a/GameDev/icons/fog.png and /dev/null differ diff --git a/GameDev/icons/folder.png b/GameDev/icons/folder.png deleted file mode 100644 index 100a1aba..00000000 Binary files a/GameDev/icons/folder.png and /dev/null differ diff --git a/GameDev/icons/group.png b/GameDev/icons/group.png deleted file mode 100644 index 58c6c211..00000000 Binary files a/GameDev/icons/group.png and /dev/null differ diff --git a/GameDev/icons/js.png b/GameDev/icons/js.png deleted file mode 100644 index 0dd1df37..00000000 Binary files a/GameDev/icons/js.png and /dev/null differ diff --git a/GameDev/icons/json.png b/GameDev/icons/json.png deleted file mode 100644 index 17db63d3..00000000 Binary files a/GameDev/icons/json.png and /dev/null differ diff --git a/GameDev/icons/model.png b/GameDev/icons/model.png deleted file mode 100644 index 034578e0..00000000 Binary files a/GameDev/icons/model.png and /dev/null differ diff --git a/GameDev/icons/object3d.png b/GameDev/icons/object3d.png deleted file mode 100644 index 890ca18c..00000000 Binary files a/GameDev/icons/object3d.png and /dev/null differ diff --git a/GameDev/icons/plane.png b/GameDev/icons/plane.png deleted file mode 100644 index a2064c3f..00000000 Binary files a/GameDev/icons/plane.png and /dev/null differ diff --git a/GameDev/icons/scene.png b/GameDev/icons/scene.png deleted file mode 100644 index 74fd7e84..00000000 Binary files a/GameDev/icons/scene.png and /dev/null differ diff --git a/GameDev/icons/sky.png b/GameDev/icons/sky.png deleted file mode 100644 index 9bc32133..00000000 Binary files a/GameDev/icons/sky.png and /dev/null differ diff --git a/GameDev/icons/sphere.png b/GameDev/icons/sphere.png deleted file mode 100644 index bdf9e687..00000000 Binary files a/GameDev/icons/sphere.png and /dev/null differ diff --git a/GameDev/icons/target.png b/GameDev/icons/target.png deleted file mode 100644 index 251fce75..00000000 Binary files a/GameDev/icons/target.png and /dev/null differ diff --git a/GameDev/icons/xml.png b/GameDev/icons/xml.png deleted file mode 100644 index 88395d91..00000000 Binary files a/GameDev/icons/xml.png and /dev/null differ diff --git a/GamePlayer/App.config b/GamePlayer/App.config deleted file mode 100644 index 56efbc7b..00000000 --- a/GamePlayer/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/GamePlayer/App.xaml b/GamePlayer/App.xaml deleted file mode 100644 index 5ad50234..00000000 --- a/GamePlayer/App.xaml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/GamePlayer/App.xaml.cs b/GamePlayer/App.xaml.cs deleted file mode 100644 index d5c43a80..00000000 --- a/GamePlayer/App.xaml.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.IO; -using System.Windows; - -namespace GamePlayer -{ - /// - /// Interaction logic for App.xaml - /// - public partial class App : Application - { - private void Application_Startup(object sender, StartupEventArgs e) - { - if (e.Args.Length > 1) - { - string path_proj = e.Args[0]; - int idx = int.Parse(e.Args[1]); - this.MainWindow = new PlayerWindow(path_proj, idx); - } - else if (File.Exists(".\\client\\project.json")) - { - this.MainWindow = new PlayerWindow(".\\client\\project.json", 0); - } - else - { - this.MainWindow = new MainWindow(); - } - - this.MainWindow.Show(); - } - } -} diff --git a/GamePlayer/GamePlayer.csproj b/GamePlayer/GamePlayer.csproj deleted file mode 100644 index d6204444..00000000 --- a/GamePlayer/GamePlayer.csproj +++ /dev/null @@ -1,122 +0,0 @@ - - - - - Debug - AnyCPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2} - WinExe - GamePlayer - GamePlayer - v4.7.2 - 512 - {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 4 - true - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x64 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - 4.0 - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - App.xaml - Code - - - MainWindow.xaml - Code - - - MSBuild:Compile - Designer - - - - - PlayerWindow.xaml - - - Code - - - True - True - Resources.resx - - - True - Settings.settings - True - - - ResXFileCodeGenerator - Resources.Designer.cs - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - - - - - - {8accb6bd-c7b1-4a80-91d5-53cf222b716a} - Three.V8.CLR - - - - - 13.0.2 - - - - \ No newline at end of file diff --git a/GamePlayer/MainWindow.xaml b/GamePlayer/MainWindow.xaml deleted file mode 100644 index 506b329e..00000000 --- a/GamePlayer/MainWindow.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - diff --git a/GamePlayer/MainWindow.xaml.cs b/GamePlayer/MainWindow.xaml.cs deleted file mode 100644 index 692cf026..00000000 --- a/GamePlayer/MainWindow.xaml.cs +++ /dev/null @@ -1,211 +0,0 @@ -using System; -using System.Timers; -using System.Windows; -using System.Diagnostics; -using Microsoft.Win32; -using CLRBinding; - -namespace GamePlayer -{ - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainWindow : Window - { - private CGLControl glControl = null; - private CGamePlayer game_player = null; - private string default_script = "../../../game/bundle_game.js"; - private bool is_portrait = false; - - - public MainWindow() - { - InitializeComponent(); - glControl = new CGLControl(); - glControl.SetFramerate(60.0f); - glControl.Paint += GLControl_Paint; - glControl.Dock = System.Windows.Forms.DockStyle.Fill; - glControl.MouseDown += GLControl_MouseDown; - glControl.MouseUp += GLControl_MouseUp; - glControl.MouseMove += GLControl_MouseMove; - glControl.MouseWheel += GLControl_MouseWheel; - glControl.KeyPress += GLControl_KeyChar; - glControl.ControlKey += GLControl_ControlKey; - wf_host.Child = glControl; - - string exe_name = Process.GetCurrentProcess().ProcessName; - game_player = new CGamePlayer(exe_name, glControl); - game_player.LoadScript(default_script, null); - } - - private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) - { - glControl.MakeCurrent(); - game_player.Dispose(); - game_player = null; - } - - private void GLControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e) - { - if (game_player == null) return; - game_player.Draw(glControl.Width, glControl.Height); - } - - private void BtnLoad_Click(object sender, RoutedEventArgs e) - { - if (game_player == null) return; - OpenFileDialog openFileDialog = new OpenFileDialog(); - openFileDialog.Filter = "Script Files|*.js"; - if (openFileDialog.ShowDialog() == true) - { - glControl.MakeCurrent(); - game_player.LoadScript(openFileDialog.FileName, null); - } - } - - private MouseEventArgs convert_args(System.Windows.Forms.MouseEventArgs e) - { - int button = -1; - if (e.Button == System.Windows.Forms.MouseButtons.Left) - { - button = 0; - } - else if (e.Button == System.Windows.Forms.MouseButtons.Middle) - { - button = 1; - } - else if (e.Button == System.Windows.Forms.MouseButtons.Right) - { - button = 2; - } - else if (e.Button == System.Windows.Forms.MouseButtons.XButton1) - { - button = 3; - } - else if (e.Button == System.Windows.Forms.MouseButtons.XButton2) - { - button = 4; - } - - MouseEventArgs args; - args.button = button; - args.clicks = e.Clicks; - args.delta = e.Delta; - args.x = e.X; - args.y = e.Y; - return args; - } - - private Timer press_timer = null; - private int x_down; - private int y_down; - - private void GLControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.Focus(); - glControl.MakeCurrent(); - game_player.OnMouseDown(convert_args(e)); - - if (e.Button == System.Windows.Forms.MouseButtons.Left) - { - x_down = e.X; - y_down = e.Y; - - press_timer = new Timer(); - press_timer.Elapsed += (source, timer_event) => - { - Dispatcher.Invoke(() => - { - press_timer = null; - game_player.OnLongPress(x_down, y_down); - }); - - }; - press_timer.AutoReset = false; - press_timer.Interval = 500.0; - press_timer.Start(); - } - } - - private void GLControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseUp(convert_args(e)); - - if (press_timer!=null) - { - press_timer.Stop(); - press_timer = null; - } - } - - private void GLControl_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseMove(convert_args(e)); - - if (press_timer != null) - { - int x = e.X; - int y = e.Y; - - int dx = x - x_down; - int dy = y - y_down; - double dis = Math.Sqrt((double)(dx * dx) + (double)(dy * dy)); - if (dis>3.0) - { - press_timer.Stop(); - press_timer = null; - } - - } - } - - private void GLControl_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseWheel(convert_args(e)); - } - - private void GLControl_ControlKey(uint code) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnControlKey(code); - } - - private void GLControl_KeyChar(object sender, System.Windows.Forms.KeyPressEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnChar(e.KeyChar); - e.Handled = true; - } - - private void btn_rotate_Click(object sender, RoutedEventArgs e) - { - if (!is_portrait) - { - this.Width = 500; - this.Height = 720; - wf_host.Width = 360; - wf_host.Height = 640; - btn_rotate.Content = "To Landscape"; - is_portrait = true; - } - else - { - this.Width = 800; - this.Height = 450; - wf_host.Width = 640; - wf_host.Height = 360; - btn_rotate.Content = "To Portrait"; - is_portrait = false; - } - } - } -} diff --git a/GamePlayer/PlayerWindow.xaml b/GamePlayer/PlayerWindow.xaml deleted file mode 100644 index 0bfb1708..00000000 --- a/GamePlayer/PlayerWindow.xaml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/GamePlayer/PlayerWindow.xaml.cs b/GamePlayer/PlayerWindow.xaml.cs deleted file mode 100644 index c20099c9..00000000 --- a/GamePlayer/PlayerWindow.xaml.cs +++ /dev/null @@ -1,238 +0,0 @@ -using System; -using System.IO; -using System.Timers; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; -using System.Diagnostics; -using Newtonsoft.Json.Linq; -using CLRBinding; - -namespace GamePlayer -{ - /// - /// Interaction logic for PlayerWindow.xaml - /// - public partial class PlayerWindow : Window - { - private CGLControl glControl = null; - private CGamePlayer game_player = null; - - - public PlayerWindow(string path_proj, int idx) - { - InitializeComponent(); - - JObject obj_proj = JObject.Parse(File.ReadAllText(path_proj)); - JObject obj_target = (JObject)obj_proj["targets"][idx]; - - string dir_proj = Path.GetDirectoryName(path_proj); - string path_output = Path.GetFullPath(dir_proj + "\\" + obj_target["output"].ToString()); - - Title = obj_target["name"].ToString(); - - if (obj_target.ContainsKey("width") && obj_target.ContainsKey("height")) - { - this.Width = int.Parse(obj_target["width"].ToString()) + 36.0; - this.Height = int.Parse(obj_target["height"].ToString()) + 64.0; - } - - glControl = new CGLControl(); - glControl.SetFramerate(60.0f); - glControl.Paint += GLControl_Paint; - glControl.Dock = System.Windows.Forms.DockStyle.Fill; - glControl.MouseDown += GLControl_MouseDown; - glControl.MouseUp += GLControl_MouseUp; - glControl.MouseMove += GLControl_MouseMove; - glControl.MouseWheel += GLControl_MouseWheel; - glControl.KeyPress += GLControl_KeyChar; - glControl.ControlKey += GLControl_ControlKey; - wf_host.Child = glControl; - - string exe_name = Process.GetCurrentProcess().ProcessName; - game_player = new CGamePlayer(exe_name, glControl); - game_player.SetPrintCallbacks(console_std, console_err); - game_player.LoadScript(path_output, null); - - } - - private Thickness thickness_zero = new Thickness(0); - private FontFamily font_courier = new FontFamily("Courier New"); - private SolidColorBrush brush_red = new SolidColorBrush(Colors.Red); - - private void console_log(string str_line, Brush brush = null) - { - var line = new TextBox(); - line.BorderThickness = thickness_zero; - line.IsReadOnly = true; - line.FontFamily = font_courier; - if (brush != null) - { - line.Foreground = brush; - } - line.Text = str_line; - console.Children.Add(line); - } - - private void console_std(string str) - { - string[] lines = str.Split(new char[]{'\n'}); - foreach(string str_line in lines) - { - console_log(str_line); - } - console_scroll.ScrollToBottom(); - } - - private void console_err(string str) - { - string[] lines = str.Split(new char[] { '\n' }); - foreach (string str_line in lines) - { - console_log(str_line, brush_red); - } - console_scroll.ScrollToBottom(); - } - - private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) - { - glControl.MakeCurrent(); - game_player.Dispose(); - game_player = null; - } - - private void GLControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e) - { - if (game_player == null) return; - game_player.Draw(glControl.Width, glControl.Height); - } - - private MouseEventArgs convert_args(System.Windows.Forms.MouseEventArgs e) - { - int button = -1; - if (e.Button == System.Windows.Forms.MouseButtons.Left) - { - button = 0; - } - else if (e.Button == System.Windows.Forms.MouseButtons.Middle) - { - button = 1; - } - else if (e.Button == System.Windows.Forms.MouseButtons.Right) - { - button = 2; - } - else if (e.Button == System.Windows.Forms.MouseButtons.XButton1) - { - button = 3; - } - else if (e.Button == System.Windows.Forms.MouseButtons.XButton2) - { - button = 4; - } - - MouseEventArgs args; - args.button = button; - args.clicks = e.Clicks; - args.delta = e.Delta; - args.x = e.X; - args.y = e.Y; - return args; - } - - private Timer press_timer = null; - private int x_down; - private int y_down; - - private void GLControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.Focus(); - glControl.MakeCurrent(); - game_player.OnMouseDown(convert_args(e)); - - if (e.Button == System.Windows.Forms.MouseButtons.Left) - { - x_down = e.X; - y_down = e.Y; - - press_timer = new Timer(); - press_timer.Elapsed += (source, timer_event) => - { - Dispatcher.Invoke(() => - { - press_timer = null; - game_player.OnLongPress(x_down, y_down); - }); - - }; - press_timer.AutoReset = false; - press_timer.Interval = 500.0; - press_timer.Start(); - } - } - - private void GLControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseUp(convert_args(e)); - - if (press_timer != null) - { - press_timer.Stop(); - press_timer = null; - } - } - - private void GLControl_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseMove(convert_args(e)); - - if (press_timer != null) - { - int x = e.X; - int y = e.Y; - - int dx = x - x_down; - int dy = y - y_down; - double dis = Math.Sqrt((double)(dx * dx) + (double)(dy * dy)); - if (dis > 3.0) - { - press_timer.Stop(); - press_timer = null; - } - - } - } - - private void GLControl_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnMouseWheel(convert_args(e)); - } - - private void GLControl_ControlKey(uint code) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnControlKey(code); - } - - private void GLControl_KeyChar(object sender, System.Windows.Forms.KeyPressEventArgs e) - { - if (game_player == null) return; - glControl.MakeCurrent(); - game_player.OnChar(e.KeyChar); - e.Handled = true; - } - - private void menu_clear_console_Click(object sender, RoutedEventArgs e) - { - console.Children.Clear(); - } - } -} diff --git a/GamePlayer/Properties/AssemblyInfo.cs b/GamePlayer/Properties/AssemblyInfo.cs deleted file mode 100644 index 099f71f4..00000000 --- a/GamePlayer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Windows; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("GamePlayer")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("GamePlayer")] -[assembly: AssemblyCopyright("Copyright © 2022")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -//In order to begin building localizable applications, set -//CultureYouAreCodingWith in your .csproj file -//inside a . For example, if you are using US english -//in your source files, set the to en-US. Then uncomment -//the NeutralResourceLanguage attribute below. Update the "en-US" in -//the line below to match the UICulture setting in the project file. - -//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] - - -[assembly: ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) -)] - - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/GamePlayer/Properties/Resources.Designer.cs b/GamePlayer/Properties/Resources.Designer.cs deleted file mode 100644 index c1c7e76b..00000000 --- a/GamePlayer/Properties/Resources.Designer.cs +++ /dev/null @@ -1,70 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - - -namespace GamePlayer.Properties -{ - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GamePlayer.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { - return resourceCulture; - } - set - { - resourceCulture = value; - } - } - } -} diff --git a/GamePlayer/Properties/Resources.resx b/GamePlayer/Properties/Resources.resx deleted file mode 100644 index af7dbebb..00000000 --- a/GamePlayer/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/GamePlayer/Properties/Settings.Designer.cs b/GamePlayer/Properties/Settings.Designer.cs deleted file mode 100644 index a0ce3539..00000000 --- a/GamePlayer/Properties/Settings.Designer.cs +++ /dev/null @@ -1,29 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - - -namespace GamePlayer.Properties -{ - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { - return defaultInstance; - } - } - } -} diff --git a/GamePlayer/Properties/Settings.settings b/GamePlayer/Properties/Settings.settings deleted file mode 100644 index 033d7a5e..00000000 --- a/GamePlayer/Properties/Settings.settings +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/GamePlayer/bin/Release/avcodec-58.dll b/GamePlayer/bin/Release/avcodec-58.dll deleted file mode 100644 index fe98cee2..00000000 Binary files a/GamePlayer/bin/Release/avcodec-58.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/avdevice-58.dll b/GamePlayer/bin/Release/avdevice-58.dll deleted file mode 100644 index 2fa0acf6..00000000 Binary files a/GamePlayer/bin/Release/avdevice-58.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/avfilter-7.dll b/GamePlayer/bin/Release/avfilter-7.dll deleted file mode 100644 index 1e36c5ed..00000000 Binary files a/GamePlayer/bin/Release/avfilter-7.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/avformat-58.dll b/GamePlayer/bin/Release/avformat-58.dll deleted file mode 100644 index 4f875564..00000000 Binary files a/GamePlayer/bin/Release/avformat-58.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/avutil-56.dll b/GamePlayer/bin/Release/avutil-56.dll deleted file mode 100644 index 29fdb519..00000000 Binary files a/GamePlayer/bin/Release/avutil-56.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/icudtl.dat b/GamePlayer/bin/Release/icudtl.dat deleted file mode 100644 index 0e35d1da..00000000 Binary files a/GamePlayer/bin/Release/icudtl.dat and /dev/null differ diff --git a/GamePlayer/bin/Release/icui18n.dll b/GamePlayer/bin/Release/icui18n.dll deleted file mode 100644 index ea9a114b..00000000 Binary files a/GamePlayer/bin/Release/icui18n.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/icuuc.dll b/GamePlayer/bin/Release/icuuc.dll deleted file mode 100644 index 6be4c8f0..00000000 Binary files a/GamePlayer/bin/Release/icuuc.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/postproc-55.dll b/GamePlayer/bin/Release/postproc-55.dll deleted file mode 100644 index e51df89e..00000000 Binary files a/GamePlayer/bin/Release/postproc-55.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/swresample-3.dll b/GamePlayer/bin/Release/swresample-3.dll deleted file mode 100644 index b2492ed0..00000000 Binary files a/GamePlayer/bin/Release/swresample-3.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/swscale-5.dll b/GamePlayer/bin/Release/swscale-5.dll deleted file mode 100644 index 3315062c..00000000 Binary files a/GamePlayer/bin/Release/swscale-5.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/v8.dll b/GamePlayer/bin/Release/v8.dll deleted file mode 100644 index 7737c6ae..00000000 Binary files a/GamePlayer/bin/Release/v8.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/v8_libbase.dll b/GamePlayer/bin/Release/v8_libbase.dll deleted file mode 100644 index 419e0f91..00000000 Binary files a/GamePlayer/bin/Release/v8_libbase.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/v8_libplatform.dll b/GamePlayer/bin/Release/v8_libplatform.dll deleted file mode 100644 index fb940ec9..00000000 Binary files a/GamePlayer/bin/Release/v8_libplatform.dll and /dev/null differ diff --git a/GamePlayer/bin/Release/zlib.dll b/GamePlayer/bin/Release/zlib.dll deleted file mode 100644 index ebe9bb48..00000000 Binary files a/GamePlayer/bin/Release/zlib.dll and /dev/null differ diff --git a/Three.V8.CLR/CLRBinding.cpp b/Three.V8.CLR/CLRBinding.cpp deleted file mode 100644 index 3b49ec3e..00000000 --- a/Three.V8.CLR/CLRBinding.cpp +++ /dev/null @@ -1,339 +0,0 @@ -#include "CLRBinding.h" - -#pragma unmanaged -#include -#include -#include -#include "utils/Utils.h" -#pragma comment(lib, "opengl32.lib") -#pragma comment(lib, "gdi32.lib") -#pragma managed - -using namespace System::IO; - -namespace CLRBinding -{ - - public delegate void TimerCallback(); - static void __stdcall s_timer_callback(PTP_CALLBACK_INSTANCE, PVOID p_func_invalidate, PTP_TIMER timer) - { - GCHandle handle = GCHandle::FromIntPtr((IntPtr)p_func_invalidate); - TimerCallback^ func_invalidate = (TimerCallback^)handle.Target; - func_invalidate(); - } - - CGLControl::CGLControl() - { - SetStyle(ControlStyles::Opaque, true); - SetStyle(ControlStyles::UserPaint, true); - SetStyle(ControlStyles::AllPaintingInWmPaint, true); - SetStyle(ControlStyles::Selectable, true); - DoubleBuffered = false; - - - m_func_invalidate = GCHandle::Alloc(gcnew TimerCallback(this, &CGLControl::Invalidate), GCHandleType::Normal); - IntPtr p_func_invalidate = GCHandle::ToIntPtr(m_func_invalidate); - m_timer = CreateThreadpoolTimer(s_timer_callback, (void*)p_func_invalidate, nullptr); - - PIXELFORMATDESCRIPTOR pfd = - { - sizeof(PIXELFORMATDESCRIPTOR), - 1, - PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED | PFD_DOUBLEBUFFER, // Flags - PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette. - 32, // Colordepth of the framebuffer. - 0, 0, 0, 0, 0, 0, - 0, - 0, - 0, - 0, 0, 0, 0, - 24, // Number of bits for the depthbuffer - 8, // Number of bits for the stencilbuffer - 0, // Number of Aux buffers in the framebuffer. - PFD_MAIN_PLANE, - 0, - 0, 0, 0 - }; - - HWND hwnd = (HWND)(void*)this->Handle; - m_hdc = GetDC(hwnd); - int pfm = ChoosePixelFormat(m_hdc, &pfd); - SetPixelFormat(m_hdc, pfm, &pfd); - m_hrc = wglCreateContext(m_hdc); - wglMakeCurrent(m_hdc, m_hrc); - glewInit(); - } - - CGLControl::!CGLControl() - { - if (m_hdc != nullptr) - { - wglMakeCurrent(m_hdc, NULL); - wglDeleteContext(m_hrc); - } - - SetThreadpoolTimer(m_timer, NULL, 0, 0); - WaitForThreadpoolTimerCallbacks(m_timer, TRUE); - CloseThreadpoolTimer(m_timer); - m_func_invalidate.Free(); - - } - - void CGLControl::MakeCurrent() - { - wglMakeCurrent(m_hdc, m_hrc); - glBindFramebuffer(GL_FRAMEBUFFER, 0); - } - - void CGLControl::SetFramerate(float fps) - { - m_interval = (unsigned)(1000.0f / fps); - m_time_scheduled = time_milli_sec(); - this->Invalidate(); - } - - void CGLControl::Pause() - { - m_paused = true; - } - - void CGLControl::Resume() - { - m_paused = false; - m_time_scheduled = time_milli_sec(); - this->Invalidate(); - } - - void CGLControl::OnPaint(PaintEventArgs^ e) - { - if (m_hdc != nullptr) - { - this->MakeCurrent(); - Control::OnPaint(e); - SwapBuffers(m_hdc); - } - - if (!m_paused && m_interval > 0) - { - unsigned interval = m_interval; - uint64_t t = time_milli_sec(); - int delta = (int)(int64_t)(t - m_time_scheduled); - if (delta > interval) interval = 0; - else if (delta > 0) interval -= delta; - m_time_scheduled = t + interval; - - if (interval > 0) - { - ULARGE_INTEGER due; - due.QuadPart = (ULONGLONG)(-((int64_t)interval * 10000LL)); - ::FILETIME ft; - ft.dwHighDateTime = due.HighPart; - ft.dwLowDateTime = due.LowPart; - SetThreadpoolTimer(m_timer, &ft, 0, 0); - } - else - { - this->Invalidate(); - } - } - } - - bool CGLControl::ProcessCmdKey(Message% msg, Keys keyData) - { - static std::unordered_set s_set = - { - 8, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, - }; - - unsigned code = (unsigned)(keyData); - if (s_set.find(code) != s_set.end()) - { - ControlKey(code); - return true; - } - return Control::ProcessCmdKey(msg, keyData); - } - - static std::string g_HandleUserMessage(void* pplayer, const char* cname, const char* cmsg) - { - GCHandle handle_player = GCHandle::FromIntPtr((IntPtr)pplayer); - CGamePlayer^ player = (CGamePlayer^)handle_player.Target; - - String^ name = gcnew String(cname, 0, strlen(cname), Encoding::UTF8); - String^ msg = gcnew String(cmsg, 0, strlen(cmsg), Encoding::UTF8); - String^ ret = player->UserMessage(name, msg); - - int len_ret = Encoding::UTF8->GetByteCount(ret); - array^ bytes_ret = gcnew array(len_ret + 1); - Encoding::UTF8->GetBytes(ret, 0, ret->Length, bytes_ret, 0); - bytes_ret[len_ret] = 0; - const char* cret = (const char*)(void*)(Marshal::UnsafeAddrOfPinnedArrayElement(bytes_ret, 0)); - - return cret; - } - - String^ CGamePlayer::SetCapture(String^ msg) - { - m_window->Capture = true; - return ""; - } - - String^ CGamePlayer::ReleaseCapture(String^ msg) - { - m_window->Capture = false; - return ""; - } - - CGamePlayer::CGamePlayer(String^ exec_path, Control^ window) - { - const char* cpath = (const char*)(void*)Marshal::StringToHGlobalAnsi(exec_path); - m_native = new GamePlayer(cpath, window->Width, window->Height); - - m_window = window; - - m_handle_this = GCHandle::Alloc(this, GCHandleType::Normal); - void* pplayer = (void*)GCHandle::ToIntPtr(m_handle_this); - m_native->SetUserMessageCallback(pplayer, g_HandleUserMessage); - - m_msg_dict = gcnew Dictionary(); - - AddUserMessageHandler("setPointerCapture", gcnew MessageCallback(this, &CGamePlayer::SetCapture)); - AddUserMessageHandler("releasePointerCapture", gcnew MessageCallback(this, &CGamePlayer::ReleaseCapture)); - } - - CGamePlayer::!CGamePlayer() - { - if (m_handle_this.IsAllocated) - { - m_handle_this.Free(); - } - delete m_native; - } - - void CGamePlayer::Draw(int width, int height) - { - m_native->Draw(width, height); - m_native->Idle(); - } - - void CGamePlayer::LoadScript(String^ script_path, String^ resource_root) - { - if (resource_root == nullptr) - { - resource_root = Path::GetDirectoryName(script_path); - script_path = Path::GetFileName(script_path); - } - const char* cscript_path = (const char*)(void*)Marshal::StringToHGlobalAnsi(script_path); - const char* cresource_root = (const char*)(void*)Marshal::StringToHGlobalAnsi(resource_root); - m_native->LoadScript(cresource_root, cscript_path); - } - - void CGamePlayer::UnloadScript() - { - m_native->UnloadScript(); - } - - void CGamePlayer::OnMouseDown(MouseEventArgs e) - { - m_native->OnMouseDown(e.button, e.clicks, e.delta, e.x, e.y); - } - - void CGamePlayer::OnMouseUp(MouseEventArgs e) - { - m_native->OnMouseUp(e.button, e.clicks, e.delta, e.x, e.y); - } - - void CGamePlayer::OnMouseMove(MouseEventArgs e) - { - m_native->OnMouseMove(e.button, e.clicks, e.delta, e.x, e.y); - } - - void CGamePlayer::OnMouseWheel(MouseEventArgs e) - { - m_native->OnMouseWheel(e.button, e.clicks, e.delta, e.x, e.y); - } - - void CGamePlayer::OnLongPress(int x, int y) - { - m_native->OnLongPress(x, y); - } - - void CGamePlayer::OnChar(int keyChar) - { - m_native->OnChar(keyChar); - } - - void CGamePlayer::OnControlKey(unsigned code) - { - m_native->OnControlKey(code); - } - - void CGamePlayer::AddUserMessageHandler(String^ name, MessageCallback^ callback) - { - m_msg_dict[name] = callback; - } - - String^ CGamePlayer::UserMessage(String^ name, String^ msg) - { - if (m_msg_dict->ContainsKey(name)) - { - return m_msg_dict[name](msg); - } - return ""; - } - - String^ CGamePlayer::SendMessageToUser(String^ name, String^ msg) - { - int len_name = Encoding::UTF8->GetByteCount(name); - array^ bytes_name = gcnew array(len_name + 1); - Encoding::UTF8->GetBytes(name, 0, name->Length, bytes_name, 0); - bytes_name[len_name] = 0; - const char* cname = (const char*)(void*)(Marshal::UnsafeAddrOfPinnedArrayElement(bytes_name, 0)); - - int len_msg = Encoding::UTF8->GetByteCount(msg); - array^ bytes_msg = gcnew array(len_msg + 1); - Encoding::UTF8->GetBytes(msg, 0, msg->Length, bytes_msg, 0); - bytes_msg[len_msg] = 0; - const char* cmsg = (const char*)(void*)(Marshal::UnsafeAddrOfPinnedArrayElement(bytes_msg, 0)); - - std::string cret = m_native->SendMessageToUser(cname, cmsg); - return gcnew String(cret.c_str(), 0, cret.length(), Encoding::UTF8); - } - - static void g_PrintStd(void* pplayer, const char* cstr) - { - GCHandle handle_player = GCHandle::FromIntPtr((IntPtr)pplayer); - CGamePlayer^ player = (CGamePlayer^)handle_player.Target; - String^ str = gcnew String(cstr, 0, strlen(cstr), Encoding::UTF8); - player->PrintStd(str); - } - - static void g_PrintErr(void* pplayer, const char* cstr) - { - GCHandle handle_player = GCHandle::FromIntPtr((IntPtr)pplayer); - CGamePlayer^ player = (CGamePlayer^)handle_player.Target; - String^ str = gcnew String(cstr, 0, strlen(cstr), Encoding::UTF8); - player->PrintErr(str); - } - - void CGamePlayer::SetPrintCallbacks(PrintCallback^ print_callback, PrintCallback^ error_callback) - { - void* pplayer = (void*)GCHandle::ToIntPtr(m_handle_this); - - m_print_callback = print_callback; - m_error_callback = error_callback; - - m_native->SetPrintCallbacks(pplayer, g_PrintStd, g_PrintErr); - } - - void CGamePlayer::PrintStd(String^ str) - { - m_print_callback(str); - } - - void CGamePlayer::PrintErr(String^ str) - { - m_error_callback(str); - } - -} diff --git a/Three.V8.CLR/CLRBinding.h b/Three.V8.CLR/CLRBinding.h deleted file mode 100644 index 6d102506..00000000 --- a/Three.V8.CLR/CLRBinding.h +++ /dev/null @@ -1,142 +0,0 @@ -#pragma once - -#pragma unmanaged -#include -#include -#include "binding.h" -#include "GamePlayer.h" -#pragma managed - -using namespace System; -using namespace System::Text; -using namespace System::Windows::Forms; -using namespace System::Runtime::InteropServices; -using namespace System::Collections::Generic; - -namespace CLRBinding -{ - public delegate void ControlEvent(unsigned code); - - public ref class CGLControl : public Control - { - public: - CGLControl(); - !CGLControl(); - ~CGLControl() - { - if (!m_finalized) - { - this->!CGLControl(); - m_finalized = true; - } - } - - void MakeCurrent(); - void SetFramerate(float fps); - void Pause(); - void Resume(); - - ControlEvent^ pControlKey = nullptr; - - event ControlEvent^ ControlKey - { - void add(ControlEvent^ p) - { - pControlKey = static_cast (Delegate::Combine(pControlKey, p)); - } - - void remove(ControlEvent^ p) - { - pControlKey = static_cast (Delegate::Remove(pControlKey, p)); - } - - void raise(unsigned code) - { - if (pControlKey != nullptr) - pControlKey->Invoke(code); - } - } - - - protected: - virtual void OnPaint(PaintEventArgs^ e) override; - virtual bool ProcessCmdKey(Message% msg, Keys keyData) override; - - private: - HDC m_hdc = nullptr; - HGLRC m_hrc = nullptr; - unsigned m_interval = 0; - bool m_paused = false; - uint64_t m_time_scheduled; - PTP_TIMER m_timer = nullptr; - GCHandle m_func_invalidate; - bool m_finalized = false; - }; - - - public value struct MouseEventArgs - { - int button; - int clicks; - int delta; - int x; - int y; - }; - - public delegate void PrintCallback(String^ str); - public delegate String^ MessageCallback(String^ msg); - - public ref class CGamePlayer - { - public: - CGamePlayer(String^ exec_path, Control^ window); - !CGamePlayer(); - ~CGamePlayer() - { - if (!m_finalized) - { - this->!CGamePlayer(); - m_finalized = true; - } - } - - void Draw(int width, int height); - void LoadScript(String^ script_path, String^ resource_root); - void UnloadScript(); - - void OnMouseDown(MouseEventArgs e); - void OnMouseUp(MouseEventArgs e); - void OnMouseMove(MouseEventArgs e); - void OnMouseWheel(MouseEventArgs e); - void OnLongPress(int x, int y); - - void OnChar(int keyChar); - void OnControlKey(unsigned code); - - void AddUserMessageHandler(String^ name, MessageCallback^ callback); - - String^ UserMessage(String^ name, String^ msg); - String^ SendMessageToUser(String^ name, String^ msg); - - void SetPrintCallbacks(PrintCallback^ print_callback, PrintCallback^ error_callback); - void PrintStd(String^ str); - void PrintErr(String^ str); - - private: - Control^ m_window = nullptr; - GamePlayer* m_native = nullptr; - bool m_finalized = false; - GCHandle m_handle_this; - - Dictionary^ m_msg_dict; - - String^ SetCapture(String^ msg); - String^ ReleaseCapture(String^ msg); - - PrintCallback^ m_print_callback = nullptr; - PrintCallback^ m_error_callback = nullptr; - }; - - -} - diff --git a/Three.V8.CLR/Three.V8.CLR.vcxproj b/Three.V8.CLR/Three.V8.CLR.vcxproj deleted file mode 100644 index 7c977baa..00000000 --- a/Three.V8.CLR/Three.V8.CLR.vcxproj +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A} - v4.7.2 - ManagedCProj - ThreeV8CLR - 10.0 - - - - Application - true - v143 - true - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - true - Unicode - - - DynamicLibrary - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - - - Level3 - NDEBUG; GLEW_STATIC=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - ../ThreeEngine;../thirdparty/glew/include;../thirdparty/glm/glm;../Three.V8;../ThreeMM;%(AdditionalIncludeDirectories) - stdcpp17 - - - glew.lib;draco.lib;crypt32.lib;portaudio.lib;libwebp.lib;libwebpdecoder.lib;libwebpdemux.lib;libwebpmux.lib;%(AdditionalDependencies) - ../thirdparty/glew/lib;../thirdparty/draco/lib;../thirdparty/portaudio/lib;../thirdparty/webp/lib;%(AdditionalLibraryDirectories) - - - - - Level3 - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - - - - - - Level3 - _DEBUG;%(PreprocessorDefinitions) - - - - - - - - Level3 - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - - - - - - {ccbe3960-dad2-49af-952f-a8a86d75f190} - - - {030c6452-10bf-48a4-b80f-0d4a996b83ae} - - - {7f3bb2ff-13e9-45a0-b8e3-f663fc651efd} - - - - - - - - - - - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - \ No newline at end of file diff --git a/Three.V8.CLR/Three.V8.CLR.vcxproj.filters b/Three.V8.CLR/Three.V8.CLR.vcxproj.filters deleted file mode 100644 index b5fdfce7..00000000 --- a/Three.V8.CLR/Three.V8.CLR.vcxproj.filters +++ /dev/null @@ -1,30 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Header Files - - - - - Source Files - - - - - - \ No newline at end of file diff --git a/Three.V8.CLR/Three.V8.CLR.vcxproj.user b/Three.V8.CLR/Three.V8.CLR.vcxproj.user deleted file mode 100644 index 88a55094..00000000 --- a/Three.V8.CLR/Three.V8.CLR.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/Three.V8.CLR/packages.config b/Three.V8.CLR/packages.config deleted file mode 100644 index 38682059..00000000 --- a/Three.V8.CLR/packages.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/Three.V8.sln b/Three.V8.sln index 3269837b..61464cdd 100644 --- a/Three.V8.sln +++ b/Three.V8.sln @@ -7,18 +7,12 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ThreeEngine", "ThreeEngine\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Three.V8", "Three.V8\Three.V8.vcxproj", "{CCBE3960-DAD2-49AF-952F-A8A86D75F190}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Three.V8.CLR", "Three.V8.CLR\Three.V8.CLR.vcxproj", "{8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Test.Cpp", "Test.Cpp\Test.Cpp.vcxproj", "{3F00C726-809A-4269-9281-33B6AACE99F9}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Test.V8", "Test.V8\Test.V8.vcxproj", "{67D5CD91-A728-4719-8E9C-8610CF661CEB}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GamePlayer", "GamePlayer\GamePlayer.csproj", "{3765E14C-74FC-463A-A843-D5B67FE8A7C2}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ThreeMM", "ThreeMM\ThreeMM.vcxproj", "{7F3BB2FF-13E9-45A0-B8E3-F663FC651EFD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameDev", "GameDev\GameDev.csproj", "{50E53E1E-BC53-442C-AA8E-E1149F23D6E1}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lightmapper", "Lightmapper\Lightmapper.vcxproj", "{CD28457C-63C3-43E9-8C91-A015D91B7B49}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LightmapCompressor", "LightmapCompressor\LightmapCompressor.vcxproj", "{BE12DD92-F55E-4138-8755-A62107C35182}" @@ -53,16 +47,6 @@ Global {CCBE3960-DAD2-49AF-952F-A8A86D75F190}.Release|x64.Build.0 = Release|x64 {CCBE3960-DAD2-49AF-952F-A8A86D75F190}.Release|x86.ActiveCfg = Release|Win32 {CCBE3960-DAD2-49AF-952F-A8A86D75F190}.Release|x86.Build.0 = Release|Win32 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Debug|Any CPU.ActiveCfg = Debug|Win32 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Debug|x64.ActiveCfg = Debug|x64 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Debug|x64.Build.0 = Debug|x64 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Debug|x86.ActiveCfg = Debug|Win32 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Debug|x86.Build.0 = Debug|Win32 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Release|Any CPU.ActiveCfg = Release|Win32 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Release|x64.ActiveCfg = Release|x64 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Release|x64.Build.0 = Release|x64 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Release|x86.ActiveCfg = Release|Win32 - {8ACCB6BD-C7B1-4A80-91D5-53CF222B716A}.Release|x86.Build.0 = Release|Win32 {3F00C726-809A-4269-9281-33B6AACE99F9}.Debug|Any CPU.ActiveCfg = Debug|Win32 {3F00C726-809A-4269-9281-33B6AACE99F9}.Debug|x64.ActiveCfg = Debug|x64 {3F00C726-809A-4269-9281-33B6AACE99F9}.Debug|x64.Build.0 = Debug|x64 @@ -83,18 +67,6 @@ Global {67D5CD91-A728-4719-8E9C-8610CF661CEB}.Release|x64.Build.0 = Release|x64 {67D5CD91-A728-4719-8E9C-8610CF661CEB}.Release|x86.ActiveCfg = Release|Win32 {67D5CD91-A728-4719-8E9C-8610CF661CEB}.Release|x86.Build.0 = Release|Win32 - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Debug|x64.ActiveCfg = Debug|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Debug|x64.Build.0 = Debug|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Debug|x86.ActiveCfg = Debug|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Debug|x86.Build.0 = Debug|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Release|Any CPU.Build.0 = Release|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Release|x64.ActiveCfg = Release|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Release|x64.Build.0 = Release|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Release|x86.ActiveCfg = Release|Any CPU - {3765E14C-74FC-463A-A843-D5B67FE8A7C2}.Release|x86.Build.0 = Release|Any CPU {7F3BB2FF-13E9-45A0-B8E3-F663FC651EFD}.Debug|Any CPU.ActiveCfg = Debug|x64 {7F3BB2FF-13E9-45A0-B8E3-F663FC651EFD}.Debug|Any CPU.Build.0 = Debug|x64 {7F3BB2FF-13E9-45A0-B8E3-F663FC651EFD}.Debug|x64.ActiveCfg = Debug|x64 @@ -107,18 +79,6 @@ Global {7F3BB2FF-13E9-45A0-B8E3-F663FC651EFD}.Release|x64.Build.0 = Release|x64 {7F3BB2FF-13E9-45A0-B8E3-F663FC651EFD}.Release|x86.ActiveCfg = Release|Win32 {7F3BB2FF-13E9-45A0-B8E3-F663FC651EFD}.Release|x86.Build.0 = Release|Win32 - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Debug|x64.ActiveCfg = Debug|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Debug|x64.Build.0 = Debug|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Debug|x86.ActiveCfg = Debug|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Debug|x86.Build.0 = Debug|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Release|Any CPU.Build.0 = Release|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Release|x64.ActiveCfg = Release|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Release|x64.Build.0 = Release|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Release|x86.ActiveCfg = Release|Any CPU - {50E53E1E-BC53-442C-AA8E-E1149F23D6E1}.Release|x86.Build.0 = Release|Any CPU {CD28457C-63C3-43E9-8C91-A015D91B7B49}.Debug|Any CPU.ActiveCfg = Debug|x64 {CD28457C-63C3-43E9-8C91-A015D91B7B49}.Debug|Any CPU.Build.0 = Debug|x64 {CD28457C-63C3-43E9-8C91-A015D91B7B49}.Debug|x64.ActiveCfg = Debug|x64