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
use color::{Rgba, color_space::LinearRgb};
use blender;
use crate::utils::{self, ObjectId, LibraryId};
use angle::{Deg, Rad, Angle};
use crate::utils::Property;

#[repr(u16)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Clone,Debug,Copy,PartialEq,Eq)]
pub enum ShadowMapType{
    No = 3,
    Simple = 0,
    Variance = 1,
    Exponential = 2,
}

#[repr(u16)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Clone,Debug,Copy,PartialEq,Eq)]
pub enum LightType {
    /* type */
    Point	    = 0,
    Directional	= 1,
    Spot		= 2,
    Hemi		= 3,
    Area		= 4,
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Clone,Debug)]
pub struct Lamp{
    pub name: ObjectId,
    pub ty: LightType,
    pub transformations: utils::Transformations,
    pub color: Rgba<f32, LinearRgb>,
    pub strength: f32,
    pub att_constant: f32,
    pub att_linear: f32,
    pub att_quadratic: f32,
    pub size: f32,
    pub angle: Deg<f32>,
    pub spot_blend: f32,
    pub shadowmap_type: ShadowMapType,
    pub shadow_frustum_size: Option<f32>,
    pub shadow_bufsize: u16,
    pub shadow_near_clip: f32,
    pub shadow_far_clip: Option<f32>,
    pub shadow_bias: f32,
    pub shadow_contact: bool,
    pub custom_properties: Vec<Property>,
    pub visible: bool,
}

bitflags! {
    struct LampMode: u32 {
        /* mode */
        const LA_SHAD_BUF	= (1 << 0);
        const LA_HALO		= (1 << 1);
        const LA_LAYER		= (1 << 2);
        const LA_QUAD		= (1 << 3) /* no longer used */;
        const LA_NEG		= (1 << 4);
        const LA_ONLYSHADOW	= (1 << 5);
        const LA_SPHERE		= (1 << 6);
        const LA_SQUARE		= (1 << 7);
        const LA_TEXTURE	= (1 << 8);
        const LA_OSATEX		= (1 << 9);
        const LA_NO_DIFF	= (1 << 11);
        const LA_NO_SPEC	= (1 << 12);
        const LA_SHAD_RAY	= (1 << 13);
        const LA_LAYER_SHADOW	= (1 << 15);
        const LA_SHAD_TEX		= (1 << 16);
        const LA_SHOW_CONE		= (1 << 17);
        const LA_SHOW_SHADOW_BOX =  (1 << 18);
        const LA_SHAD_CONTACT = (1 << 19);
    }
}

pub fn parse(obj: &blender::Object, library_id: LibraryId, visible: bool, scene_eevee: Option<&blender::Object>) -> Option<Lamp>{
    if let Ok(lightdata) = obj.get_object("data"){
        let lighttype = *lightdata.get("type").unwrap();
        let transformations = utils::transformations(&obj);
        let name = obj.name().unwrap();

        match lighttype{
            LightType::Point => { // Point Light
                Some(parse_point_light_nodes(&lightdata, library_id, name, transformations, visible, scene_eevee))
            }
            LightType::Directional => { // Directional Light
                Some(parse_directional_light_nodes(&lightdata, library_id, name, transformations, visible, scene_eevee))
            }
            LightType::Spot => { // Spot Light
                Some(parse_spot_light_nodes(&lightdata, library_id, name, transformations, visible, scene_eevee))
            }
            _ => {
                None
            }
        }
    }else{
        None
    }
}

fn shadowmap_type(lightdata: &blender::Object, eevee: Option<&blender::Object>) -> ShadowMapType{
    let mode: LampMode = *lightdata.get("mode").unwrap();
    if mode.contains(LampMode::LA_SHAD_BUF)
        || mode.contains(LampMode::LA_SHAD_RAY)
        || mode.contains(LampMode::LA_SHAD_TEX)
    {
        if let Some(eevee) = eevee{
            match *eevee.get::<i32>("shadow_method").unwrap(){
                1 => ShadowMapType::Exponential,
                2 => ShadowMapType::Variance,
                3 => ShadowMapType::Simple,
                _ => unreachable!("Unkown shadow map type")
            }
        }else{
            *lightdata.get("shadowmap_type").unwrap()
        }
    }else{
        ShadowMapType::No
    }
}


