File: utils.cpp

package info (click to toggle)
sight 25.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 42,180 kB
  • sloc: cpp: 289,476; xml: 17,257; ansic: 9,878; python: 1,379; sh: 144; makefile: 33
file content (883 lines) | stat: -rw-r--r-- 27,940 bytes parent folder | download
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
/************************************************************************
 *
 * Copyright (C) 2014-2025 IRCAD France
 * Copyright (C) 2014-2020 IHU Strasbourg
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

// cspell:ignore NOLINT

#include "viz/scene3d/utils.hpp"

#include "viz/scene3d/compositor/manager/oit.hpp"
#include "viz/scene3d/detail/collision_tools.hpp"
#include "viz/scene3d/factory/r2vb_renderable.hpp"
#include "viz/scene3d/helper/camera.hpp"
#include "viz/scene3d/layer.hpp"
#include "viz/scene3d/ogre.hpp"
#include "viz/scene3d/vr/grid_proxy_geometry.hpp"

#include <core/os/temp_path.hpp>
#include <core/runtime/path.hpp>
#include <core/spy_log.hpp>
#include <core/tools/os.hpp>

#include <data/helper/medical_image.hpp>

#include <geometry/data/image.hpp>

#include <OGRE/OgreMaterialManager.h>

#include <OgreConfigFile.h>
#include <OgreException.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreResourceGroupManager.h>
#include <OgreTextureManager.h>

#include <algorithm>
#include <cctype> // Needed for isspace()
#include <filesystem>

namespace sight::viz::scene3d
{

static std::list<std::string> s_module_with_resources_names;

static std::set<std::string> s_ogre_plugins;

viz::scene3d::factory::r2vb_renderable* utils::s_r2vb_renderable_factory            = nullptr;
viz::scene3d::vr::grid_proxy_geometry_factory* utils::s_grid_proxy_geometry_factory = nullptr;
viz::scene3d::compositor::manager::oit* utils::s_oit_manager                        = nullptr;

//------------------------------------------------------------------------------

void utils::add_plugins(const std::vector<std::string>& _plugins)
{
    for(const auto& plugin : _plugins)
    {
        s_ogre_plugins.insert(plugin);
    }
}

//------------------------------------------------------------------------------

void utils::load_resources()
{
    Ogre::ConfigFile cf;
    Ogre::String resource_group_name;
    Ogre::String type_name;
    Ogre::String arch_name;

    // Ensure we always load the resources of this library first, since other may reuse our programs or shaders
    std::list<std::string> module_with_resources_names;
    std::copy(
        s_module_with_resources_names.begin(),
        s_module_with_resources_names.end(),
        std::back_inserter(module_with_resources_names)
    );
    module_with_resources_names.emplace_front("sight::viz::scene3d");

    for(const auto& module_name : module_with_resources_names)
    {
        try
        {
            // Check file existence
            const auto path = core::runtime::get_resource_file_path(module_name + "/resources.cfg");

            if(!std::filesystem::exists(path))
            {
                SIGHT_FATAL("File '" + path.string() + "' doesn't exist. Ogre needs it to load resources");
            }

            core::os::temp_file tmp_file;
            std::ofstream new_resource_file(tmp_file);

            if(!std::filesystem::exists(tmp_file))
            {
                SIGHT_FATAL("Can't create the file '" + tmp_file.string() + "'");
            }

            // Copy the resource file and make paths absolute.
            std::ifstream resource_file(path);

            make_paths_absolute("FileSystem", resource_file, new_resource_file, path.parent_path());
            resource_file.close();
            new_resource_file.close();
            cf.load(tmp_file.string());

            const Ogre::ConfigFile::SettingsBySection_ settings_by_section = cf.getSettingsBySection();

            for(const auto& s : settings_by_section)
            {
                resource_group_name = s.first;
                Ogre::ConfigFile::SettingsMultiMap settings = s.second;
                Ogre::ConfigFile::SettingsMultiMap::iterator i;
                for(i = settings.begin() ; i != settings.end() ; ++i)
                {
                    type_name = i->first;
                    arch_name = i->second;
                    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
                        arch_name,
                        type_name,
                        resource_group_name
                    );
                }
            }
        }
        catch(Ogre::FileNotFoundException&)
        {
            SIGHT_ERROR("Unable to find Ogre resources path : " + module_name);
        }
        catch(...)
        {
            SIGHT_ERROR("Unable to load resource from " + module_name);
        }
    }
}

//------------------------------------------------------------------------------

void utils::add_resources_path(const std::string& _module_name)
{
    SIGHT_ASSERT("Empty resource path", !_module_name.empty());

    s_module_with_resources_names.push_front(_module_name);
}

//------------------------------------------------------------------------------

Ogre::Root* utils::get_ogre_root()
{
    using namespace std::literals::string_literals;

    Ogre::Root* root = Ogre::Root::getSingletonPtr();

    if(root == nullptr)
    {
        core::os::temp_file tmp_plugin_cfg;

        // Set the actual plugin path in the plugin config file and add application plugins.
        {
            std::ofstream tmp_plugin_cfg_stream(tmp_plugin_cfg.string());

            SIGHT_FATAL_IF(
                "Can't create temporary config file'" + tmp_plugin_cfg.string() + "'",
                !std::filesystem::exists(tmp_plugin_cfg)
            );

            SIGHT_FATAL_IF("Failed to open new plugin file", !tmp_plugin_cfg_stream.is_open());

            // Find the path of the OgreMain library and deduce the path of the plugins
            const std::string ogre_main_name =
#if defined(_WIN32) && defined(_DEBUG)
                "OgreMain_d";
#else
                "OgreMain";
#endif

            const auto ogre_main_path = core::tools::os::get_shared_library_path(ogre_main_name);
            SIGHT_FATAL_IF("Failed to find `" + ogre_main_name + "`", !std::filesystem::exists(ogre_main_path));
            const auto ogre_lib_path = ogre_main_path.parent_path();

            // Find the ogre plugins path

#if defined(_WIN32)
            const auto ogre_plugins_path = ogre_lib_path.parent_path() / "plugins" / "ogre";
#else
            const auto ogre_plugins_path = ogre_lib_path / "OGRE";
#endif

            // Add render system plugin
            tmp_plugin_cfg_stream << "Plugin=RenderSystem_GL3Plus" << std::endl << std::endl;

            // Write to the new plugin file
            tmp_plugin_cfg_stream << "PluginFolder=" << std::filesystem::canonical(ogre_plugins_path).string();
        }

        root = new Ogre::Root(tmp_plugin_cfg.string());

        const Ogre::RenderSystemList& rs_list = root->getAvailableRenderers();

        Ogre::RenderSystem* rs = nullptr;

        if(!rs_list.empty())
        {
            rs = rs_list.front();
        }

        /*
           This list setup the search order for used render system.
         */
        Ogre::StringVector render_order;

        render_order.emplace_back("OpenGL");

        for(auto& iter : render_order)
        {
            for(auto* it : rs_list)
            {
                if(it->getName().find(iter) != Ogre::String::npos)
                {
                    rs = it;
                    break;
                }
            }

            if(rs != nullptr)
            {
                break;
            }
        }

        SIGHT_ASSERT("Abort render system configuration, no render system found", rs);

        rs->setConfigOption("Full Screen", "false");
        rs->setConfigOption("VSync", "false");
        rs->setConfigOption("Display Frequency", "60");
        rs->setConfigOption("Separate Shader Objects", "No");

        root->setRenderSystem(rs);

        root->initialise(false);

        load_resources();

        // Register factory for R2VB renderables objects
        s_r2vb_renderable_factory = OGRE_NEW viz::scene3d::factory::r2vb_renderable();
        Ogre::Root::getSingleton().addMovableObjectFactory(s_r2vb_renderable_factory);

        // Register factory for grid_proxy_geometry objects
        s_grid_proxy_geometry_factory = OGRE_NEW viz::scene3d::vr::grid_proxy_geometry_factory();
        Ogre::Root::getSingleton().addMovableObjectFactory(s_grid_proxy_geometry_factory);

        // Add the material manager listener that allows us to generate OIT techniques
        s_oit_manager = new viz::scene3d::compositor::manager::oit();
        Ogre::MaterialManager::getSingleton().addListener(s_oit_manager);
    }

    return root;
}

