1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#![recursion_limit="256"]

extern crate proc_macro;
#[macro_use] extern crate quote;
extern crate proc_macro2;
#[macro_use] extern crate syn;

use proc_macro::TokenStream;
use proc_macro_crate::crate_name;
use std::io::Write;
use std::fmt;
use rinecs_derive_utils::system;
use quote::TokenStreamExt;

mod material;

fn _rustfmt<C: fmt::Display>(code: C) -> String{
    // rustfmt_core::format_code_block(code, rustfmt_core::Config::default()).unwrap()
    let code = format!("{}", code);
    let mut child = ::std::process::Command::new("rustfmt")
        .stdin(::std::process::Stdio::piped())
        .stdout(::std::process::Stdio::piped())
        .spawn()
        .expect("Failed to format source snippet");
    {
        let stdin = child.stdin.as_mut().expect("Failed to open stdin");
        stdin.write_all(code.as_bytes()).expect("Failed to write to stdin");
    }
    let out = child.wait_with_output().expect("Failed to format source snippet").stdout;
    String::from_utf8_lossy(&out).to_string()
}

#[proc_macro_derive(Material, attributes(material))]
pub fn material(input: TokenStream) -> TokenStream{
    let ast: syn::DeriveInput = syn::parse(input).unwrap();
    let vis = ast.vis;
    let ident = ast.ident;
    let generics = ast.generics;
    let data = ast.data;
    let attrs = ast.attrs.into_iter()
        .filter(|attr| attr.path.is_ident("material"))
        .collect::<Vec<_>>();
    let input = if let syn::Data::Struct(data_struct) = data {
        let fields = data_struct.fields;
        quote!(#vis struct #ident #generics #fields).into()
    }else{
        panic!("Material can only be derived for structs")
    };

    let material = syn::parse_macro_input!(input as material::Material);
    let module_name = crate_name("rin-material")
        .or(crate_name("rin").map(|rin| rin + "::material"))
        .unwrap_or("crate".to_owned());
    let module_name: syn::Path = syn::parse_str(&module_name).unwrap();
    // panic!("{}", _rustfmt(material.impl_material(&module_name)))
    material.impl_material(attrs, &module_name).into()
    // match syn::parse::<material::Material>(input) {
    //     Ok(material) => {
    //     }

    //     Err(err) => err.to_compile_error().into()
    // }


    // let ast: DeriveInput = syn::parse(input).unwrap();
    // let name = &ast.ident;
    // let generics = &ast.generics;
    // let struct_attrs = ast.attrs.iter().flat_map(|attr|{
    //     if let Ok(Meta::List(metalist)) = attr.parse_meta(){
    //         if metalist.path.is_ident("material") {
    //             metalist.nested.iter().map(|meta|{
    //                 match meta {
    //                     NestedMeta::Meta(Meta::NameValue(namevalue))
    //                         => (
    //                             namevalue.path.segments.first().unwrap().ident.clone(),
    //                             Some(namevalue.lit.clone())
    //                         ),

    //                     NestedMeta::Meta(Meta::Path(path))
    //                         => (path.segments.first().unwrap().ident.clone(), None),

    //                     _ => panic!("Wrong syntax for material attribute, expecting word or name value pair, got list"),
    //                 }
    //             }).collect()
    //         }else{
    //             vec![]
    //         }
    //     }else{
    //         vec![]
    //     }
    // }).collect::<Vec<_>>();

    // let default = struct_attrs
    //     .iter()
    //     .find(|(ident, lit)| {
    //         if *ident == Ident::new("default", Span::call_site()){
    //             if lit.is_some(){
    //                 panic!("default struct attr, didn't expect any argument")
    //             }else{
    //                 true
    //             }
    //         }else{
    //             false
    //         }
    //     })
    //     .is_some();

    // let module_name = crate_name("rin-material")
    //     .unwrap_or("crate".to_owned());
    // let module_name: syn::Path = syn::parse_str(&module_name).unwrap();

    // if let syn::Data::Struct(DataStruct { ref fields, .. }) = ast.data {
    //     let default_gen = if default {
    //         default::impl_default(name, generics, fields, &module_name)
    //     }else{
    //         quote!{}
    //     };

    //     let material_gen = material_trait::impl_material_trait(
    //         name,
    //         generics,
    //         fields,
    //         &module_name);

    //     let tokens: proc_macro2::TokenStream = default_gen.into_iter()
    //         .chain(material_gen)
    //         .collect();

    //     tokens.into()
    // }else{
    //     panic!("Material derive can only be used with structs")
    // }
}

#[proc_macro_attribute]
pub fn update_system(args: TokenStream, input: TokenStream) -> TokenStream{
    let args = parse_macro_input!(args as syn::AttributeArgs);
    let system_type = system::SystemType::Send;
    let system_impl = if let Ok(func) = syn::parse(input.clone()){
        let system_trait = quote!(::rin::scene::UpdateSystem);
        let trait_run_fn_name = quote!(update);

        system::impl_any_system_fn(
            &args,
            &func,
            system_type,
            system_trait,
            trait_run_fn_name,
            parse_quote!(),
            system::GenericsIn::Type,
            system::SystemResourcesTy::EntitiesResources
        )
    }else if let Ok(system_impl) = syn::parse(input){
        system::impl_any_system_impl(
            &args,
            system_impl,
            system_type,
            system::SystemResourcesTy::EntitiesResources
        )
    }else{
        panic!("update_system attribute can only be used with an fn or a partial impl of System")
    };

    TokenStream::from(system_impl)
}

#[proc_macro_attribute]
pub fn update_system_thread_local(args: TokenStream, input: TokenStream) -> TokenStream{
    let args = parse_macro_input!(args as syn::AttributeArgs);
    let system_type = system::SystemType::ThreadLocal;
    let system_impl = if let Ok(func) = syn::parse(input.clone()){
        let system_trait = quote!(::rin::scene::UpdateSystemThreadLocal);
        let trait_run_fn_name = quote!(update);

        system::impl_any_system_fn(
            &args,
            &func,
            system_type,
            system_trait,
            trait_run_fn_name,
            parse_quote!(),
            system::GenericsIn::Type,
            system::SystemResourcesTy::EntitiesResources,
        )
    }else if let Ok(system_impl) = syn::parse(input){
        system::impl_any_system_impl(
            &args,
            system_impl,
            system_type,
            system::SystemResourcesTy::EntitiesResources
        )
    }else{
        panic!("update_system_thread_local attribute can only be used with an fn or a partial impl of System")
    };

    TokenStream::from(system_impl)
}


enum RenderStage{
    RenderSurfaceOpaque,
    AfterPostprocessingOpaque,
    RenderSurfaceTranslucent,
    AfterPostprocessing,
    Window,
}

impl syn::parse::Parse for RenderStage {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<RenderStage> {
        let ident: syn::Ident = input.parse()?;
        let render_stage = match format!("{}", ident).as_str() {
            "RenderSurfaceOpaque" => RenderStage::RenderSurfaceOpaque,
            "AfterPostprocessingOpaque" => RenderStage::AfterPostprocessingOpaque,
            "RenderSurfaceTranslucent" => RenderStage::RenderSurfaceTranslucent,
            "AfterPostprocessing" => RenderStage::AfterPostprocessing,
            "Window" => RenderStage::Window,
            render_stage
                => return Err(syn::Error::new(input.span(), "Unrecognized render stage")),
        };
        Ok(render_stage)
    }
}

impl quote::ToTokens for RenderStage {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let str_tokens = match self {
            RenderStage::RenderSurfaceOpaque => "RenderSurfaceOpaque",
            RenderStage::AfterPostprocessingOpaque => "AfterPostprocessingOpaque",
            RenderStage::RenderSurfaceTranslucent => "RenderSurfaceTranslucent",
            RenderStage::AfterPostprocessing => "AfterPostprocessing",
            RenderStage::Window => "Window",
        };
        let ident: syn::Ident = syn::Ident::new(str_tokens, proc_macro2::Span::call_site());
        tokens.append(ident)
    }
}