fn parse_point_light_nodes(
    lightdata: &blender::Object,
    library_id: LibraryId,
    name: &str,
    transformations: utils::Transformations,
    visible: bool,
    eevee: Option<&blender::Object>) -> Lamp
{
    let mut color = rgba_linear!(1.,1.,1.,1.);
    let mut strength = 1.;
    let mut att_constant = 1.;
    let mut att_linear = 0.;
    let mut att_quadratic = 0.1 / strength;
    let custom_properties = utils::custom_properties(lightdata);
    if let Ok(nodetree) = lightdata.get_object("nodetree"){
        if let Some(emission) = nodetree.get_list("nodes").unwrap().iter().find(|node| node.name().unwrap() == "Emission"){
            if let Some(strength_obj) = emission.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Strength"){
                if let Ok(link) = strength_obj.get_object("link"){
                    if let Ok(from) = link.get_object("fromnode"){
                        let name = from.name().unwrap();
                        if name.starts_with("Light Falloff"){
                            let out = link.get_object("fromsock").unwrap();
                            let strength_obj = from.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Strength").unwrap();
                            strength = *strength_obj.get_object("default_value").unwrap().cast_to("bNodeSocketValueFloat").unwrap().get::<f32>("value").unwrap();
                            if out.name().unwrap() == "Quadratic"{
                                att_constant = 1.0;
                                att_linear = 0.0;
                                att_quadratic = 0.1 / strength;
                            }else if out.name().unwrap() == "Linear"{
                                att_constant = 1.0;
                                att_linear = 0.1 / strength;
                                att_quadratic = 0.0;
                            }else if out.name().unwrap() == "Constant"{
                                att_constant = 0.1 / strength;
                                att_linear = 0.0;
                                att_quadratic = 0.0;
                            }
                        }
                    }
                }else{
                    let strength_obj = strength_obj.get_object("default_value").unwrap();
                    let strength_socket = strength_obj.cast_to("bNodeSocketValueFloat").unwrap();
                    strength = *strength_socket.get::<f32>("value").unwrap();
                    att_constant = 1.0;
                    att_linear = 0.0;
                    att_quadratic = 0.1 / strength;
                }
            }
            if let Some(color_obj) = emission.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Color"){
                if let Ok(link) = color_obj.get_object("link"){
                    if let Ok(from) = link.get_object("fromnode"){
                        let name = from.get_str("idname").unwrap();
                        if name == "ShaderNodeBlackbody"{
                            let temperature = from.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Temperature").unwrap();
                            let temperature = *temperature.get_object("default_value").unwrap().cast_to("bNodeSocketValueFloat").unwrap().get::<f32>("value").unwrap();
                            color = rgba_linear!(utils::blackbody(temperature), 1.0);
                        }
                    }
                }else{
                    let color_obj = color_obj.get_object("default_value").unwrap();
                    let color_socket = color_obj.cast_to("bNodeSocketValueRGBA").unwrap();
                    let color_arr = color_socket.get_slice::<f32>("value").unwrap();
                    color = rgba_linear!(color_arr[0], color_arr[1], color_arr[2], color_arr[3]);
                }
            }
        }
    }else{
        let r = *lightdata.get::<f32>("r").unwrap();
        let g = *lightdata.get("g").unwrap();
        let b = *lightdata.get("b").unwrap();
        let a = *lightdata.get("k").unwrap();
        if let Ok(energy) = lightdata.get("energy"){
            strength = *energy;
        }
        color = rgba_linear!(r, g, b, a);
    }

    Lamp{
        name: ObjectId::new(library_id, name),
        ty: LightType::Point,
        transformations,
        color,
        strength,
        att_constant,
        att_linear,
        att_quadratic,
        size: *lightdata.get("area_size").unwrap(),
        angle: Deg(0.),
        spot_blend: 0.,
        shadowmap_type: shadowmap_type(lightdata, eevee),
        shadow_frustum_size: lightdata.get::<f32>("shadow_frustum_size").map(|size| *size * 2.).ok(),
        shadow_bufsize: eevee
            .map(|eevee| *eevee.get::<i32>("shadow_cascade_size").unwrap() as u16)
            .unwrap_or_else(|| *lightdata.get("bufsize").unwrap()),
        shadow_near_clip: *lightdata.get("clipsta").unwrap(),
        shadow_far_clip: None,
        shadow_bias: *lightdata.get("bias").unwrap(),
        shadow_contact: lightdata.get::<LampMode>("mode").unwrap().contains(LampMode::LA_SHAD_CONTACT),
        custom_properties,
        visible,
    }
}