//------------------------------------------------------------------------------

void utils::destroy_ogre_root()
{
    Ogre::MaterialManager::getSingleton().removeListener(s_oit_manager);
    delete s_oit_manager;

    Ogre::Root::getSingleton().removeMovableObjectFactory(s_grid_proxy_geometry_factory);
    delete s_grid_proxy_geometry_factory;

    Ogre::Root::getSingleton().removeMovableObjectFactory(s_r2vb_renderable_factory);
    delete s_r2vb_renderable_factory;

    Ogre::Root* root = viz::scene3d::utils::get_ogre_root();
    Ogre::ResourceGroupManager::getSingleton().shutdownAll();

    // Processes all dirty and pending deletion passes, needs to be done before the root deletion.
    //
    // Actually in some case, the deletion of the Ogre root may cause a crash when material resources are deleted.
    // This function deletes items in the graveyard and allows to delete the root properly.
    Ogre::Pass::processPendingPassUpdates();

    delete root;
}

//------------------------------------------------------------------------------

void utils::convert_from_ogre_texture(Ogre::TexturePtr _texture, const data::image::sptr _image, bool _flip)
{
    SIGHT_ASSERT("texture is null", _texture);
    SIGHT_ASSERT("image is null", _image);

    data::image::size_t image_size = {_texture->getWidth(), 0, 0};

    if(_texture->getHeight() > 1)
    {
        image_size[1] = _texture->getHeight();

        if(_texture->getDepth() > 1)
        {
            image_size[2] = _texture->getDepth();
        }
    }

    auto [type, format] = utils::get_pixel_format_from_ogre(_texture->getFormat());
    data::image::spacing_t spacing = {1., 1., 1.};
    data::image::origin_t origin   = {0., 0., 0.};

    _image->set_spacing(spacing);
    _image->set_origin(origin);
    _image->resize(image_size, type, format);

    // Get the pixel buffer
    Ogre::HardwarePixelBufferSharedPtr pixel_buffer = _texture->getBuffer();

    // Lock the pixel buffer and copy it
    {
        const auto dump_lock = _image->dump_lock();

        auto* __restrict dst_buffer = reinterpret_cast<std::uint8_t*>(_image->buffer());

        pixel_buffer->lock(Ogre::HardwareBuffer::HBL_READ_ONLY);
        const Ogre::PixelBox& pixel_box           = pixel_buffer->getCurrentLock();
        const std::size_t pitch                   = pixel_box.rowPitch * _image->num_components();
        const std::uint8_t* __restrict src_buffer =
            reinterpret_cast<const std::uint8_t*>(pixel_box.data) + (_flip ? pixel_box.getConsecutiveSize() : 0);

        // Copy and flip the image
        const auto num_rows = pixel_box.getConsecutiveSize() / pitch;
        if(_flip)
        {
            for(std::size_t i = 0 ; i < num_rows ; ++i)
            {
                src_buffer -= pitch;
                std::memcpy(dst_buffer, src_buffer, pitch);
                dst_buffer += pitch;
            }
        }
        else
        {
            for(std::size_t i = 0 ; i < num_rows ; ++i)
            {
                std::memcpy(dst_buffer, src_buffer, pitch);
                dst_buffer += pitch;
                src_buffer += pitch;
            }
        }

        // Unlock the pixel buffer
        pixel_buffer->unlock();
    }
}