#[proc_macro_attribute]
pub fn render_system(args: TokenStream, input: TokenStream) -> TokenStream{
    let args = parse_macro_input!(args as syn::AttributeArgs);
    let system_type = system::SystemType::ThreadLocal;
    let system_impl = if let Ok(mut func) = syn::parse::<syn::ItemFn>(input.clone()){
        let system_trait = quote!(::rin::scene::RenderSystem);
        let trait_run_fn_name = if func.sig.generics.params.is_empty() {
            quote!(render_to_screen)
        }else{
            quote!(render)
        };
        let extra_methods = func.attrs.iter().filter_map(|attr| {
            if attr.path.is_ident("render_stage") {
                match attr.parse_args::<RenderStage>() {
                    Ok(render_stage) => {
                        let render_stage: proc_macro2::TokenStream = parse_quote!{
                            fn render_stage() -> ::rin::scene::RenderStage {
                                ::rin::scene::RenderStage::#render_stage
                            }
                        };

                        Some(Ok(render_stage))
                    }
                    Err(err) => Some(Err(err)),
                }
            }else{
                None
            }
        }).chain(if func.sig.generics.params.is_empty() {
            Some(Ok(quote!{
                fn render<S: gl::RenderSurface>(
                    &mut self,
                    gl: &gl::Renderer<S>,
                    viewport: Rect<i32>,
                    entities: EntitiesThreadLocal,
                    resources: ResourcesThreadLocal){
                        unimplemented!("This render system can only be used to render directly to a window, please add generic surface parameter to the render to be able to use it on any render surface")
                    }
            }))
        }else{
            None
        })
        .collect::<syn::Result<proc_macro2::TokenStream>>();

        let attrs = func.attrs
            .into_iter()
            .filter(|attr| !attr.path.is_ident("render_stage"))
            .collect();
        func.attrs = attrs;

        let extra_methods = match extra_methods  {
            Ok(extra_methods) => extra_methods,
            Err(err) => return err.to_compile_error().into()
        };

        system::impl_any_system_fn(
            &args,
            &func,
            system_type,
            system_trait,
            trait_run_fn_name,
            extra_methods,
            system::GenericsIn::Fn,
            system::SystemResourcesTy::EntitiesResources
        )
    }else if let Ok(system_impl) = syn::parse(input){
        system::impl_any_system_impl(
            &args,
            system_impl,
            system_type,
            system::SystemResourcesTy::EntitiesResources
        )
    }else{
        panic!("renderer_system attribute can only be used with an fn or a partial impl of System")
    };

    TokenStream::from(system_impl)
}