fn parse_spot_light_nodes(
    lightdata: &blender::Object,
    library_id: LibraryId,
    name: &str,
    transformations: utils::Transformations,
    visible: bool,
    eevee: Option<&blender::Object>) -> Lamp
{
    let mut color = rgba_linear!(1.,1.,1.,1.);
    let mut strength = 1.;
    let mut att_constant = 1.;
    let mut att_linear = 0.;
    let mut att_quadratic = 0.1 / strength;
    let custom_properties = utils::custom_properties(lightdata);
    if let Ok(nodetree) = lightdata.get_object("nodetree"){
        if let Some(emission) = nodetree.get_list("nodes").unwrap().iter().find(|node| node.name().unwrap() == "Emission"){
            if let Some(strength_obj) = emission.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Strength"){
                if let Ok(link) = strength_obj.get_object("link"){
                    if let Ok(from) = link.get_object("fromnode"){
                        let name = from.name().unwrap();
                        if name.starts_with("Light Falloff"){
                            let out = link.get_object("fromsock").unwrap();
                            let strength_obj = from.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Strength").unwrap();
                            strength = *strength_obj.get_object("default_value").unwrap().cast_to("bNodeSocketValueFloat").unwrap().get::<f32>("value").unwrap();
                            if out.name().unwrap() == "Quadratic"{
                                att_constant = 1.0;
                                att_linear = 0.0;
                                att_quadratic = 0.1 / strength;
                            }else if out.name().unwrap() == "Linear"{
                                att_constant = 1.0;
                                att_linear = 0.1 / strength;
                                att_quadratic = 0.0;
                            }else if out.name().unwrap() == "Constant"{
                                att_constant = 0.1 / strength;
                                att_linear = 0.0;
                                att_quadratic = 0.0;
                            }
                        }
                    }
                }else{
                    let strength_obj = strength_obj.get_object("default_value").unwrap();
                    let strength_socket = strength_obj.cast_to("bNodeSocketValueFloat").unwrap();
                    strength = *strength_socket.get::<f32>("value").unwrap();
                    att_constant = 1.0;
                    att_linear = 0.0;
                    att_quadratic = 0.1 / strength;
                }
            }
            if let Some(color_obj) = emission.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Color"){
                if let Ok(link) = color_obj.get_object("link"){
                    if let Ok(from) = link.get_object("fromnode"){
                        let name = from.get_str("idname").unwrap();
                        if name == "ShaderNodeBlackbody"{
                            let temperature = from.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Temperature").unwrap();
                            let temperature = *temperature.get_object("default_value").unwrap().cast_to("bNodeSocketValueFloat").unwrap().get::<f32>("value").unwrap();
                            color = rgba_linear!(utils::blackbody(temperature), 1.0);
                        }
                    }
                }else{
                    let color_obj = color_obj.get_object("default_value").unwrap();
                    let color_socket = color_obj.cast_to("bNodeSocketValueRGBA").unwrap();
                    let color_arr = color_socket.get_slice::<f32>("value").unwrap();
                    color = rgba_linear!(color_arr[0], color_arr[1], color_arr[2], color_arr[3]);
                }
            }
        }
    }else{
        let r = *lightdata.get::<f32>("r").unwrap();
        let g = *lightdata.get("g").unwrap();
        let b = *lightdata.get("b").unwrap();
        let a = *lightdata.get("k").unwrap();
        if let Ok(energy) = lightdata.get("energy"){
            strength = *energy;
        }
        color = rgba_linear!(r, g, b, a);
    }

    Lamp{
        name: ObjectId::new(library_id, name),
        ty: LightType::Spot,
        transformations,
        color,
        strength,
        att_constant,
        att_linear,
        att_quadratic,
        size: *lightdata.get("area_size").unwrap(),
        angle: Rad(*lightdata.get("spotsize").unwrap()).to_deg(),
        spot_blend: *lightdata.get("spotblend").unwrap(),
        shadowmap_type: shadowmap_type(lightdata, eevee),
        shadow_frustum_size: lightdata.get::<f32>("shadow_frustum_size").map(|size| *size * 2.).ok(),
        shadow_bufsize: eevee
            .map(|eevee| *eevee.get::<i32>("shadow_cascade_size").unwrap() as u16)
            .unwrap_or_else(|| *lightdata.get("bufsize").unwrap()),
        shadow_near_clip: *lightdata.get("clipsta").unwrap(),
        shadow_far_clip: None,
        shadow_bias: *lightdata.get("bias").unwrap(),
        shadow_contact: lightdata.get::<LampMode>("mode").unwrap().contains(LampMode::LA_SHAD_CONTACT),
        custom_properties,
        visible,
    }
}