//------------------------------------------------------------------------------

Ogre::PixelFormat utils::get_pixel_format_ogre(const data::image& _image)
{
    const core::type pixel_type           = _image.type();
    const std::size_t number_of_component = _image.num_components();

    if(number_of_component == 1)
    {
        if(pixel_type == core::type::INT8)
        {
            // int8
            return Ogre::PF_L8;
        }

        if(pixel_type == core::type::UINT8)
        {
            // uint8
            return Ogre::PF_L8;
        }

        if(pixel_type == core::type::INT16)
        {
            // int16
            return Ogre::PF_L16;
        }

        if(pixel_type == core::type::UINT16)
        {
            // uint16
            return Ogre::PF_L16;
        }

        if(pixel_type == core::type::FLOAT)
        {
            // float
            return Ogre::PF_FLOAT32_R;
        }

        if(pixel_type == core::type::INT32)
        {
            // 32 bits are not well handled in our TF approach. However, most 32bits images fits in 16 bits.
            return Ogre::PF_L16;
        }

        if(pixel_type == core::type::UINT32)
        {
            // 32 bits are not well handled in our TF approach. However, most 32bits images fits in 16 bits.
            return Ogre::PF_L16;
        }

        SIGHT_THROW("Format '" + pixel_type.name() + "' not handled");
    }

    if(number_of_component == 2)
    {
        if(pixel_type == core::type::UINT8)
        {
            // uint8
            return Ogre::PF_RG8;
        }

        if(pixel_type == core::type::INT8)
        {
            // int16
            return Ogre::PF_R8G8_SNORM;
        }

        if(pixel_type == core::type::FLOAT)
        {
            // float
            return Ogre::PF_FLOAT32_GR;
        }

        SIGHT_THROW("Format '" + pixel_type.name() + "' not handled");
    }

    // PixelFormat in little endian
    if(pixel_type == core::type::UINT8)
    {
        // uint8
        return number_of_component == 3 ? Ogre::PF_BYTE_RGB : Ogre::PF_BYTE_RGBA;
    }

    if(pixel_type == core::type::UINT16)
    {
        // uint16
        return number_of_component == 3 ? Ogre::PF_R16G16B16_UINT : Ogre::PF_R16G16B16A16_UINT;
    }

    if(pixel_type == core::type::UINT32)
    {
        // uint32
        return number_of_component == 3 ? Ogre::PF_R32G32B32_UINT : Ogre::PF_R32G32B32A32_UINT;
    }

    if(pixel_type == core::type::INT8)
    {
        // int8
        return number_of_component == 3 ? Ogre::PF_R8G8B8_SINT : Ogre::PF_R8G8B8A8_SINT;
    }

    if(pixel_type == core::type::INT16)
    {
        // int16
        return number_of_component == 3 ? Ogre::PF_R16G16B16_SINT : Ogre::PF_R16G16B16A16_SINT;
    }

    if(pixel_type == core::type::INT32)
    {
        // int32
        return number_of_component == 3 ? Ogre::PF_R32G32B32_SINT : Ogre::PF_R32G32B32A32_SINT;
    }

    if(pixel_type == core::type::FLOAT)
    {
        return number_of_component == 3 ? Ogre::PF_FLOAT32_RGB : Ogre::PF_FLOAT32_RGBA;
    }

    if(pixel_type == core::type::DOUBLE)
    {
        SIGHT_FATAL("Pixel format not handled.");
    }

    SIGHT_WARN("Pixel format not found, trying with the default 8-bits RGBA.");
    return Ogre::PF_BYTE_RGBA;
}

