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
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
use crate::resources::pipeline_cache::GraphicsPipelineRenderTargetMeta;
use crate::resources::resource_arc::{ResourceId, ResourceWithHash, WeakResourceArc};
use crate::resources::DescriptorSetLayout;
use crate::resources::ResourceArc;
use crate::ResourceDropSink;
use bitflags::_core::sync::atomic::AtomicU64;
use crossbeam_channel::{Receiver, Sender};
use fnv::{FnvHashMap, FnvHasher};
use rafx_api::extra::image::RafxImage;
use rafx_api::*;
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};

// Hash of a GPU resource
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ResourceHash(u64);

impl ResourceHash {
    pub fn from_key<KeyT: Hash>(key: &KeyT) -> ResourceHash {
        let mut hasher = FnvHasher::default();
        key.hash(&mut hasher);
        ResourceHash(hasher.finish())
    }
}

impl From<ResourceId> for ResourceHash {
    fn from(resource_id: ResourceId) -> Self {
        ResourceHash(resource_id.0)
    }
}

impl Into<ResourceId> for ResourceHash {
    fn into(self) -> ResourceId {
        ResourceId(self.0)
    }
}

//
// A lookup of resources. They reference count using Arcs internally and send a signal when they
// drop. This allows the resources to be collected and disposed of
//
pub struct ResourceLookupInner<KeyT, ResourceT>
where
    KeyT: Eq + Hash + Clone,
    ResourceT: Clone,
{
    resources: FnvHashMap<ResourceHash, WeakResourceArc<ResourceT>>,
    //TODO: Add support for "cancelling" dropping stuff. This would likely be a ring of hashmaps.
    // that gets cycled.
    drop_sink: ResourceDropSink<ResourceT>,
    drop_tx: Sender<ResourceWithHash<ResourceT>>,
    drop_rx: Receiver<ResourceWithHash<ResourceT>>,
    phantom_data: PhantomData<KeyT>,
    #[cfg(debug_assertions)]
    keys: FnvHashMap<ResourceHash, KeyT>,
    #[cfg(debug_assertions)]
    lock_call_count_previous_frame: u64,
    #[cfg(debug_assertions)]
    lock_call_count: u64,
    create_count_previous_frame: u64,
    create_count: u64,
}

//TODO: Don't love using a mutex here. If this becomes a performance bottleneck:
// - Try making locks more granular (something like dashmap)
// - Have a read-only hashmap that's checked first and then a read/write map that's checked if the
//   read-only fails. At a later sync point, copy new data from the read-write into the read. This
//   could occur during the extract phase. Or could potentially double-buffer the read-only map
//   and swap them.
pub struct ResourceLookup<KeyT, ResourceT>
where
    KeyT: Eq + Hash + Clone,
    ResourceT: Clone,
{
    inner: Mutex<ResourceLookupInner<KeyT, ResourceT>>,
}