fn parse_directional_light_nodes(
    lightdata: &blender::Object,
    library_id: LibraryId,
    name: &str,
    transformations: utils::Transformations,
    visible: bool,
    eevee: Option<&blender::Object>) -> Lamp
{
    let mut color = rgba_linear!(1.,1.,1.,1.);
    let mut strength = 1.;
    let att_constant = 1.;
    let att_linear = 0.;
    let att_quadratic = 0.1 / strength;
    let custom_properties = utils::custom_properties(lightdata);
    if let Ok(nodetree) = lightdata.get_object("nodetree"){
        if let Some(emission) = nodetree.get_list("nodes").unwrap().iter().find(|node| node.name().unwrap() == "Emission"){
            if let Some(strength_obj) = emission.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Strength"){
                let strength_obj = strength_obj.get_object("default_value").unwrap();
                let strength_socket = strength_obj.cast_to("bNodeSocketValueFloat").unwrap();
                strength = *strength_socket.get("value").unwrap();
            }
            if let Some(color_obj) = emission.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Color"){
                if let Ok(link) = color_obj.get_object("link"){
                    if let Ok(from) = link.get_object("fromnode"){
                        let name = from.get_str("idname").unwrap();
                        if name == "ShaderNodeBlackbody"{
                            let temperature = from.get_list("inputs").unwrap().iter().find(|input| input.name().unwrap() == "Temperature").unwrap();
                            let temperature = *temperature.get_object("default_value").unwrap().cast_to("bNodeSocketValueFloat").unwrap().get::<f32>("value").unwrap();
                            color = rgba_linear!(utils::blackbody(temperature), 1.0);
                        }else{
                            trace!("found color node with unkown name {}", name);
                        }
                    }
                }else{
                    let color_obj = color_obj.get_object("default_value").unwrap();
                    let color_socket = color_obj.cast_to("bNodeSocketValueRGBA").unwrap();
                    let color_arr = color_socket.get_slice::<f32>("value").unwrap();
                    color = rgba_linear!(color_arr[0], color_arr[1], color_arr[2], color_arr[3]);
                }
            }
        }
    }else{
        let r = *lightdata.get::<f32>("r").unwrap();
        let g = *lightdata.get("g").unwrap();
        let b = *lightdata.get("b").unwrap();
        let a = *lightdata.get("k").unwrap();
        color = rgba_linear!(r, g, b, a);
    }

    Lamp{
        name: ObjectId::new(library_id, name),
        ty: LightType::Directional,
        transformations,
        color,
        strength,
        att_constant,
        att_linear,
        att_quadratic,
        size: if let Ok(sun_angle) = lightdata.get::<f32>("sun_angle"){
            (sun_angle.min(Deg(179.9).to_rad().value())  / 2.).tan().max(0.01)
        }else{
             *lightdata.get("area_size").unwrap()
        },
        angle: Deg(0.),
        spot_blend: 0.,
        shadowmap_type: shadowmap_type(lightdata, eevee),
        shadow_frustum_size: lightdata.get::<f32>("shadow_frustum_size").map(|size| *size * 2.).ok(),
        shadow_bufsize: eevee
            .map(|eevee| *eevee.get::<i32>("shadow_cascade_size").unwrap() as u16)
            .unwrap_or_else(|| *lightdata.get("bufsize").unwrap()),
        shadow_near_clip: *lightdata.get("clipsta").unwrap(),
        shadow_far_clip: Some(*lightdata.get("clipend").unwrap()),
        shadow_bias: *lightdata.get("bias").unwrap(),
        shadow_contact: lightdata.get::<LampMode>("mode").unwrap().contains(LampMode::LA_SHAD_CONTACT),
        custom_properties,
        visible
    }
}