//------------------------------------------------------------------------------

Ogre::Vector2 utils::get_texture_window(core::type _format)
{
    static const std::map<core::type, Ogre::Vector2> s_TEXTURE_WINDOW = {
        {core::type::INT8, {std::numeric_limits<std::int8_t>::min(), std::numeric_limits<std::uint8_t>::max()}},
        {core::type::UINT8, {std::numeric_limits<std::uint8_t>::min(), std::numeric_limits<std::uint8_t>::max()}},
        {core::type::INT16, {std::numeric_limits<std::int16_t>::min(), std::numeric_limits<std::uint16_t>::max()}},
        {core::type::UINT16, {std::numeric_limits<std::uint16_t>::min(), std::numeric_limits<std::uint16_t>::max()}},
        // 32 bits are not well handled in our TF approach. However, most 32bits images fits in 16 bits.
        {core::type::INT32, {std::numeric_limits<std::int16_t>::min(), std::numeric_limits<std::uint16_t>::max()}},
        {core::type::UINT32, {std::numeric_limits<std::uint16_t>::min(), std::numeric_limits<std::uint16_t>::max()}},
    };

    SIGHT_ERROR_IF(
        "texture windowing not supported for 64 bits integers formats",
        _format == core::type::INT64 || _format == core::type::UINT64
    );

    auto it = s_TEXTURE_WINDOW.find(_format);
    if(it != s_TEXTURE_WINDOW.end())
    {
        return it->second;
    }

    return {0., 1.};
}

