Skip to content

Commit

Permalink
Add support for extensions and a version-less context
Browse files Browse the repository at this point in the history
  • Loading branch information
Diggsey committed Feb 5, 2018
1 parent ad61f95 commit 43294b0
Show file tree
Hide file tree
Showing 11 changed files with 241 additions and 14 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
members = [
"gl",
"gl_generator",
"webgl",
"webgl_generator",
"tests/test_add_registries",
"tests/test_gen_symbols",
Expand Down
2 changes: 1 addition & 1 deletion tests/test_webgl_stdweb/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn main() {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("test_webgl_stdweb.rs")).unwrap();

Registry::new(Api::WebGl2)
Registry::new(Api::WebGl2, Exts::ALL)
.write_bindings(StdwebGenerator, &mut file)
.unwrap();
}
2 changes: 1 addition & 1 deletion tests/test_webgl_stdweb/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(unused_parens)]
#![allow(unused_parens, non_camel_case_types)]

#[macro_use]
extern crate stdweb as _stdweb;
Expand Down
23 changes: 23 additions & 0 deletions webgl/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "webgl_stdweb"
version = "0.1.0"
authors = [
"Diggory Blake",
]
description = "WebGL bindings (stdweb)"
license = "Apache-2.0"
build = "build.rs"
documentation = "https://docs.rs/webgl_stdweb"
homepage = "https://github.com/brendanzab/gl-rs/webgl/"
repository = "https://github.com/brendanzab/gl-rs/"
readme = "README.md"
categories = ["api-bindings", "rendering::graphics-api"]
keywords = ["webgl", "stdweb"]

[build-dependencies]
webgl_generator = { version = "0.1.0", path = "../webgl_generator" }

[dependencies]
stdweb = { path = "../../stdweb" }
serde = "1.0.0"
serde_derive = "1.0.0"
3 changes: 3 additions & 0 deletions webgl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# webgl-stdweb

WebGL bindings using stdweb
29 changes: 29 additions & 0 deletions webgl/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate webgl_generator;

use webgl_generator::*;
use std::env;
use std::fs::File;
use std::path::*;

fn main() {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("bindings.rs")).unwrap();

Registry::new(Api::WebGl2, Exts::ALL)
.write_bindings(StdwebGenerator, &mut file)
.unwrap();
}
24 changes: 24 additions & 0 deletions webgl/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(unused_parens, non_camel_case_types)]
#![crate_name = "webgl_stdweb"]
#![crate_type = "lib"]

#[macro_use]
extern crate stdweb as _stdweb;
#[macro_use]
extern crate serde_derive as _serde_derive;

include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
4 changes: 4 additions & 0 deletions webgl_generator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,7 @@ path = "lib.rs"
khronos_api = { version = "2.0.0", path = "../khronos_api" }
webidl = { version = "0.4.1" }
heck = { version = "0.3.0" }
serde-xml-rs = "0.2.1"
serde_derive = "1.0"
serde = "1.0"
regex = "0.2.5"
2 changes: 2 additions & 0 deletions webgl_generator/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
//! include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs"));
//! ```
//!
#[macro_use]
extern crate serde_derive;

mod webgl_generators;
mod webgl_registry;
Expand Down
57 changes: 53 additions & 4 deletions webgl_generator/webgl_generators/stdweb_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ enum ArgWrapper {
Optional(Box<ArgWrapper>),
Sequence(Box<ArgWrapper>),
DoubleCast,
Once,
}

impl ArgWrapper {
Expand All @@ -67,6 +68,7 @@ impl ArgWrapper {
&ArgWrapper::Optional(ref inner) => format!("{}.map(|inner| {})", arg, inner.wrap("inner")),
&ArgWrapper::Sequence(ref inner) => format!("{}.iter().map(|inner| {}).collect::<Vec<_>>()", arg, inner.wrap("inner")),
&ArgWrapper::DoubleCast => format!("({} as f64)", arg),
&ArgWrapper::Once => format!("Once({})", arg),
}
}
}
Expand Down Expand Up @@ -139,6 +141,11 @@ fn process_arg_type_kind(name: &str, type_kind: &TypeKind, registry: &Registry,
let gp = gc.arg("T");
gc.constrain(format!("{}: JsSerializable", gp));
ProcessedArg::simple(gp)
},
&TypeKind::Callback(ref _args, ref _return_type) => {
let gp = gc.arg("F");
gc.constrain(format!("{}: FnOnce() + 'static", gp));
ProcessedArg { type_: gp, wrapper: ArgWrapper::Once, optional: false }
}
}
}
Expand Down Expand Up @@ -218,7 +225,8 @@ fn process_result_type_kind(name: &str, type_kind: &TypeKind, registry: &Registr
optional: inner.optional
}
},
&TypeKind::Any | &TypeKind::Object => ProcessedResult::simple("Value")
&TypeKind::Any | &TypeKind::Object => ProcessedResult::simple("Value"),
&TypeKind::Callback(ref _args, ref _return_type) => unimplemented!()
}
}