impl<KeyT, ResourceT> ResourceLookup<KeyT, ResourceT>
where
    KeyT: Eq + Hash + Clone,
    ResourceT: Clone + std::fmt::Debug,
{
    pub fn new(max_frames_in_flight: u32) -> Self {
        let (drop_tx, drop_rx) = crossbeam_channel::unbounded();

        let inner = ResourceLookupInner {
            resources: Default::default(),
            drop_sink: ResourceDropSink::new(max_frames_in_flight),
            drop_tx,
            drop_rx,
            phantom_data: Default::default(),
            #[cfg(debug_assertions)]
            keys: Default::default(),
            #[cfg(debug_assertions)]
            lock_call_count_previous_frame: 0,
            #[cfg(debug_assertions)]
            lock_call_count: 0,
            create_count_previous_frame: 0,
            create_count: 0,
        };

        ResourceLookup {
            inner: Mutex::new(inner),
        }
    }

    fn do_get(
        inner: &mut ResourceLookupInner<KeyT, ResourceT>,
        hash: ResourceHash,
        _key: &KeyT,
    ) -> Option<ResourceArc<ResourceT>> {
        let resource = inner.resources.get(&hash);

        if let Some(resource) = resource {
            let upgrade = resource.upgrade();
            #[cfg(debug_assertions)]
            if upgrade.is_some() {
                debug_assert!(inner.keys.get(&hash).unwrap() == _key);
            }

            upgrade
        } else {
            None
        }
    }

    fn do_create<F>(
        inner: &mut ResourceLookupInner<KeyT, ResourceT>,
        hash: ResourceHash,
        _key: &KeyT,
        create_resource_fn: F,
    ) -> RafxResult<ResourceArc<ResourceT>>
    where
        F: FnOnce() -> RafxResult<ResourceT>,
    {
        // Process any pending drops. If we don't do this, it's possible that the pending drop could
        // wipe out the state we're about to set
        Self::handle_dropped_resources(inner);

        inner.create_count += 1;

        let resource = (create_resource_fn)()?;
        log::trace!(
            "insert resource {} {:?}",
            core::any::type_name::<ResourceT>(),
            resource
        );

        let arc = ResourceArc::new(resource, hash.into(), inner.drop_tx.clone());
        let downgraded = arc.downgrade();
        let old = inner.resources.insert(hash, downgraded);
        assert!(old.is_none());

        #[cfg(debug_assertions)]
        {
            inner.keys.insert(hash, _key.clone());
            assert!(old.is_none());
        }

        Ok(arc)
    }

    #[allow(dead_code)]
    pub fn get(
        &self,
        key: &KeyT,
    ) -> Option<ResourceArc<ResourceT>> {
        let hash = ResourceHash::from_key(key);
        let mut guard = self.inner.lock().unwrap();
        #[cfg(debug_assertions)]
        {
            guard.lock_call_count += 1;
        }

        Self::do_get(&mut *guard, hash, key)
    }

    pub fn create<F>(
        &self,
        key: &KeyT,
        create_resource_fn: F,
    ) -> RafxResult<ResourceArc<ResourceT>>
    where
        F: FnOnce() -> RafxResult<ResourceT>,
    {
        let hash = ResourceHash::from_key(key);
        let mut guard = self.inner.lock().unwrap();
        #[cfg(debug_assertions)]
        {
            guard.lock_call_count += 1;
        }

        Self::do_create(&mut *guard, hash, key, create_resource_fn)
    }

    pub fn get_or_create<F>(
        &self,
        key: &KeyT,
        create_resource_fn: F,
    ) -> RafxResult<ResourceArc<ResourceT>>
    where
        F: FnOnce() -> RafxResult<ResourceT>,
    {
        let hash = ResourceHash::from_key(key);

        let mut guard = self.inner.lock().unwrap();
        #[cfg(debug_assertions)]
        {
            guard.lock_call_count += 1;
        }

        if let Some(resource) = Self::do_get(&mut *guard, hash, key) {
            //println!("get {} {:?}", core::any::type_name::<ResourceT>(), hash);
            Ok(resource)
        } else {
            //println!("create {} {:?}", core::any::type_name::<ResourceT>(), hash);
            Self::do_create(&mut *guard, hash, key, create_resource_fn)
        }
    }

    fn handle_dropped_resources(inner: &mut ResourceLookupInner<KeyT, ResourceT>) {
        for dropped in inner.drop_rx.try_iter() {
            log::trace!(
                "dropping {} {:?}",
                core::any::type_name::<ResourceT>(),
                dropped.resource
            );
            inner.drop_sink.retire(dropped.resource);
            inner.resources.remove(&dropped.resource_hash.into());

            #[cfg(debug_assertions)]
            {
                inner.keys.remove(&dropped.resource_hash.into());
            }
        }
    }

    fn on_frame_complete(&self) -> RafxResult<()> {
        let mut guard = self.inner.lock().unwrap();
        #[cfg(debug_assertions)]
        {
            guard.lock_call_count_previous_frame = guard.lock_call_count + 1;
            guard.lock_call_count = 0;
        }

        guard.create_count_previous_frame = guard.create_count;
        guard.create_count = 0;

        Self::handle_dropped_resources(&mut guard);
        guard.drop_sink.on_frame_complete()?;
        Ok(())
    }

    fn metrics(&self) -> ResourceLookupMetric {
        let guard = self.inner.lock().unwrap();
        ResourceLookupMetric {
            count: guard.resources.len(),
            previous_frame_create_count: guard.create_count_previous_frame,
            #[cfg(debug_assertions)]
            previous_frame_lock_call_count: guard.lock_call_count_previous_frame,
        }
    }

    fn destroy(
        &self,
        device_context: &RafxDeviceContext,
    ) -> RafxResult<()> {
        let mut guard = self.inner.lock().unwrap();
        #[cfg(debug_assertions)]
        {
            guard.lock_call_count += 1;
        }

        Self::handle_dropped_resources(&mut guard);

        if !guard.resources.is_empty() {
            log::warn!(
                "{} resource count {} > 0, resources will leak",
                core::any::type_name::<ResourceT>(),
                guard.resources.len()
            );
        }

        guard.drop_sink.destroy(device_context)?;
        Ok(())
    }
}