//------------------------------------------------------------------------------

std::pair<core::type, enum data::image::pixel_format_t> utils::get_pixel_format_from_ogre(Ogre::PixelFormat _format)
{
    enum data::image::pixel_format_t pixel_format = data::image::pixel_format_t::undefined;

    switch(_format)
    {
        case Ogre::PF_L8:
        case Ogre::PF_L16:
        case Ogre::PF_R16_UINT:
        case Ogre::PF_R32_SINT:
        case Ogre::PF_FLOAT32_R:
            pixel_format = data::image::pixel_format_t::gray_scale;
            break;

        case Ogre::PF_RG8:
        case Ogre::PF_R8G8_SNORM:
            SIGHT_FATAL("Pixel format " << _format << " not found.");
            break;

        case Ogre::PF_BYTE_RGB:
        case Ogre::PF_R8G8B8:
        case Ogre::PF_R16G16B16_UINT:
        case Ogre::PF_R32G32B32_UINT:
        case Ogre::PF_R8G8B8_SINT:
        case Ogre::PF_R16G16B16_SINT:
        case Ogre::PF_R32G32B32_SINT:
        case Ogre::PF_SHORT_RGB:
        case Ogre::PF_FLOAT32_RGB:
            pixel_format = data::image::pixel_format_t::rgb;
            break;

        case Ogre::PF_BYTE_RGBA:
        case Ogre::PF_A8R8G8B8:
        case Ogre::PF_B8G8R8A8:
        case Ogre::PF_R8G8B8A8:
        case Ogre::PF_X8R8G8B8:
        case Ogre::PF_X8B8G8R8:
        case Ogre::PF_R16G16B16A16_UINT:
        case Ogre::PF_R32G32B32A32_UINT:
        case Ogre::PF_R8G8B8A8_SINT:
        case Ogre::PF_R16G16B16A16_SINT:
        case Ogre::PF_R32G32B32A32_SINT:
        case Ogre::PF_SHORT_RGBA:
        case Ogre::PF_FLOAT32_RGBA:
            pixel_format = data::image::pixel_format_t::rgba;
            break;

        default:
            SIGHT_FATAL("Pixel format " << _format << " not found.");
    }

    core::type pixel_type;
    switch(_format)
    {
        case Ogre::PF_L8:
        case Ogre::PF_RG8:
        case Ogre::PF_R8G8B8:
        case Ogre::PF_A8R8G8B8:
        case Ogre::PF_B8G8R8A8:
        case Ogre::PF_R8G8B8A8:
        case Ogre::PF_X8R8G8B8:
        case Ogre::PF_X8B8G8R8:
        case Ogre::PF_BYTE_RGB:
        case Ogre::PF_BYTE_RGBA:
            pixel_type = core::type::UINT8;
            break;

        case Ogre::PF_R8G8_SNORM:
        case Ogre::PF_R8G8B8_SINT:
        case Ogre::PF_R8G8B8A8_SINT:
            pixel_type = core::type::INT8;
            break;

        case Ogre::PF_L16:
        case Ogre::PF_R16G16B16_UINT:
        case Ogre::PF_R16_UINT:
        case Ogre::PF_R16G16B16A16_UINT:
            pixel_type = core::type::UINT16;
            break;

        case Ogre::PF_SHORT_RGB:
        case Ogre::PF_SHORT_RGBA:
        case Ogre::PF_R16G16B16_SINT:
        case Ogre::PF_R16G16B16A16_SINT:
            pixel_type = core::type::INT16;
            break;

        case Ogre::PF_R32G32B32_UINT:
        case Ogre::PF_R32G32B32A32_UINT:
            pixel_type = core::type::UINT32;
            break;

        case Ogre::PF_R32G32B32_SINT:
        case Ogre::PF_R32_SINT:
        case Ogre::PF_R32G32B32A32_SINT:
            pixel_type = core::type::INT32;
            break;

        case Ogre::PF_FLOAT32_R:
        case Ogre::PF_FLOAT32_RGB:
        case Ogre::PF_FLOAT32_RGBA:
            pixel_type = core::type::FLOAT;
            break;

        default:
            SIGHT_ERROR("Pixel format " << _format << " not found, defaults to s_UINT8.");
            pixel_type = core::type::UINT8;
    }

    return std::make_pair(pixel_type, pixel_format);
}