Expand All @@ -239,7 +247,7 @@ fn write_header<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W:
extern crate stdweb;
extern crate serde;
use self::stdweb::{{Reference, Value, UnsafeTypedArray}};
use self::stdweb::{{Reference, Value, UnsafeTypedArray, Once}};
use self::stdweb::private::{{
JsSerializable,
FromReferenceUnchecked,
Expand All @@ -266,6 +274,10 @@ pub trait AsTypedArray<'a, T> {{
unsafe fn as_typed_array(self) -> Self::Result;
}}
pub trait Extension: TryFrom<Value> {{
const NAME: &'static str;
}}
macro_rules! define_array {{
($elem:ty) => {{
impl<'a> AsTypedArray<'a, $elem> for &'a TypedArray<$elem> {{
Expand Down Expand Up @@ -303,6 +315,7 @@ impl super::Generator for StdwebGenerator {
write_enums(registry, dest)?;
write_dictionaries(registry, dest)?;
write_interfaces(registry, dest)?;
write_extensions(registry, dest)?;
Ok(())
}
}
Expand Down Expand Up @@ -420,6 +433,14 @@ fn write_interface<W>(name: &str, interface: &Interface, registry: &Registry, de
return Ok(());
}

let instance_check = if name == "GLContext" {
"return [WebGLRenderingContext, WebGL2RenderingContext].includes(Module.STDWEB.acquire_js_reference( $0 ).constructor) | 0;".into()
} else if interface.has_class {
format!("return (Module.STDWEB.acquire_js_reference( $0 ) instanceof {}) | 0;", name)
} else {
format!("return (Module.STDWEB.acquire_js_reference( $0 ).constructor.name == {:?}) | 0;", name)
};

write!(dest, r#"
#[derive(Debug, Clone)]
pub struct {name}(Reference);
Expand All @@ -435,7 +456,7 @@ impl FromReference for {name} {{
fn from_reference(reference: Reference) -> Option<Self> {{
if {{
__js_raw_asm!(
"return (Module.STDWEB.acquire_js_reference( $0 ) instanceof {name}) | 0;",
{instance_check:?},
reference.as_raw()
) == 1
}} {{
Expand Down Expand Up @@ -500,7 +521,7 @@ impl JsSerializable for {name} {{
__js_serializable_boilerplate!(() ({name}) ());
impl {name} {{
"#, name=name)?;
"#, name=name, instance_check=instance_check)?;

for (name, members) in interface.collect_members(registry, &VisitOptions::default()) {
for (index, member) in members.into_iter().enumerate() {
Expand Down Expand Up @@ -586,7 +607,20 @@ fn write_attribute<W>(name: &str, attribute: &Attribute, registry: &Registry, de
Ok(())
}

fn write_get_extension<W>(dest: &mut W) -> io::Result<()> where W: io::Write {
write!(dest, r#"
pub fn get_extension<E: Extension>(&self) -> Option<E> {{
(js! {{ return @{{self}}.getExtension({{E::NAME}}); }} ).try_into().ok()
}}"#)
}

fn write_operation<W>(name: &str, index: usize, operation: &Operation, registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write {
match name {
"getExtension" => return write_get_extension(dest),
_ => {}
}

let mut rust_name = unreserve(snake(name));
if index > 0 {
rust_name = format!("{}_{}", rust_name, index);
Expand Down Expand Up @@ -643,3 +677,18 @@ fn write_operation<W>(name: &str, index: usize, operation: &Operation, registry:
}
Ok(())
}

fn write_extensions<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write {
for name in &registry.extensions {
write_extension(name, registry, dest)?;
}
Ok(())
}

fn write_extension<W>(name: &str, _registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write {
writeln!(dest, r#"
impl Extension for {name} {{
const NAME: &'static str = "{name}";
}}"#,
name=name)
}
Loading

0 comments on commit 43294b0

Please sign in to comment.