//
// Keys for each resource type. (Some keys are simple and use types from crate::pipeline_description
// and some are a combination of the definitions and runtime state. (For example, combining a
// renderpass with the swapchain surface it would be applied to)
//

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FixedFunctionState {
    pub blend_state: RafxBlendState,
    pub depth_state: RafxDepthState,
    pub rasterizer_state: RafxRasterizerState,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ShaderModuleMeta {
    pub stage: RafxShaderStageFlags,
    pub entry_name: String,
    // Reference to shader is excluded
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ShaderModuleResourceDef {
    // Precalculate a hash so we can avoid hashing this blob of bytes at runtime
    pub shader_module_hash: ShaderModuleHash,
    pub code: Vec<u8>,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ShaderModuleHash(u64);
impl ShaderModuleHash {
    pub fn new(shader_module: &RafxShaderModuleDef) -> Self {
        let mut hasher = FnvHasher::default();
        shader_module.hash_definition(&mut hasher);
        let hash = hasher.finish();
        ShaderModuleHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ShaderHash(u64);
impl ShaderHash {
    pub fn new(
        stage_defs: &[RafxShaderStageDef],
        shader_module_hashes: &[ShaderModuleHash],
    ) -> Self {
        let mut hasher = FnvHasher::default();
        RafxShaderStageDef::hash_definition(&mut hasher, stage_defs, shader_module_hashes);
        let hash = hasher.finish();
        ShaderHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct SamplerHash(u64);
impl SamplerHash {
    pub fn new(sampler_def: &RafxSamplerDef) -> Self {
        let mut hasher = FnvHasher::default();
        sampler_def.hash_definition(&mut hasher);
        let hash = hasher.finish();
        SamplerHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct RootSignatureHash(u64);
impl RootSignatureHash {
    pub fn new(
        shader_hashes: &[ShaderHash],
        immutable_sampler_keys: &[RafxImmutableSamplerKey],
        immutable_sampler_hashes: &[Vec<SamplerHash>],
    ) -> Self {
        let mut hasher = FnvHasher::default();
        RafxRootSignatureDef::hash_definition(
            &mut hasher,
            shader_hashes,
            immutable_sampler_keys,
            immutable_sampler_hashes,
        );
        let hash = hasher.finish();
        RootSignatureHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct DescriptorSetLayoutHash(u64);
impl DescriptorSetLayoutHash {
    pub fn new(
        root_signature_hash: RootSignatureHash,
        set_index: u32,
        bindings: &DescriptorSetLayout,
    ) -> Self {
        let mut hasher = FnvHasher::default();
        root_signature_hash.hash(&mut hasher);
        set_index.hash(&mut hasher);
        bindings.hash(&mut hasher);
        let hash = hasher.finish();
        DescriptorSetLayoutHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct MaterialPassHash(u64);
impl MaterialPassHash {
    pub fn new(
        shader_hash: ShaderHash,
        root_signature_hash: RootSignatureHash,
        descriptor_set_layout_hashes: &[DescriptorSetLayoutHash],
        fixed_function_state: &FixedFunctionState,
        vertex_inputs: &[MaterialPassVertexInput],
    ) -> Self {
        let mut hasher = FnvHasher::default();
        shader_hash.hash(&mut hasher);
        root_signature_hash.hash(&mut hasher);
        descriptor_set_layout_hashes.hash(&mut hasher);
        fixed_function_state.hash(&mut hasher);
        for vertex_input in vertex_inputs {
            vertex_input.hash(&mut hasher);
        }
        let hash = hasher.finish();
        MaterialPassHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct GraphicsPipelineHash(u64);
impl GraphicsPipelineHash {
    pub fn new(
        material_pass_key: MaterialPassHash,
        render_target_meta: &GraphicsPipelineRenderTargetMeta,
        primitive_topology: RafxPrimitiveTopology,
        vertex_layout: &RafxVertexLayout,
    ) -> Self {
        let mut hasher = FnvHasher::default();
        material_pass_key.hash(&mut hasher);
        render_target_meta
            .render_target_meta_hash()
            .hash(&mut hasher);
        primitive_topology.hash(&mut hasher);
        vertex_layout.hash(&mut hasher);
        let hash = hasher.finish();
        GraphicsPipelineHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ComputePipelineHash(u64);
impl ComputePipelineHash {
    pub fn new(
        shader_hash: ShaderHash,
        root_signature_hash: RootSignatureHash,
        descriptor_set_layout_hashes: &[DescriptorSetLayoutHash],
    ) -> Self {
        let mut hasher = FnvHasher::default();
        shader_hash.hash(&mut hasher);
        root_signature_hash.hash(&mut hasher);
        descriptor_set_layout_hashes.hash(&mut hasher);
        let hash = hasher.finish();
        ComputePipelineHash(hash)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ShaderModuleKey {
    hash: ShaderModuleHash,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ShaderKey {
    hash: ShaderHash,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RootSignatureKey {
    // hash is based on shader code hash, stage, and entry point
    hash: RootSignatureHash,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct DescriptorSetLayoutKey {
    hash: DescriptorSetLayoutHash,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MaterialPassVertexInput {
    pub semantic: String,
    pub location: u32,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MaterialPassKey {
    hash: MaterialPassHash,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GraphicsPipelineKey {
    hash: GraphicsPipelineHash,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ComputePipelineKey {
    hash: ComputePipelineHash,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ImageKey {
    id: u64,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct BufferKey {
    id: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SamplerKey {
    hash: SamplerHash,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ImageViewKey {
    image_key: ImageKey,
    texture_bind_type: Option<RafxTextureBindType>,
}

#[derive(Debug)]
pub struct ResourceLookupMetric {
    pub count: usize,
    pub previous_frame_create_count: u64,
    #[cfg(debug_assertions)]
    pub previous_frame_lock_call_count: u64,
}

#[derive(Debug)]
pub struct ResourceMetrics {
    pub shader_module_metrics: ResourceLookupMetric,
    pub shader_metrics: ResourceLookupMetric,
    pub root_signature_metrics: ResourceLookupMetric,
    pub descriptor_set_layout_metrics: ResourceLookupMetric,
    pub material_pass_metrics: ResourceLookupMetric,
    pub graphics_pipeline_metrics: ResourceLookupMetric,
    pub compute_pipeline_metrics: ResourceLookupMetric,
    pub image_metrics: ResourceLookupMetric,
    pub image_view_metrics: ResourceLookupMetric,
    pub sampler_metrics: ResourceLookupMetric,
    pub buffer_metrics: ResourceLookupMetric,
}

#[derive(Debug, Clone)]
pub struct ShaderModuleResource {
    pub shader_module_key: ShaderModuleKey,
    pub shader_module_resource_def: Arc<ShaderModuleResourceDef>,
    pub shader_module: RafxShaderModule,
}

#[derive(Debug, Clone)]
pub struct ShaderResource {
    pub key: ShaderKey,
    pub shader_modules: Vec<ResourceArc<ShaderModuleResource>>,
    pub shader: RafxShader,
}

#[derive(Debug, Clone)]
pub struct RootSignatureResource {
    pub key: RootSignatureKey,
    pub shaders: Vec<ResourceArc<ShaderResource>>,
    pub immutable_samplers: Vec<ResourceArc<SamplerResource>>,
    pub root_signature: RafxRootSignature,
}

#[derive(Debug, Clone)]
pub struct DescriptorSetLayoutResource {
    // Just keep it in scope
    pub root_signature_arc: ResourceArc<RootSignatureResource>,
    pub root_signature: RafxRootSignature,
    pub set_index: u32,

    pub descriptor_set_layout_def: DescriptorSetLayout,
    pub key: DescriptorSetLayoutKey,
}

#[derive(Debug, Clone)]
pub struct MaterialPassResource {
    pub material_pass_key: MaterialPassKey,
    pub shader: ResourceArc<ShaderResource>,
    pub root_signature: ResourceArc<RootSignatureResource>,
    pub descriptor_set_layouts: Vec<ResourceArc<DescriptorSetLayoutResource>>,

    pub fixed_function_state: Arc<FixedFunctionState>,
    pub vertex_inputs: Arc<Vec<MaterialPassVertexInput>>,
}

#[derive(Debug, Clone)]
pub struct GraphicsPipelineResource {
    pub render_target_meta: GraphicsPipelineRenderTargetMeta,
    pub pipeline: Arc<RafxPipeline>,
    pub descriptor_set_layouts: Vec<ResourceArc<DescriptorSetLayoutResource>>,
}

#[derive(Debug, Clone)]
pub struct ComputePipelineResource {
    pub root_signature: ResourceArc<RootSignatureResource>,
    pub pipeline: Arc<RafxPipeline>,
    pub descriptor_set_layouts: Vec<ResourceArc<DescriptorSetLayoutResource>>,
}

#[derive(Debug, Clone)]
pub struct ImageResource {
    pub image: Arc<RafxImage>,
    // Dynamic resources have no key
    pub image_key: Option<ImageKey>,
}

#[derive(Debug, Clone)]
pub struct ImageViewResource {
    pub image: ResourceArc<ImageResource>,
    // Dynamic resources have no key
    pub image_view_key: Option<ImageViewKey>,
    pub texture_bind_type: Option<RafxTextureBindType>,
}

#[derive(Debug, Clone)]
pub struct SamplerResource {
    pub sampler: RafxSampler,
    pub sampler_key: SamplerKey,
}

#[derive(Debug, Clone)]
pub struct BufferResource {
    pub buffer: Arc<RafxBuffer>,
    // Dynamic resources have no key
    pub buffer_key: Option<BufferKey>,
}

//
// Handles raw lookup and destruction of GPU resources. Everything is reference counted. No safety
// is provided for dependencies/order of destruction. The general expectation is that anything
// dropped can safely be destroyed after a few frames have passed (based on max number of frames
// that can be submitted to the GPU)
//
//TODO: Some of the resources like buffers and images don't need to be "keyed" and could probably
// be kept in a slab. We *do* need a way to access and quickly remove elements though, and whatever
// key we use is sent through a Sender/Receiver pair to be dropped later.
pub struct ResourceLookupSetInner {
    device_context: RafxDeviceContext,

    shader_modules: ResourceLookup<ShaderModuleKey, ShaderModuleResource>,
    shaders: ResourceLookup<ShaderKey, ShaderResource>,
    root_signatures: ResourceLookup<RootSignatureKey, RootSignatureResource>,
    descriptor_set_layouts: ResourceLookup<DescriptorSetLayoutKey, DescriptorSetLayoutResource>,
    material_passes: ResourceLookup<MaterialPassKey, MaterialPassResource>,
    graphics_pipelines: ResourceLookup<GraphicsPipelineKey, GraphicsPipelineResource>,
    compute_pipelines: ResourceLookup<ComputePipelineKey, ComputePipelineResource>,
    images: ResourceLookup<ImageKey, ImageResource>,
    image_views: ResourceLookup<ImageViewKey, ImageViewResource>,
    samplers: ResourceLookup<SamplerKey, SamplerResource>,
    buffers: ResourceLookup<BufferKey, BufferResource>,

    // Used to generate keys for images/buffers
    next_image_id: AtomicU64,
    next_buffer_id: AtomicU64,
}

#[derive(Clone)]
pub struct ResourceLookupSet {
    inner: Arc<ResourceLookupSetInner>,
}

impl ResourceLookupSet {
    pub fn new(
        device_context: &RafxDeviceContext,
        max_frames_in_flight: u32,
    ) -> Self {
        let set = ResourceLookupSetInner {
            device_context: device_context.clone(),
            shader_modules: ResourceLookup::new(max_frames_in_flight),
            shaders: ResourceLookup::new(max_frames_in_flight),
            root_signatures: ResourceLookup::new(max_frames_in_flight),
            descriptor_set_layouts: ResourceLookup::new(max_frames_in_flight),
            material_passes: ResourceLookup::new(max_frames_in_flight),
            graphics_pipelines: ResourceLookup::new(max_frames_in_flight),
            compute_pipelines: ResourceLookup::new(max_frames_in_flight),
            images: ResourceLookup::new(max_frames_in_flight),
            image_views: ResourceLookup::new(max_frames_in_flight),
            samplers: ResourceLookup::new(max_frames_in_flight),
            buffers: ResourceLookup::new(max_frames_in_flight),
            next_image_id: AtomicU64::new(0),
            next_buffer_id: AtomicU64::new(0),
        };

        ResourceLookupSet {
            inner: Arc::new(set),
        }
    }

    #[profiling::function]
    pub fn on_frame_complete(&self) -> RafxResult<()> {
        self.inner.images.on_frame_complete()?;
        self.inner.image_views.on_frame_complete()?;
        self.inner.buffers.on_frame_complete()?;
        self.inner.shader_modules.on_frame_complete()?;
        self.inner.shaders.on_frame_complete()?;
        self.inner.samplers.on_frame_complete()?;
        self.inner.root_signatures.on_frame_complete()?;
        self.inner.descriptor_set_layouts.on_frame_complete()?;
        self.inner.material_passes.on_frame_complete()?;
        self.inner.graphics_pipelines.on_frame_complete()?;
        self.inner.compute_pipelines.on_frame_complete()?;
        Ok(())
    }

    pub fn destroy(&self) -> RafxResult<()> {
        //WARNING: These need to be in order of dependencies to avoid frame-delays on destroying
        // resources.
        self.inner
            .compute_pipelines
            .destroy(&self.inner.device_context)?;
        self.inner
            .graphics_pipelines
            .destroy(&self.inner.device_context)?;
        self.inner
            .material_passes
            .destroy(&self.inner.device_context)?;
        self.inner
            .descriptor_set_layouts
            .destroy(&self.inner.device_context)?;
        self.inner
            .root_signatures
            .destroy(&self.inner.device_context)?;
        self.inner.samplers.destroy(&self.inner.device_context)?;
        self.inner.shaders.destroy(&self.inner.device_context)?;
        self.inner
            .shader_modules
            .destroy(&self.inner.device_context)?;
        self.inner.buffers.destroy(&self.inner.device_context)?;
        self.inner.image_views.destroy(&self.inner.device_context)?;
        self.inner.images.destroy(&self.inner.device_context)?;
        Ok(())
    }

    pub fn metrics(&self) -> ResourceMetrics {
        ResourceMetrics {
            shader_module_metrics: self.inner.shader_modules.metrics(),
            shader_metrics: self.inner.shaders.metrics(),
            root_signature_metrics: self.inner.root_signatures.metrics(),
            descriptor_set_layout_metrics: self.inner.descriptor_set_layouts.metrics(),
            material_pass_metrics: self.inner.material_passes.metrics(),
            graphics_pipeline_metrics: self.inner.graphics_pipelines.metrics(),
            compute_pipeline_metrics: self.inner.compute_pipelines.metrics(),
            image_metrics: self.inner.images.metrics(),
            image_view_metrics: self.inner.image_views.metrics(),
            sampler_metrics: self.inner.samplers.metrics(),
            buffer_metrics: self.inner.buffers.metrics(),
        }
    }

    pub fn get_or_create_shader_module(
        &self,
        shader_module_resource_def: &Arc<ShaderModuleResourceDef>,
    ) -> RafxResult<ResourceArc<ShaderModuleResource>> {
        let shader_module_key = ShaderModuleKey {
            hash: shader_module_resource_def.shader_module_hash,
        };

        self.inner
            .shader_modules
            .get_or_create(&shader_module_key, || {
                log::trace!(
                    "Creating shader module\n[hash: {:?} bytes: {}]",
                    shader_module_key.hash,
                    shader_module_resource_def.code.len()
                );

                let shader_module = self
                    .inner
                    .device_context
                    .vk_device_context()
                    .unwrap()
                    .create_shader_module_from_bytes(&shader_module_resource_def.code)?
                    .into();

                let resource = ShaderModuleResource {
                    shader_module,
                    shader_module_resource_def: shader_module_resource_def.clone(),
                    shader_module_key: shader_module_key.clone(),
                };
                log::trace!("Created shader module {:?}", resource);
                Ok(resource)
            })
    }

    pub fn get_or_create_sampler(
        &self,
        sampler_def: &RafxSamplerDef,
    ) -> RafxResult<ResourceArc<SamplerResource>> {
        let hash = SamplerHash::new(sampler_def);
        let sampler_key = SamplerKey { hash };

        self.inner.samplers.get_or_create(&sampler_key, || {
            log::trace!("Creating sampler\n{:#?}", sampler_def);

            let sampler = self.inner.device_context.create_sampler(sampler_def)?;

            let resource = SamplerResource {
                sampler,
                sampler_key: sampler_key.clone(),
            };

            log::trace!("Created sampler {:?}", resource);
            Ok(resource)
        })
    }

    pub fn get_or_create_shader(
        &self,
        shader_stage_defs: &[RafxShaderStageDef],
        shader_modules: &[ResourceArc<ShaderModuleResource>],
    ) -> RafxResult<ResourceArc<ShaderResource>> {
        let shader_module_hashes: Vec<_> = shader_modules
            .iter()
            .map(|x| x.get_raw().shader_module_key.hash)
            .collect();
        let hash = ShaderHash::new(shader_stage_defs, &shader_module_hashes);
        let key = ShaderKey { hash };

        self.inner.shaders.get_or_create(&key, || {
            log::trace!("Creating sampler\n{:#?}", shader_stage_defs);

            let shader = self
                .inner
                .device_context
                .create_shader(shader_stage_defs.iter().cloned().collect())?;

            let resource = ShaderResource {
                key,
                shader,
                shader_modules: shader_modules.iter().cloned().collect(),
            };

            log::trace!("Created sampler {:?}", resource);
            Ok(resource)
        })
    }

    pub fn get_or_create_root_signature(
        &self,
        shader_resources: &[ResourceArc<ShaderResource>],
        immutable_sampler_keys: &[RafxImmutableSamplerKey],
        immutable_sampler_resources: &[Vec<ResourceArc<SamplerResource>>],
    ) -> RafxResult<ResourceArc<RootSignatureResource>> {
        let shader_hashes: Vec<_> = shader_resources
            .iter()
            .map(|x| x.get_raw().key.hash)
            .collect();

        let mut sampler_hashes = Vec::with_capacity(immutable_sampler_resources.len());
        for sampler_list in immutable_sampler_resources {
            let hashes: Vec<_> = sampler_list
                .iter()
                .map(|x| x.get_raw().sampler_key.hash)
                .collect();
            sampler_hashes.push(hashes);
        }

        let hash = RootSignatureHash::new(&shader_hashes, immutable_sampler_keys, &sampler_hashes);
        let key = RootSignatureKey { hash };

        self.inner.root_signatures.get_or_create(&key, || {
            let mut samplers = Vec::with_capacity(immutable_sampler_resources.len());
            for sampler_list in immutable_sampler_resources {
                let cloned_sampler_list: Vec<_> = sampler_list
                    .iter()
                    .map(|x| x.get_raw().sampler.clone())
                    .collect();
                samplers.push(cloned_sampler_list);
            }

            let mut immutable_samplers = Vec::with_capacity(samplers.len());
            for i in 0..samplers.len() {
                immutable_samplers.push(RafxImmutableSamplers {
                    key: immutable_sampler_keys[i].clone(),
                    samplers: &samplers[i],
                });
            }

            log::trace!("Creating root signature\n{:#?}", key);
            let shaders: Vec<_> = shader_resources
                .iter()
                .map(|x| x.get_raw().shader.clone())
                .collect();
            let root_signature =
                self.inner
                    .device_context
                    .create_root_signature(&RafxRootSignatureDef {
                        shaders: &shaders,
                        immutable_samplers: &immutable_samplers,
                    })?;

            let shaders = shader_resources.iter().cloned().collect();

            let mut immutable_samplers = vec![];
            for resource_list in immutable_sampler_resources {
                for resource in resource_list {
                    immutable_samplers.push(resource.clone());
                }
            }

            let resource = RootSignatureResource {
                key,
                root_signature,
                shaders,
                immutable_samplers,
            };

            log::trace!("Created root signature");
            Ok(resource)
        })
    }

    pub fn get_or_create_descriptor_set_layout(
        &self,
        root_signature: &ResourceArc<RootSignatureResource>,
        set_index: u32,
        descriptor_set_layout_def: &DescriptorSetLayout,
    ) -> RafxResult<ResourceArc<DescriptorSetLayoutResource>> {
        let hash = DescriptorSetLayoutHash::new(
            root_signature.get_raw().key.hash,
            set_index,
            descriptor_set_layout_def,
        );
        let key = DescriptorSetLayoutKey { hash };

        self.inner.descriptor_set_layouts.get_or_create(&key, || {
            log::trace!(
                "Creating descriptor set layout set_index={}, root_signature:\n{:#?}",
                set_index,
                root_signature
            );

            // Create the resource object, which contains the descriptor set layout we created plus
            // ResourceArcs to the samplers, which must remain alive for the lifetime of the descriptor set
            let resource = DescriptorSetLayoutResource {
                root_signature_arc: root_signature.clone(),
                root_signature: root_signature.get_raw().root_signature.clone(),
                set_index,
                descriptor_set_layout_def: descriptor_set_layout_def.clone(),
                key: key.clone(),
            };

            log::trace!("Created descriptor set layout {:?}", resource);
            Ok(resource)
        })
    }

    pub fn get_or_create_material_pass(
        &self,
        shader: ResourceArc<ShaderResource>,
        root_signature: ResourceArc<RootSignatureResource>,
        descriptor_sets: Vec<ResourceArc<DescriptorSetLayoutResource>>,
        fixed_function_state: Arc<FixedFunctionState>,
        vertex_inputs: Arc<Vec<MaterialPassVertexInput>>,
    ) -> RafxResult<ResourceArc<MaterialPassResource>> {
        let descriptor_set_hashes: Vec<_> = descriptor_sets
            .iter()
            .map(|x| x.get_raw().key.hash)
            .collect();
        let hash = MaterialPassHash::new(
            shader.get_raw().key.hash,
            root_signature.get_raw().key.hash,
            &descriptor_set_hashes,
            &*fixed_function_state,
            &*vertex_inputs,
        );
        let material_pass_key = MaterialPassKey { hash };

        self.inner
            .material_passes
            .get_or_create(&material_pass_key, || {
                log::trace!("Creating material pass\n{:#?}", material_pass_key);
                let resource = MaterialPassResource {
                    material_pass_key: material_pass_key.clone(),
                    root_signature,
                    descriptor_set_layouts: descriptor_sets,
                    shader,
                    fixed_function_state,
                    vertex_inputs,
                };
                Ok(resource)
            })
    }

    pub fn get_or_create_graphics_pipeline(
        &self,
        material_pass: &ResourceArc<MaterialPassResource>,
        render_target_meta: &GraphicsPipelineRenderTargetMeta,
        primitive_topology: RafxPrimitiveTopology,
        vertex_layout: &RafxVertexLayout,
    ) -> RafxResult<ResourceArc<GraphicsPipelineResource>> {
        let hash = GraphicsPipelineHash::new(
            material_pass.get_raw().material_pass_key.hash,
            render_target_meta,
            primitive_topology,
            vertex_layout,
        );

        let pipeline_key = GraphicsPipelineKey { hash };

        self.inner
            .graphics_pipelines
            .get_or_create(&pipeline_key, || {
                log::trace!("Creating graphics pipeline\n{:#?}", pipeline_key);

                let fixed_function_state = &material_pass.get_raw().fixed_function_state;
                let pipeline = self.inner.device_context.create_graphics_pipeline(
                    &RafxGraphicsPipelineDef {
                        root_signature: &material_pass
                            .get_raw()
                            .root_signature
                            .get_raw()
                            .root_signature,

                        shader: &material_pass.get_raw().shader.get_raw().shader,

                        blend_state: &fixed_function_state.blend_state,
                        depth_state: &fixed_function_state.depth_state,
                        rasterizer_state: &fixed_function_state.rasterizer_state,

                        primitive_topology,
                        vertex_layout: &vertex_layout,

                        color_formats: &render_target_meta.color_formats(),
                        depth_stencil_format: render_target_meta.depth_stencil_format(),
                        sample_count: render_target_meta.sample_count(),
                    },
                )?;

                let resource = GraphicsPipelineResource {
                    render_target_meta: render_target_meta.clone(),
                    pipeline: Arc::new(pipeline),
                    descriptor_set_layouts: material_pass.get_raw().descriptor_set_layouts.clone(),
                };
                Ok(resource)
            })
    }

    pub fn get_or_create_compute_pipeline(
        &self,
        shader: &ResourceArc<ShaderResource>,
        root_signature: &ResourceArc<RootSignatureResource>,
        descriptor_set_layouts: Vec<ResourceArc<DescriptorSetLayoutResource>>,
    ) -> RafxResult<ResourceArc<ComputePipelineResource>> {
        let descriptor_set_hashes: Vec<_> = descriptor_set_layouts
            .iter()
            .map(|x| x.get_raw().key.hash)
            .collect();
        let hash = ComputePipelineHash::new(
            shader.get_raw().key.hash,
            root_signature.get_raw().key.hash,
            &descriptor_set_hashes,
        );
        let pipeline_key = ComputePipelineKey { hash };

        self.inner
            .compute_pipelines
            .get_or_create(&pipeline_key, || {
                log::trace!("Creating compute pipeline\n{:#?}", pipeline_key);
                let rafx_pipeline =
                    self.inner
                        .device_context
                        .create_compute_pipeline(&RafxComputePipelineDef {
                            root_signature: &root_signature.get_raw().root_signature,
                            shader: &shader.get_raw().shader,
                        })?;
                log::trace!("Created compute pipeline {:?}", rafx_pipeline);

                let resource = ComputePipelineResource {
                    root_signature: root_signature.clone(),
                    pipeline: Arc::new(rafx_pipeline),
                    descriptor_set_layouts,
                };
                Ok(resource)
            })
    }

    //
    // A key difference between these insert_image and the insert_image in a DynResourceAllocator
    // is that these can be retrieved. However, a mutable reference is required. This one is
    // more appropriate to use with descriptors loaded from assets, and DynResourceAllocator with runtime-created
    // descriptors
    //
    pub fn insert_texture(
        &self,
        texture: RafxTexture,
    ) -> ResourceArc<ImageResource> {
        let image = RafxImage::Texture(texture);
        self.insert_image(image)
    }

    pub fn insert_render_target(
        &self,
        render_target: RafxRenderTarget,
    ) -> ResourceArc<ImageResource> {
        let image = RafxImage::RenderTarget(render_target);
        self.insert_image(image)
    }

    pub fn insert_image(
        &self,
        image: RafxImage,
    ) -> ResourceArc<ImageResource> {
        let image_id = self.inner.next_image_id.fetch_add(1, Ordering::Relaxed);

        let image_key = ImageKey { id: image_id };

        let resource = ImageResource {
            image: Arc::new(image),
            image_key: Some(image_key),
        };

        self.inner
            .images
            .create(&image_key, || Ok(resource))
            .unwrap()
    }

    //TODO: Support direct removal of raw images with verification that no references remain

    // A key difference between this insert_buffer and the insert_buffer in a DynResourceAllocator
    // is that these can be retrieved. This one is more appropriate to use with loaded assets, and
    // DynResourceAllocator with runtime assets
    pub fn insert_buffer(
        &self,
        buffer: RafxBuffer,
    ) -> ResourceArc<BufferResource> {
        let buffer_id = self.inner.next_buffer_id.fetch_add(1, Ordering::Relaxed);
        let buffer_key = BufferKey { id: buffer_id };

        let resource = BufferResource {
            buffer: Arc::new(buffer),
            buffer_key: Some(buffer_key),
        };

        self.inner
            .buffers
            .create(&buffer_key, || Ok(resource))
            .unwrap()
    }

    pub fn get_or_create_image_view(
        &self,
        image: &ResourceArc<ImageResource>,
        texture_bind_type: Option<RafxTextureBindType>,
    ) -> RafxResult<ResourceArc<ImageViewResource>> {
        if image.get_raw().image_key.is_none() {
            log::error!("Tried to create an image view resource with a dynamic image");
            return Err("Tried to create an image view resource with a dynamic image")?;
        }

        let image_view_key = ImageViewKey {
            image_key: image.get_raw().image_key.unwrap(),
            texture_bind_type,
        };

        self.inner.image_views.get_or_create(&image_view_key, || {
            log::trace!("Creating image view\n{:#?}", image_view_key);
            let resource = ImageViewResource {
                image: image.clone(),
                texture_bind_type,
                image_view_key: Some(image_view_key.clone()),
            };
            log::trace!("Created image view\n{:#?}", resource);

            Ok(resource)
        })
    }
}