//------------------------------------------------------------------------------

void utils::allocate_texture(
    Ogre::Texture* _texture,
    std::size_t _width,
    std::size_t _height,
    std::size_t _depth,
    Ogre::PixelFormat _format,
    Ogre::TextureType _tex_type,
    bool _dynamic
)
{
    auto usage = _dynamic ? Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE : Ogre::TU_STATIC_WRITE_ONLY;

    _texture->unload();

    _texture->setWidth(static_cast<Ogre::uint32>(_width));
    _texture->setHeight(static_cast<Ogre::uint32>(_height));
    _texture->setDepth(static_cast<Ogre::uint32>(_depth));
    _texture->setTextureType(_tex_type);
    _texture->setNumMipmaps(0);

    _texture->setFormat(_format);
    _texture->setUsage(usage);

    _texture->createInternalResources();
}

//------------------------------------------------------------------------------

data::color::sptr utils::from_ogre_color(const Ogre::ColourValue& _ogre_color)
{
    data::color::sptr fw_color = std::make_shared<data::color>();
    fw_color->set_rgba(_ogre_color.r, _ogre_color.g, _ogre_color.b, _ogre_color.a);

    return fw_color;
}

//------------------------------------------------------------------------------

Ogre::Matrix4 utils::to_ogre_matrix(const data::matrix4::csptr& _tm3d)
{
    std::array<Ogre::Real, 16> float_data {};
    std::transform(_tm3d->begin(), _tm3d->end(), float_data.begin(), boost::numeric_cast<float, double>);

    return Ogre::Matrix4(float_data.data());
}

//------------------------------------------------------------------------------

void utils::from_ogre_matrix(const Ogre::Matrix4& _mx, const data::matrix4::sptr& _tm3d)
{
    for(std::uint8_t l = 0 ; l < 4 ; ++l)
    {
        for(std::uint8_t c = 0 ; c < 4 ; ++c)
        {
            (*_tm3d)(l, c) = _mx[l][c];
        }
    }
}

//------------------------------------------------------------------------------

Ogre::Vector3 utils::get_ogre_spacing(const data::image& _image)
{
    const auto& spacing = _image.spacing();

    return {
        static_cast<Ogre::Real>(spacing[0]),
        static_cast<Ogre::Real>(spacing[1]),
        static_cast<Ogre::Real>(spacing[2])
    };
}

//------------------------------------------------------------------------------

Ogre::Vector3 utils::get_ogre_origin(const data::image& _image)
{
    const auto& origin = _image.origin();

    return {
        static_cast<Ogre::Real>(origin[0]),
        static_cast<Ogre::Real>(origin[1]),
        static_cast<Ogre::Real>(origin[2])
    };
}

//------------------------------------------------------------------------------

Ogre::Quaternion utils::get_ogre_orientation(const data::image& _image)
{
    const auto& orientation = _image.orientation();

    return Ogre::Matrix3 {
        static_cast<Ogre::Real>(orientation[0]),
        static_cast<Ogre::Real>(orientation[1]),
        static_cast<Ogre::Real>(orientation[2]),
        static_cast<Ogre::Real>(orientation[3]),
        static_cast<Ogre::Real>(orientation[4]),
        static_cast<Ogre::Real>(orientation[5]),
        static_cast<Ogre::Real>(orientation[6]),
        static_cast<Ogre::Real>(orientation[7]),
        static_cast<Ogre::Real>(orientation[8])
    };
}