#[cfg(feature="gl_shader_source")]
use proc_macro_faithful_display::faithful_display;
#[cfg(feature="gl_shader_source")]
use proc_macro_hack::proc_macro_hack;

#[cfg(feature="gl_shader_source")]
#[proc_macro_hack]
pub fn vertex_shader_source(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let source = format!("{}", faithful_display(&input));
    let gen = quote!{
        rin::gl::shader_source!(rin::gl::VERTEX_SHADER, #source)
    };
    gen.into()
}

#[cfg(feature="gl_shader_source")]
#[proc_macro_hack]
pub fn fragment_shader_source(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let source = format!("{}", faithful_display(&input));
    let gen = quote!{
        rin::gl::shader_source!(rin::gl::FRAGMENT_SHADER, #source)
    };
    gen.into()
}


// TODO: this kind of works but calling a proc macro from inside a proc macro fails with ambiguous call
// #[cfg(feature="gl")]
// #[proc_macro_hack]
// fn shader_material(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
//     let shader_material = syn::parse_macro_input!(input as ShaderMaterial);
//     let (shaders, uniforms): (Vec<_>, Vec<_>) = shader_material.entries.into_iter().map(|entry|{
//         match entry{
//             Entry::Shader(ty, shader) => (Some(shader.to_str(ty)), None),
//             Entry::Uniforms(uniforms) => (None, Some(uniforms))
//         }
//     }).unzip();
//     // let shaders = shader_material.shaders.into_iter().map(|(ty,s)| s.to_str(ty));
//     // let uniforms = shader_material.uniforms.map(|uniforms| quote!{
//     //     Some(::std::cell::RefCell::new(Box::new( #uniforms )))
//     // });
//     let uniforms = if let Some(uniforms) = uniforms.into_iter().filter_map(|u| u).next() {
//         quote!{
//             Some(::std::cell::RefCell::new(Box::new( #uniforms )))
//         }
//     }else{
//         quote!{
//             None
//         }
//     };

//     let shaders = shaders.into_iter().filter_map(|s| s);

//     let gen = quote!{
//         ::rin::scene::renderer::ShaderMaterial{
//             shaders: vec![
//                 #( #shaders ),*
//             ],
//             uniforms: #uniforms
//         }
//     };

//     gen.into()
// }

// #[cfg(feature="gl")]
// enum ShaderTy{
//     Vertex,
//     Fragment,
// }

// #[cfg(feature="gl")]
// impl ShaderTy{
//     fn to_gl(self) -> proc_macro2::TokenStream {
//         match self{
//             ShaderTy::Vertex =>   quote!( rin::gl::VERTEX_SHADER ),
//             ShaderTy::Fragment => quote!( rin::gl::FRAGMENT_SHADER ),
//         }
//     }
// }

// #[cfg(feature="gl")]
// struct Shader{
//     source: syn::Expr,
// }

// #[cfg(feature="gl")]
// impl syn::parse::Parse for Shader {
//     fn parse(input: syn::parse::ParseStream) -> syn::Result<Shader>{
//         let source = input.parse()?;

//         Ok(Shader{
//             source,
//         })
//     }
// }

// #[cfg(feature="gl")]
// impl Shader{
//     fn to_str(self, ty: ShaderTy) -> proc_macro2::TokenStream {
//         let source = self.source;
//         let ty = ty.to_gl();
//         quote!{
//             rin::gl::ty_shader_source!(#ty, #source)
//         }
//     }
// }

// #[cfg(feature="gl")]
// struct Uniforms{
//     closure: syn::Expr,
// }

// #[cfg(feature="gl")]
// impl syn::parse::Parse for Uniforms{
//     fn parse(input: syn::parse::ParseStream) -> syn::Result<Uniforms>{
//         let closure = input.parse()?;
//         Ok(Uniforms{
//             closure
//         })
//     }
// }

// #[cfg(feature="gl")]
// impl quote::ToTokens for Uniforms{
//     fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream){
//         self.closure.to_tokens(tokens)
//     }
// }

// #[cfg(feature="gl")]
// enum Entry{
//     Shader(ShaderTy, Shader),
//     Uniforms(Uniforms)
// }

// #[cfg(feature="gl")]
// impl syn::parse::Parse for Entry {
//     fn parse(input: syn::parse::ParseStream) -> syn::Result<Entry>{
//         let ident: syn::Ident = input.parse()?;
//         if ident == Ident::new("vertex_shader", Span::call_site()){
//             let _arrow: syn::Token![=>] = input.parse()?;
//             let shader = input.parse()?;
//             Ok(Entry::Shader(ShaderTy::Vertex, shader))
//         }else if ident == Ident::new("fragment_shader", Span::call_site()){
//             let _arrow: syn::Token![=>] = input.parse()?;
//             let shader = input.parse()?;
//             Ok(Entry::Shader(ShaderTy::Fragment, shader))
//         }else if ident == Ident::new("uniforms", Span::call_site()){
//             let _arrow: syn::Token![=>] = input.parse()?;
//             Ok(Entry::Uniforms(input.parse()?))
//         }else{
//             Err(syn::Error::new(
//                 Span::call_site(),
//                 &format!("Unrecognized keyword in shader material: {}", ident)))
//         }
//     }
// }

// #[cfg(feature="gl")]
// struct ShaderMaterial{
//     entries: syn::punctuated::Punctuated<Entry, syn::Token![,]>,
// }

// #[cfg(feature="gl")]
// impl syn::parse::Parse for ShaderMaterial{
//     fn parse(input: syn::parse::ParseStream) -> syn::Result<ShaderMaterial>{
//         Ok(ShaderMaterial{
//             entries: syn::punctuated::Punctuated::parse_terminated(input)?,
//         })
//     }
// }