//------------------------------------------------------------------------------

Ogre::Vector3i utils::world_to_slices(const data::image& _image, const Ogre::Vector3& _world)
{
    // Avoid 0 division
    const auto& spacing = _image.spacing();

    SIGHT_THROW_EXCEPTION_IF(
        core::exception("image spacing cannot be '0'"),
        core::is_equal(0.0, spacing[0])
        || core::is_equal(0.0, spacing[1])
        || core::is_equal(0.0, spacing[2])
    );

    const auto voxel  = geometry::data::world_to_image(_image, _world, true);
    const auto& sizes = _image.size();

    for(std::size_t i = 0 ; i < sizes.size() ; ++i)
    {
        if(voxel[int(i)] < 0 || voxel[int(i)] >= int(sizes[i]))
        {
            SIGHT_THROW_EXCEPTION(core::exception("Point is outside image boundaries"));
        }
    }

    return {
        static_cast<int>(voxel[0]),
        static_cast<int>(voxel[1]),
        static_cast<int>(voxel[2])
    };
}

//------------------------------------------------------------------------------

std::optional<std::pair<Ogre::MovableObject*, Ogre::Vector3> > utils::pick_object(
    int _x,
    int _y,
    std::uint32_t _query_mask,
    Ogre::SceneManager& _layer,
    bool _shift_toward_camera
)
{
    const auto* const camera = _layer.getCamera(viz::scene3d::layer::DEFAULT_CAMERA_NAME);
    const auto vp_pos        = viz::scene3d::helper::camera::convert_from_window_to_viewport_space(*camera, _x, _y);
    const Ogre::Ray vp_ray   = camera->getCameraToViewportRay(vp_pos.x, vp_pos.y);

    viz::scene3d::detail::collision_tools tool(_layer, _query_mask);

    auto&& [entityFound, rayIntersect, selectedObject, _] = tool.raycast(vp_ray, _query_mask);

    if(entityFound)
    {
        SIGHT_DEBUG("Entity find and intersect at " << rayIntersect << "(WS)");

        if(_shift_toward_camera)
        {
            rayIntersect -= vp_ray.getDirection() * 0.01F;
        }
    }
    else
    {
        return std::nullopt;
    }

    return std::make_optional(std::make_pair(selectedObject, rayIntersect));
}

//------------------------------------------------------------------------------

std::string utils::pick_image(
    const data::image& _image,
    const Ogre::Vector3& _position
)
{
    const auto picked_voxel = geometry::data::world_to_image(_image, _position, true, true);
    const auto intensity    = _image.get_pixel_as_string(
        data::image::index_t(picked_voxel[0]),
        data::image::index_t(picked_voxel[1]),
        data::image::index_t(picked_voxel[2])
    );

    return "(" + std::to_string(picked_voxel[0]) + ", "
           + std::to_string(picked_voxel[1]) + ", "
           + std::to_string(picked_voxel[2]) + "): "
           + intensity;
}

//------------------------------------------------------------------------------

bool utils::make_paths_absolute(
    const std::string& _key,
    std::istream& _input,
    std::ostream& _output,
    const std::filesystem::path& _module_path
)
{
    bool key_found = false;

    const std::size_t key_size = _key.size();

    for(std::string line ; std::getline(_input, line) ; )
    {
        // Remove all whitespace from the line.
        line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());

        // Skip comments, go to the next line.
        if(line[0] != '#')
        {
            if(line.substr(0, key_size) == _key)
            {
                SIGHT_FATAL_IF("Key '" + _key + "' has no value bound to it.", line.size() < key_size + 1);

                const auto current_path = std::filesystem::path(line.substr(key_size + 1));

                if(!current_path.is_absolute())
                {
                    const auto abs_path = _module_path / current_path;
                    _output << _key << "=" << abs_path.string() << std::endl;
                }
                else
                {
                    _output << line << std::endl;
                }

                key_found = true;
            }
            else
            {
                _output << line << std::endl;
            }
        }
    }

    return key_found;
}

//------------------------------------------------------------------------------

} // namespace sight::viz::scene3d