diff --git a/Dependencies/LFramework.CMake/LICENSE b/Dependencies/LFramework.CMake/LICENSE deleted file mode 100644 index 033687c..0000000 --- a/Dependencies/LFramework.CMake/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 Sergey Serb - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Dependencies/LFramework.CMake/README.md b/Dependencies/LFramework.CMake/README.md deleted file mode 100644 index cd90e1d..0000000 --- a/Dependencies/LFramework.CMake/README.md +++ /dev/null @@ -1 +0,0 @@ -# LFramework.CMake \ No newline at end of file diff --git a/Dependencies/LFramework.CMake/nuget.cmake b/Dependencies/LFramework.CMake/nuget.cmake deleted file mode 100644 index 20dca77..0000000 --- a/Dependencies/LFramework.CMake/nuget.cmake +++ /dev/null @@ -1,10 +0,0 @@ -find_program(nuget "nuget" REQUIRED) - - -function(nugetRestore) - execute_process( - COMMAND "${nuget}" "restore" "-PackagesDirectory" "${CMAKE_SOURCE_DIR}/packages" - WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" - ) - #nuget restore -PackagesDirectory ./packages -endfunction() diff --git a/Dependencies/LFramework.CMake/stm32/F7.cmake b/Dependencies/LFramework.CMake/stm32/F7.cmake deleted file mode 100644 index f30eb50..0000000 --- a/Dependencies/LFramework.CMake/stm32/F7.cmake +++ /dev/null @@ -1,40 +0,0 @@ - - - -set(MCU_ARCH cortex-m7) -set(MCU_FLOAT_ABI softfp) -set(MCU_FPU fpv4-sp-d16) - - -set(COMMON_COMPILE_FLAGS -mcpu=${MCU_ARCH} -mthumb -mfloat-abi=${MCU_FLOAT_ABI} -mfpu=${MCU_FPU}) -set(C_CXX_COMPILE_FLAGS -ffunction-sections -fdata-sections -fsigned-char -g -fmessage-length=0) - -if(NOT (TARGET STM32::F7)) - add_library(STM32::F7 INTERFACE IMPORTED) - - target_compile_options(STM32::F7 INTERFACE - --sysroot="${TOOLCHAIN_SYSROOT}" - ${COMMON_COMPILE_FLAGS} - ) - - #target_compile_options(STM32::F7 INTERFACE $<$:-x assembler-with-cpp>) - target_compile_options(STM32::F7 INTERFACE $<$:${C_CXX_COMPILE_FLAGS}>) - target_compile_options(STM32::F7 INTERFACE $<$:${C_CXX_COMPILE_FLAGS}>) - target_compile_options(STM32::F7 INTERFACE $<$:-fno-exceptions -fno-rtti -fno-use-cxa-atexit -fno-threadsafe-statics>) - - target_link_options(STM32::F7 INTERFACE - --sysroot="${TOOLCHAIN_SYSROOT}" - ${COMMON_COMPILE_FLAGS} - ${C_CXX_COMPILE_FLAGS} - LINKER:-gc-sections - ) - - - target_link_options(STM32::F7 INTERFACE $<$:LINKER:--undefined=vTaskSwitchContext,--undefined=HardFault_HandlerC,-undefined=_realloc_r>) - - target_compile_definitions(STM32::F7 INTERFACE - STM32F7 - "__weak=__attribute__((weak))" - "__packed=__attribute__((__packed__))" - ) -endif() \ No newline at end of file diff --git a/Dependencies/LFramework.CMake/stm32/FindStm32CmsisCore.cmake b/Dependencies/LFramework.CMake/stm32/FindStm32CmsisCore.cmake deleted file mode 100644 index 0236fce..0000000 --- a/Dependencies/LFramework.CMake/stm32/FindStm32CmsisCore.cmake +++ /dev/null @@ -1,25 +0,0 @@ -add_library(Stm32CmsisCore INTERFACE) - -target_include_directories(Stm32CmsisCore -INTERFACE - ${STM32_CMSIS_CORE_SOURCE_DIR}/Core/Include - ${STM32_CMSIS_CORE_SOURCE_DIR}/RTOS2/Include -) - - -file(GLOB_RECURSE Stm32CmsisCore_HEADERS "${STM32_CMSIS_CORE_SOURCE_DIR}/Core/Include/*.h" "${STM32_CMSIS_CORE_SOURCE_DIR}/RTOS2/Include/*.h") -#file(GLOB_RECURSE cmsis_device_f7_SOURCES1 "${cmsis_device_f7_SOURCE_DIR}/Src/**/*.c") - -target_sources(Stm32CmsisCore -INTERFACE - ${Stm32CmsisCore_HEADERS1} -) - - - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Stm32CmsisCore -REQUIRED_VARS - Stm32CmsisCore_HEADERS - #Stm32CmsisCore_SOURCES -) diff --git a/Dependencies/LFramework.CMake/stm32/FindStm32CmsisDevice.cmake b/Dependencies/LFramework.CMake/stm32/FindStm32CmsisDevice.cmake deleted file mode 100644 index 10516cc..0000000 --- a/Dependencies/LFramework.CMake/stm32/FindStm32CmsisDevice.cmake +++ /dev/null @@ -1,33 +0,0 @@ -add_library(Stm32CmsisDevice INTERFACE) - -target_include_directories(Stm32CmsisDevice -INTERFACE - ${STM32_CMSIS_DEVICE_SOURCE_DIR}/Include -) - -file(GLOB_RECURSE Stm32CmsisDevice_HEADERS "${STM32_CMSIS_DEVICE_SOURCE_DIR}/Include/*.h") - -set(Stm32CmsisDevice_SOURCES - ${STM32_CMSIS_DEVICE_SOURCE_DIR}/Source/Templates/system_stm32f7xx.c - ${STM32_CMSIS_DEVICE_SOURCE_DIR}/Source/Templates/gcc/startup_stm32f746xx.s -) - -target_compile_definitions(Stm32CmsisDevice -INTERFACE - STM32${MCU_FAMILY}${MCU_CORE}${MCU_LINE}xx -) - - -target_sources(Stm32CmsisDevice -INTERFACE - ${Stm32CmsisDevice_HEADERS} - ${Stm32CmsisDevice_SOURCES} -) - - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Stm32CmsisDevice -REQUIRED_VARS - Stm32CmsisDevice_HEADERS - Stm32CmsisDevice_SOURCES -) \ No newline at end of file diff --git a/Dependencies/LFramework.CMake/stm32/FindStm32FreeRtos.cmake b/Dependencies/LFramework.CMake/stm32/FindStm32FreeRtos.cmake deleted file mode 100644 index 9310a1b..0000000 --- a/Dependencies/LFramework.CMake/stm32/FindStm32FreeRtos.cmake +++ /dev/null @@ -1,37 +0,0 @@ -add_library(Stm32FreeRtos INTERFACE) - -target_include_directories(Stm32FreeRtos -INTERFACE - ${STM32_FREERTOS_SOURCE_DIR}/Source - ${STM32_FREERTOS_SOURCE_DIR}/Source/include - #${STM32_FREERTOS_SOURCE_DIR}/Source/CMSIS_RTOS_V2 - ${STM32_FREERTOS_SOURCE_DIR}/Source/portable/GCC/ARM_CM7/r0p1 -) - -file(GLOB_RECURSE Stm32FreeRtos_HEADERS - #"${STM32_FREERTOS_SOURCE_DIR}/Source/CMSIS_RTOS_V2/*.h" - "${STM32_FREERTOS_SOURCE_DIR}/Source/include/**/*.h" - "${STM32_FREERTOS_SOURCE_DIR}/Source/portable/GCC/ARM_CM7/*.h" -) - -file(GLOB_RECURSE Stm32FreeRtos_SOURCES - #"${STM32_FREERTOS_SOURCE_DIR}/Source/CMSIS_RTOS_V2/*.c" - "${STM32_FREERTOS_SOURCE_DIR}/Source/portable/GCC/ARM_CM7/*.c" -) - -file(GLOB Stm32FreeRtos_SOURCES2 "${STM32_FREERTOS_SOURCE_DIR}/Source/*.c") -list(APPEND Stm32FreeRtos_SOURCES ${Stm32FreeRtos_SOURCES2} ${STM32_FREERTOS_SOURCE_DIR}/Source/portable/MemMang/heap_4.c) - -target_sources(Stm32FreeRtos -INTERFACE - ${Stm32FreeRtos_HEADERS} - ${Stm32FreeRtos_SOURCES} -) - - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Stm32FreeRtos -REQUIRED_VARS - Stm32FreeRtos_HEADERS - Stm32FreeRtos_SOURCES -) \ No newline at end of file diff --git a/Dependencies/LFramework.CMake/stm32/FindStm32Hal.cmake b/Dependencies/LFramework.CMake/stm32/FindStm32Hal.cmake deleted file mode 100644 index eafb9b6..0000000 --- a/Dependencies/LFramework.CMake/stm32/FindStm32Hal.cmake +++ /dev/null @@ -1,25 +0,0 @@ -add_library(Stm32Hal INTERFACE) - -target_include_directories(Stm32Hal -INTERFACE - ${STM32_HAL_SOURCE_DIR}/Inc - ${STM32_HAL_SOURCE_DIR}/Inc/Legacy -) - -file(GLOB_RECURSE Stm32Hal_HEADERS "${STM32_HAL_SOURCE_DIR}/Inc/*.h") -file(GLOB_RECURSE Stm32Hal_SOURCES "${STM32_HAL_SOURCE_DIR}/Src/*.c") -list(FILTER Stm32Hal_SOURCES EXCLUDE REGEX ".*_template.c$") - -target_sources(Stm32Hal -INTERFACE - ${Stm32Hal_HEADERS} - ${Stm32Hal_SOURCES} -) - - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Stm32Hal -REQUIRED_VARS - Stm32Hal_HEADERS - Stm32Hal_SOURCES -) \ No newline at end of file diff --git a/Dependencies/LFramework.CMake/stm32/FindStm32UsbDevice.cmake b/Dependencies/LFramework.CMake/stm32/FindStm32UsbDevice.cmake deleted file mode 100644 index 8957cfe..0000000 --- a/Dependencies/LFramework.CMake/stm32/FindStm32UsbDevice.cmake +++ /dev/null @@ -1,25 +0,0 @@ -add_library(Stm32UsbDevice INTERFACE) - -target_include_directories(Stm32UsbDevice -INTERFACE - ${STM32_USB_DEVICE_SOURCE_DIR}/Core/Inc -) - -file(GLOB_RECURSE Stm32UsbDevice_HEADERS "${STM32_USB_DEVICE_SOURCE_DIR}/Core/Inc/*.h") -file(GLOB_RECURSE Stm32UsbDevice_SOURCES "${STM32_USB_DEVICE_SOURCE_DIR}/Core/Src/*.c") -list(FILTER Stm32UsbDevice_SOURCES EXCLUDE REGEX ".*_template.c$") -list(FILTER Stm32UsbDevice_HEADERS EXCLUDE REGEX ".*_template.h$") - -target_sources(Stm32UsbDevice -INTERFACE - ${Stm32UsbDevice_HEADERS} - ${Stm32UsbDevice_SOURCES} -) - - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Stm32UsbDevice -REQUIRED_VARS - Stm32UsbDevice_HEADERS - Stm32UsbDevice_SOURCES -) \ No newline at end of file diff --git a/Dependencies/LFramework.CMake/stm32/FindStm32UsbHost.cmake b/Dependencies/LFramework.CMake/stm32/FindStm32UsbHost.cmake deleted file mode 100644 index e69de29..0000000 diff --git a/Dependencies/LFramework.CMake/stm32/H7.cmake b/Dependencies/LFramework.CMake/stm32/H7.cmake deleted file mode 100644 index 1ef9039..0000000 --- a/Dependencies/LFramework.CMake/stm32/H7.cmake +++ /dev/null @@ -1,38 +0,0 @@ - -set(MCU_ARCH cortex-m7) -set(MCU_FLOAT_ABI hard) -set(MCU_FPU fpv5-d16) - - -set(COMMON_COMPILE_FLAGS -mcpu=${MCU_ARCH} -mthumb -mfloat-abi=${MCU_FLOAT_ABI} -mfpu=${MCU_FPU}) -set(C_CXX_COMPILE_FLAGS -ffunction-sections -fdata-sections -fsigned-char -g -fmessage-length=0) - -if(NOT (TARGET STM32::H7)) - add_library(STM32::H7 INTERFACE IMPORTED) - - target_compile_options(STM32::H7 INTERFACE - --sysroot="${TOOLCHAIN_SYSROOT}" - ${COMMON_COMPILE_FLAGS} - ) - - #target_compile_options(STM32::H7 INTERFACE $<$:-x assembler-with-cpp>) - target_compile_options(STM32::H7 INTERFACE $<$:${C_CXX_COMPILE_FLAGS}>) - target_compile_options(STM32::H7 INTERFACE $<$:${C_CXX_COMPILE_FLAGS}>) - target_compile_options(STM32::H7 INTERFACE $<$:-fno-exceptions -fno-rtti -fno-use-cxa-atexit -fno-threadsafe-statics>) - - target_link_options(STM32::H7 INTERFACE - --sysroot="${TOOLCHAIN_SYSROOT}" - ${COMMON_COMPILE_FLAGS} - ${C_CXX_COMPILE_FLAGS} - LINKER:-gc-sections - ) - - - target_link_options(STM32::H7 INTERFACE $<$:LINKER:--undefined=vTaskSwitchContext,--undefined=HardFault_HandlerC,-undefined=_realloc_r>) - - target_compile_definitions(STM32::H7 INTERFACE - STM32H7 - "__weak=__attribute__((weak))" - "__packed=__attribute__((__packed__))" - ) -endif() \ No newline at end of file diff --git a/Dependencies/LFramework.CMake/stm32/fetch.cmake b/Dependencies/LFramework.CMake/stm32/fetch.cmake deleted file mode 100644 index 56f39e1..0000000 --- a/Dependencies/LFramework.CMake/stm32/fetch.cmake +++ /dev/null @@ -1,152 +0,0 @@ -if (DEFINED STM32_DEVICE AND NOT STM32_DEVICE STREQUAL "") - string(REGEX MATCH "STM(32|8)(F|L|H|W|U)([0-9])([^A-Z]+)([A-Z])(.)" STM32_DEVICE_ ${STM32_DEVICE}]) - set(MCU_FAMILY ${CMAKE_MATCH_2}) - set(MCU_CORE ${CMAKE_MATCH_3}) - set(MCU_LINE ${CMAKE_MATCH_4}) - - message("MCU_FAMILY: ${MCU_FAMILY}") - message("MCU_CORE: ${MCU_CORE}") - message("MCU_LINE: ${MCU_LINE}") - - set(STM32_FAMILY_EX "${MCU_FAMILY}${MCU_CORE}" ) - - message("STM32_FAMILY_EX: ${STM32_FAMILY_EX}") -else() - message("STM32_DEVICE not defined") -endif() - - - -set(STM32_FAMILIES F7 ) -set(STM32_HAL_DEFAULT_VERSION v1.3.0 ) -set(STM32_FREERTOS_DEFAULT_VERSION v10.5.1 ) -set(STM32_CMSIS_DEVICE_DEFAULT_VERSION v1.2.8 ) - -set(STM32_CMSIS_CORE_DEFAULT_VERSION v5.6.0 ) - -set(STM32_USB_DEVICE_DEFAULT_VERSION v2.11.2 ) -set(STM32_USB_HOST_DEFAULT_VERSION v3.5.1 ) - -include(FetchContent) - -FetchContent_Declare(stm32_usb_host - GIT_REPOSITORY https://github.com/STMicroelectronics/stm32_mw_usb_host.git - GIT_TAG ${STM32_USB_HOST_DEFAULT_VERSION} - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - GIT_PROGRESS TRUE -) - -FetchContent_Declare(stm32_usb_device - GIT_REPOSITORY https://github.com/STMicroelectronics/stm32_mw_usb_device.git - GIT_TAG ${STM32_USB_DEVICE_DEFAULT_VERSION} - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - GIT_PROGRESS TRUE -) - -function(FetchStm32UsbDevice) - string(TOLOWER ${STM32_FAMILY_EX} STM32_FAMILY_EX_LOWER_CASE) - FetchContent_MakeAvailable(stm32_usb_device) - set(STM32_USB_DEVICE_SOURCE_DIR ${stm32_usb_device_SOURCE_DIR} PARENT_SCOPE) -endfunction() - -function(FetchStm32UsbHost) - string(TOLOWER ${STM32_FAMILY_EX} STM32_FAMILY_EX_LOWER_CASE) - FetchContent_MakeAvailable(stm32_usb_host) - set(STM32_USB_HOST_SOURCE_DIR ${stm32_usb_host_SOURCE_DIR} PARENT_SCOPE) -endfunction() - - - -FetchContent_Declare(stm32_cmsis_core - GIT_REPOSITORY https://github.com/STMicroelectronics/cmsis_core.git - GIT_TAG ${STM32_CMSIS_CORE_DEFAULT_VERSION} - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - GIT_PROGRESS TRUE -) - - -set(ARRAY_INDEX 0) -foreach(FAMILY ${STM32_FAMILIES}) - string(TOLOWER ${FAMILY} STM_FAMILY_LOWER_CASE) - - if (DEFINED STM32_HAL_VERSION AND NOT STM32_HAL_VERSION STREQUAL "") - - else() - list(GET STM32_HAL_DEFAULT_VERSION ${ARRAY_INDEX} STM32_HAL_VERSION) - endif() - message("STM32_HAL_VERSION: ${STM32_HAL_VERSION}") - - if (DEFINED STM32_FREERTOS_VERSION AND NOT STM32_FREERTOS_VERSION STREQUAL "") - - else() - list(GET STM32_FREERTOS_DEFAULT_VERSION ${ARRAY_INDEX} STM32_FREERTOS_VERSION) - endif() - message("STM32_FREERTOS_VERSION: ${STM32_FREERTOS_VERSION}") - - - if (DEFINED STM32_CMSIS_DEVICE_VERSION AND NOT STM32_CMSIS_DEVICE_VERSION STREQUAL "") - - else() - list(GET STM32_CMSIS_DEVICE_DEFAULT_VERSION ${ARRAY_INDEX} STM32_CMSIS_DEVICE_VERSION) - endif() - message("STM32_CMSIS_DEVICE_VERSION: ${STM32_CMSIS_DEVICE_VERSION}") - - #CMSIS Device - FetchContent_Declare(stm32_cmsis_device_${STM_FAMILY_LOWER_CASE} - GIT_REPOSITORY https://github.com/STMicroelectronics/cmsis_device_${STM_FAMILY_LOWER_CASE}.git - GIT_TAG ${STM32_CMSIS_DEVICE_VERSION} - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - GIT_PROGRESS TRUE - ) - - #Hal - FetchContent_Declare(stm32_hal_${STM_FAMILY_LOWER_CASE} - GIT_REPOSITORY https://github.com/STMicroelectronics/stm32${STM_FAMILY_LOWER_CASE}xx_hal_driver.git - GIT_TAG ${STM32_HAL_VERSION} - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - GIT_PROGRESS TRUE - ) - - #FreeRTOS - FetchContent_Declare(stm32_freertos - GIT_REPOSITORY https://github.com/STMicroelectronics/stm32_mw_freertos.git - GIT_TAG ${STM32_FREERTOS_VERSION} - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - GIT_PROGRESS TRUE - ) - - math(EXPR ARRAY_INDEX "${ARRAY_INDEX} + 1") -endforeach() - - - - - - -function(FetchStm32Hal) - string(TOLOWER ${STM32_FAMILY_EX} STM32_FAMILY_EX_LOWER_CASE) - FetchContent_MakeAvailable(stm32_hal_${STM32_FAMILY_EX_LOWER_CASE} ) - set(STM32_HAL_SOURCE_DIR ${stm32_hal_${STM32_FAMILY_EX_LOWER_CASE}_SOURCE_DIR} PARENT_SCOPE) -endfunction() - -function(FetchStm32FreeRtos) - FetchContent_MakeAvailable(stm32_freertos) - set(STM32_FREERTOS_SOURCE_DIR ${stm32_freertos_SOURCE_DIR} PARENT_SCOPE) -endfunction() - -function(FetchStm32CmsisDevice) - string(TOLOWER ${STM32_FAMILY_EX} STM32_FAMILY_EX_LOWER_CASE) - FetchContent_MakeAvailable(stm32_cmsis_device_${STM32_FAMILY_EX}) - set(STM32_CMSIS_DEVICE_SOURCE_DIR ${stm32_cmsis_device_${STM32_FAMILY_EX_LOWER_CASE}_SOURCE_DIR} PARENT_SCOPE) -endfunction() - -function(FetchStm32CmsisCore) - FetchContent_MakeAvailable(STM32_CMSIS_CORE) - set(STM32_CMSIS_CORE_SOURCE_DIR ${stm32_cmsis_core_SOURCE_DIR} PARENT_SCOPE) -endfunction() diff --git a/Dependencies/LFramework.CMake/stm32_gcc.cmake b/Dependencies/LFramework.CMake/stm32_gcc.cmake deleted file mode 100644 index 90cb97c..0000000 --- a/Dependencies/LFramework.CMake/stm32_gcc.cmake +++ /dev/null @@ -1,110 +0,0 @@ -if(NOT DEFINED TOOLCHAIN_DIR) - if(CMAKE_HOST_UNIX) - file(GLOB TOOLCHAIN_DIRS "/usr/local/gcc-arm-none-eabi-*") - else() - file(GLOB TOOLCHAIN_DIRS "C:/Program Files (x86)/GNU Arm Embedded Toolchain/*" "C:/Program Files (x86)/Arm GNU Toolchain arm-none-eabi/*") - endif() - - if(TOOLCHAIN_DIRS) - list(GET TOOLCHAIN_DIRS 0 TOOLCHAIN_DIR) - message("FOUND ARM GCC Toolchain Directory: ${TOOLCHAIN_DIR}") - endif() -endif() - - -GET_FILENAME_COMPONENT(STM32_CMAKE_DIR ${CMAKE_CURRENT_LIST_FILE} DIRECTORY) -list(APPEND CMAKE_MODULE_PATH ${STM32_CMAKE_DIR}) - -set(EXE_SUFFIX "") - -set(CMAKE_LIBRARY_ARCHITECTURE arm-none-eabi) - -set(CMAKE_SYSTEM_NAME Generic) -set(CMAKE_SYSTEM_PROCESSOR arm) -set(CMAKE_SYSTEM_VERSION 1) - - -set(TOOLCHAIN_PREFIX "${CMAKE_LIBRARY_ARCHITECTURE}-") -set(TOOLCHAIN_BIN_PATH "${TOOLCHAIN_DIR}/bin") -set(TOOLCHAIN_INC_PATH "${TOOLCHAIN_DIR}/${CMAKE_LIBRARY_ARCHITECTURE}/include") -set(TOOLCHAIN_LIB_PATH "${TOOLCHAIN_DIR}/${CMAKE_LIBRARY_ARCHITECTURE}/lib") -set(TOOLCHAIN_SYSROOT "${TOOLCHAIN_DIR}/${CMAKE_LIBRARY_ARCHITECTURE}") - - - - -find_program(CMAKE_C_COMPILER NAMES ${TOOLCHAIN_PREFIX}gcc HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_CXX_COMPILER NAMES ${TOOLCHAIN_PREFIX}g++ HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_ASM_COMPILER NAMES ${TOOLCHAIN_PREFIX}gcc HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_CPPFILT NAMES ${TOOLCHAIN_PREFIX}c++filt HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_DEBUGGER NAMES ${TOOLCHAIN_PREFIX}gdb HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_OBJCOPY NAMES ${TOOLCHAIN_PREFIX}objcopy HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_OBJDUMP NAMES ${TOOLCHAIN_PREFIX}objdump HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_SIZE NAMES ${TOOLCHAIN_PREFIX}size HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_AS NAMES ${TOOLCHAIN_PREFIX}as HINTS ${TOOLCHAIN_BIN_PATH}) -find_program(CMAKE_AR NAMES ${TOOLCHAIN_PREFIX}ar HINTS ${TOOLCHAIN_BIN_PATH}) - - -set(CMAKE_EXECUTABLE_SUFFIX_C .elf) -set(CMAKE_EXECUTABLE_SUFFIX_CXX .elf) -set(CMAKE_EXECUTABLE_SUFFIX_ASM .elf) - - - - -set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) - - - -#set(COMMON_FLAGS "-mcpu=${MCU_ARCH} -mthumb -mfloat-abi=${MCU_FLOAT_ABI} -mfpu=${MCU_FPU} -ffunction-sections -fdata-sections -fsigned-char -g -fmessage-length=0 -D__weak=__attribute__((weak)) -D__packed=__attribute__((__packed__))") -# -#set(CMAKE_CXX_FLAGS "${COMMON_FLAGS} -std=c++17 -fno-exceptions -fno-rtti -fno-use-cxa-atexit -fno-threadsafe-statics" CACHE INTERNAL "cxx compiler flags") -#set(CMAKE_C_FLAGS "${COMMON_FLAGS} -std=c11" CACHE INTERNAL "c compiler flags") -# -#set(CMAKE_EXE_LINKER_FLAGS "-Wl,-gc-sections -specs=nosys.specs -specs=nano.specs" CACHE INTERNAL "exe compiler flags") -#SET(CMAKE_ASM_FLAGS "-mthumb -mcpu=${MCU_ARCH} -mfpu=${MCU_FPU} -mfloat-abi=${MCU_FLOAT_ABI} -x assembler-with-cpp" CACHE INTERNAL "asm compiler flags") -# -# -#include(fetch_utils) - - - -if(NOT (TARGET GCC::Specs::NoSys)) - add_library(GCC::Specs::NoSys INTERFACE IMPORTED) - target_link_options(GCC::Specs::NoSys INTERFACE - -specs=nosys.specs - ) -endif() - -if(NOT (TARGET GCC::Specs::Nano)) - add_library(GCC::Specs::Nano INTERFACE IMPORTED) - target_link_options(GCC::Specs::Nano INTERFACE - -specs=nano.specs - ) -endif() - -function(gcc_add_linker_script TARGET VISIBILITY SCRIPT_PATH) - get_filename_component(SCRIPT_PATH "${SCRIPT_PATH}" ABSOLUTE) - target_link_options(${TARGET} ${VISIBILITY} -T "${SCRIPT_PATH}") -endfunction() - -function(gcc_generate_bin_file TargetName) - add_custom_command( - TARGET ${TargetName} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E echo "Generating flash image ${TargetName}.bin" - COMMAND ${CMAKE_OBJCOPY} -O binary ${TargetName}${CMAKE_EXECUTABLE_SUFFIX_C} ${TargetName}.bin - BYPRODUCTS ${TargetName}.bin - ) -endfunction() - - - -function(gcc_print_target_size TargetName) - add_custom_command( - TARGET ${TargetName} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E echo "Invoking: GCC Print Size" - COMMAND ${CMAKE_SIZE} ${TargetName}${CMAKE_EXECUTABLE_SUFFIX_C} - ) -endfunction() diff --git a/Dependencies/LFramework/.gitignore b/Dependencies/LFramework/.gitignore deleted file mode 100644 index 259148f..0000000 --- a/Dependencies/LFramework/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app diff --git a/Dependencies/LFramework/CMakeLists.txt b/Dependencies/LFramework/CMakeLists.txt deleted file mode 100644 index 5622c2b..0000000 --- a/Dependencies/LFramework/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -cmake_minimum_required(VERSION 3.16) - -add_library(LFramework INTERFACE) -target_include_directories(LFramework INTERFACE "Src") -add_subdirectory(Src/LFramework) diff --git a/Dependencies/LFramework/LICENSE b/Dependencies/LFramework/LICENSE deleted file mode 100644 index 0444664..0000000 --- a/Dependencies/LFramework/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Sergey Serb - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Dependencies/LFramework/README.md b/Dependencies/LFramework/README.md deleted file mode 100644 index f67fa31..0000000 --- a/Dependencies/LFramework/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# LFramework -C++ general purpose library for my projects diff --git a/Dependencies/LFramework/Src/LFramework/Assert.h b/Dependencies/LFramework/Src/LFramework/Assert.h deleted file mode 100644 index 706b069..0000000 --- a/Dependencies/LFramework/Src/LFramework/Assert.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include "Debug.h" -#include "IO/Terminal/Terminal.h" - -namespace LFramework::Debug { - class Assert : public LogWriter { - public: - Assert():LogWriter(LogLevel::Fatal){} - ~Assert(){ - for(;;); - } - }; - - -#define lfAssert(expression) \ - do { \ - if(!(expression)) { \ - LFramework::Debug::Assert() \ - << "Assert: " << #expression << LFramework::Terminal::NewLine \ - << "File: " << __FILE__ << LFramework::Terminal::NewLine; \ - } \ - }while(false) - -} - diff --git a/Dependencies/LFramework/Src/LFramework/BitField.h b/Dependencies/LFramework/Src/LFramework/BitField.h deleted file mode 100644 index 713a8c3..0000000 --- a/Dependencies/LFramework/Src/LFramework/BitField.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * BitField.h - * - * Created on: 14 sept. 2017 ã. - * Author: l-pro - */ - -#ifndef LFRAMEWORK_BITFIELD_H_ -#define LFRAMEWORK_BITFIELD_H_ - -#include -#include -#include -#include - -namespace LFramework { - - template - struct BitFieldValueConverter { - static TBase toBase(T value) { - return static_cast(value); - } - static T fromBase(TBase value) { - return static_cast(value); - } - }; - - template> - struct BitFieldMember { - static constexpr size_t FieldBitsCount = BitCount; - static constexpr size_t TBitsCount = std::numeric_limits::digits * sizeof(T); - static_assert(std::numeric_limits::digits == 8, "Only systems with 8 bit chars are supported for now"); - static_assert(std::is_standard_layout_v, "Only standard layout types supported in unions (and so in BitFieldMember) without UB"); - static_assert(BitOffset + BitCount <= TBitsCount, "Base type bits overflow"); - - TBase baseValue; - - static constexpr TBase LowMask = (static_cast((~(TBase{ 0 }))) >> (TBitsCount - BitCount)); - static constexpr TBase HiMask = TBase(LowMask << BitOffset); - - template>> - volatile BitFieldMember& operator =(TR value) volatile { - baseValue = assign(baseValue, Converter::toBase(value)); - return *this; - } - - template - constexpr BitFieldMember& operator =(TR value) { - if constexpr(std::is_same_v){ - baseValue = assign(baseValue, value); - }else{ - baseValue = assign(baseValue, Converter::toBase(value)); - } - return *this; - } - - constexpr operator T() const { - return Converter::fromBase((baseValue >> BitOffset) & LowMask); - } - static constexpr inline TBase assign(TBase left, TBase right) { - return (left & ~(HiMask)) | ((right & LowMask) << BitOffset); - } - }; - - -static_assert(std::is_standard_layout_v>, "Only standard layout types supported in unions (and so in BitFieldMember) without UB"); - -} - -#endif /* LFRAMEWORK_BITFIELD_H_ */ diff --git a/Dependencies/LFramework/Src/LFramework/BitFieldTest.cpp b/Dependencies/LFramework/Src/LFramework/BitFieldTest.cpp deleted file mode 100644 index 73ed81f..0000000 --- a/Dependencies/LFramework/Src/LFramework/BitFieldTest.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - * BitFieldTest.cpp - * - * Created on: 14 ñåíò. 2017 ã. - * Author: l-pro - */ - -#include "UnitTest/UnitTest.h" -#include "BitField.h" - -using namespace LFramework; - -union Test8BitField { - constexpr Test8BitField():value(0){} - uint8_t value; - BitFieldMember bit_0_1; - BitFieldMember bit_1_3; - BitFieldMember bit_4_4; -}; - -TEST(BitField_8bit){ - Test8BitField bitfield; - TEST_TRUE(bitfield.value == 0); - - bitfield.bit_0_1 = 1; - TEST_TRUE(bitfield.value == 1); - TEST_TRUE(bitfield.bit_0_1 == 1); - - bitfield.bit_1_3 = 4; - TEST_TRUE(bitfield.bit_1_3 == 4); - TEST_TRUE(bitfield.value == 9); - bitfield.bit_1_3 = 0; - TEST_TRUE(bitfield.value == 1); - - bitfield.bit_4_4 = 1; - TEST_TRUE(bitfield.value == 17); - - bitfield.bit_4_4 = 15; - TEST_TRUE(bitfield.value == 241); - - bitfield.bit_1_3 = 7; - TEST_TRUE(bitfield.value == 0xff); - - bitfield.bit_0_1 = 0; - TEST_TRUE(bitfield.value == 0xfe); - - bitfield.bit_4_4 = 0; - TEST_TRUE(bitfield.value == 0x0e); - - bitfield.bit_1_3 = 0; - TEST_TRUE(bitfield.value == 0x00); -} - - - diff --git a/Dependencies/LFramework/Src/LFramework/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/CMakeLists.txt deleted file mode 100644 index 07ff55f..0000000 --- a/Dependencies/LFramework/Src/LFramework/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -target_sources(LFramework -INTERFACE - Assert.h - BitField.h - CMakeLists.txt - Debug.h - Guid.h - GuidUtils.h - GuidUtils.cpp - System.h - SystemArmCortexM.h - SystemWindows.h - TupleUtils.h - #BitFieldTest.cpp - Syscalls.cpp - Text/Encoding.h - - TypeTraits/FunctionTraits.h - TypeTraits/Integral.h - - Reflection/Reflection.h -) - -add_subdirectory(USB) -add_subdirectory(UnitTest) -add_subdirectory(Threading) -add_subdirectory(IO) -add_subdirectory(Input) -#add_subdirectory(Time) - -#add_subdirectory(MCU) -#add_subdirectory(Macro) -#add_subdirectory(IO) -#add_subdirectory(Input) -#add_subdirectory(Detect) -#add_subdirectory(Containers) -#add_subdirectory(COM) diff --git a/Dependencies/LFramework/Src/LFramework/COM/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/COM/CMakeLists.txt deleted file mode 100644 index c404fc5..0000000 --- a/Dependencies/LFramework/Src/LFramework/COM/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - ComObject.h -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/COM/ComLibrary.h b/Dependencies/LFramework/Src/LFramework/COM/ComLibrary.h deleted file mode 100644 index 1d620f5..0000000 --- a/Dependencies/LFramework/Src/LFramework/COM/ComLibrary.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "ComObject.h" - -#if defined(__CYGWIN32__) -#define LFRAMEWORK_COM_LIBRARY_CALL __stdcall -#define LFRAMEWORK_COM_LIBRARY_EXPORT __declspec(dllexport) -#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY) -#define LFRAMEWORK_COM_LIBRARY_CALL __stdcall -#define LFRAMEWORK_COM_LIBRARY_EXPORT __declspec(dllexport) -#elif defined(__MACH__) -#define LFRAMEWORK_COM_LIBRARY_CALL -#define LFRAMEWORK_COM_LIBRARY_EXPORT -#elif defined(__linux__) || defined(__ANDROID__) -#define LFRAMEWORK_COM_LIBRARY_CALL -#define LFRAMEWORK_COM_LIBRARY_EXPORT __attribute__ ((visibility ("default"))) -#else -#define LFRAMEWORK_COM_LIBRARY_CALL -#define LFRAMEWORK_COM_LIBRARY_EXPORT -#endif - -namespace LFramework { - -#define LFRAMEWORK_COM_LIBRARY_EXPORT_ENTRY_FUNCTION() \ - extern "C" LFRAMEWORK_COM_LIBRARY_EXPORT void LFRAMEWORK_COM_LIBRARY_CALL getInterface(LFramework::ComPtr& result){ \ - result = LFramework::ComPtr::create(); \ - } - - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/COM/ComObject.h b/Dependencies/LFramework/Src/LFramework/COM/ComObject.h deleted file mode 100644 index 6c8eee9..0000000 --- a/Dependencies/LFramework/Src/LFramework/COM/ComObject.h +++ /dev/null @@ -1,602 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#if (LF_TARGET_OS == LF_OS_WINDOWS) || (LF_TARGET_OS == LF_OS_CYGWIN) -#define LFRAMEWORK_COM_CALL __stdcall -#else -#define LFRAMEWORK_COM_CALL -#endif - -namespace LFramework { - -using InterfaceID = Guid; - -//IUnknown -class IUnknown; - -template -struct InterfaceRemap {}; - -template -struct RemapTraits { - -}; - -template -struct RemapTraits> { - using InterfaceType = TInterface; - using ImplementerType = TImplementer; -}; - -template -struct InterfaceAbi {}; - - - - -template -bool InterfaceAbiInterfaceSupported(const InterfaceID& id) { - if (InterfaceAbi::ID() == id) { - return true; - } - if constexpr (!std::is_same_v) { - return InterfaceAbiInterfaceSupported(id); - } - return false; -}; - -struct RemapChainItemBase { - using InterfaceAbiInterfaceSupportedPtr = bool(*)(const InterfaceID&); - RemapChainItemBase* next = nullptr; - InterfaceAbiInterfaceSupportedPtr isSupported = nullptr; - void* getRemapPtr() { - return reinterpret_cast(&isSupported) + sizeof(isSupported); - } -}; - -template -struct RemapChainItem : RemapChainItemBase { - RemapChainItem(typename RemapTraits::ImplementerType* implementer) { - remap._implementer = implementer; - this->isSupported = &InterfaceAbiInterfaceSupported::InterfaceType>>; - implementer->registerRemap(this); - } - TRemap remap; -}; - -template -struct ComRemapList : ComRemapList { - using Base = ComRemapList; - ComRemapList(Implementer* _this) : Base(_this), remapContainer{ _this } {} - RemapChainItem> remapContainer; -}; - -template -struct ComRemapList { - ComRemapList(Implementer* _this) : remapContainer{ _this } {} - RemapChainItem> remapContainer; -}; - -template -struct IsInterface : std::conditional_t, InterfaceAbi>, std::true_type, std::false_type> {}; - -template -struct IsAllInterfaces : std::conjunction...> {}; - -template -struct ComImplement : public TBase { - using ComImplement_BaseType = TBase; - using ComImplement_SelfType = ComImplement; - using Implementer = TImplementer; - ComRemapList _remaps = { reinterpret_cast(this) }; -}; - - -template -struct IsComImplement : std::false_type {}; - -template -struct IsComImplement> : std::true_type {}; - -template -struct IsAllComImplement : std::conjunction...> {}; - -template -struct HasInterface : std::disjunction, InterfaceAbi>...> {}; - -template -class ComDelegate; - - -template -struct IsComDelegate : std::false_type {}; - -template -struct IsComDelegate> : std::true_type {}; - - -enum class Result : uint32_t { - Ok = 0, - NotImplemented = 0x80004001L, - NoInterface = 0x80004002L, - ErrorPointer = 0x80004003L, - UnknownFailure = 0x80004005L, - OutOfMemory = 0x8007000EL, - InvalidArg = 0x80070057L, - Pending = 0x8000000AL, - AsyncOperationNotStarted = 0x80000019L, - RpcTimeout = 0x8001011FL, - RpcDisconnected = 0x80010108L -}; - -struct ComException : std::exception { - ComException(Result code) : _errorCode(code) { - - } - ComException() : ComException(Result::UnknownFailure) { - - } - ComException(Result code, std::string message) :_errorCode(code), _message(std::move(message)) { - - } - ComException(std::string message) : ComException(Result::UnknownFailure, std::move(message)) { - - } - Result code() const { - return _errorCode; - } - char const* what() const noexcept override { - return _message.c_str(); - } - const std::string& message() const { - return _message; - } -private: - Result _errorCode; - std::string _message; -}; - -template<> -struct InterfaceAbi { -public: - using Base = void; - static constexpr InterfaceID ID() { return { 0x00000000, 0x0000000, 0x000000C0, 0x46000000 }; } - template - friend class ComPtr; - friend class ComObject; - virtual Result LFRAMEWORK_COM_CALL queryInterface(const InterfaceID& riid, void** ppvObject) = 0; - virtual std::uint32_t LFRAMEWORK_COM_CALL addRef() = 0; - virtual std::uint32_t LFRAMEWORK_COM_CALL release() = 0; - ~InterfaceAbi() = delete; -}; - - - -template -static constexpr InterfaceID getInterfaceId() { - return InterfaceAbi::ID(); -} - - -template -struct InterfaceRemap { - virtual Result LFRAMEWORK_COM_CALL queryInterface(const InterfaceID& riid, void** ppvObject) { return _implementer->queryInterface(riid, ppvObject); } - virtual std::uint32_t LFRAMEWORK_COM_CALL addRef() { return _implementer->addRef(); } - virtual std::uint32_t LFRAMEWORK_COM_CALL release() { return _implementer->release(); } - inline auto implementer() { - if constexpr (IsComDelegate::value) { - return _implementer->getImplementer(); - } else { - return _implementer; - } - } - TImplementer* _implementer; - ~InterfaceRemap() = default; -}; - -template -struct IsComImplementSupportsInterface : std::false_type {}; - -template -struct IsComImplementSupportsInterface> : HasInterface {}; - -class RefCountedObject { -public: - virtual ~RefCountedObject() = default; - std::uint32_t addRef() { - return _refCount.fetch_add(1) + 1; - } - std::uint32_t release() { - auto result = _refCount.fetch_sub(1); - if (result == 1) { - delete this; - } - return result - 1; - } -private: - std::atomic _refCount{}; -}; - -template -class ComPtr; - - -class ComObject : public RefCountedObject { -public: - template - friend struct RemapChainItem; - - ComObject() { - _headRemap.next = &_headRemap; - } - - template - ComPtr queryInterface() { - void* result = nullptr; - if(queryInterface(InterfaceAbi::ID(), &result) == Result::Ok){ - auto abiPtr = reinterpret_cast*>(result); - ComPtr result; - result.attach(abiPtr); - return result; - } - return nullptr; - } - - Result queryInterface(const InterfaceID& riid, void** ppvObject) { - if (ppvObject == nullptr) { - return Result::ErrorPointer; - } - - findInterface(riid, ppvObject); - - if (*ppvObject == nullptr) { - return Result::NoInterface; - } else { - auto obj = (reinterpret_cast*>(*ppvObject)); - obj->addRef(); - return Result::Ok; - } - } - -private: - void findInterface(const InterfaceID& id, void** result) { - RemapChainItemBase* current = &_headRemap; - do { - if (current->isSupported(id)) { - *result = current->getRemapPtr(); - return; - } - current = current->next; - } while (current != &_headRemap); - - *result = nullptr; - } - void registerRemap(RemapChainItemBase* remap) { - remap->next = _headRemap.next; - _headRemap.next = remap; - } - - RemapChainItem> _headRemap{ this }; -}; - - -template -constexpr bool IsInterfaceSupported() { - if constexpr(!LFramework::IsInterface::value || !IsComImplement::value){ - return false; - }else{ - if constexpr(std::is_same_v && std::is_same_v){ - return true; - }else{ - if constexpr (LFramework::IsComImplementSupportsInterface::value){ - return true; - }else{ - return IsInterfaceSupported(); - } - } - } -} - - -template -class InterfaceWrapper { -public: - using NotSpecialized = bool; -}; - - - - - - -template -class HasInterfaceWrapper : public std::true_type {}; - -template -class HasInterfaceWrapper::NotSpecialized>> : public std::false_type {}; - -template -class ComPtr { -public: - using InterfacePtr = InterfaceAbi*; - - using PublicInterfacePtr = std::conditional_t::value, InterfaceWrapper*, InterfacePtr>; - - ComPtr() = default; - - ComPtr(InterfacePtr ptr) : _interface(ptr){ - if(_interface != nullptr){ - _interface->addRef(); - } - } - - template, InterfaceAbi>>> - ComPtr(ComPtr ptr) : _interface(ptr.get()) { - _interface->addRef(); - } - - ComPtr(const ComPtr& ptr) : _interface(ptr.get()) { - if(_interface != nullptr){ - _interface->addRef(); - } - } - - template - ComPtr queryInterface(){ - ComPtr result; - if(_interface->queryInterface(InterfaceAbi::ID(), result.put()) == Result::Ok){ - return result; - } - return {}; - } - - ~ComPtr() { - reset(); - } - - PublicInterfacePtr operator ->() { - if constexpr(HasInterfaceWrapper::value){ - return reinterpret_cast(&_interface); - }else{ - return reinterpret_cast(_interface); - } - - } - - template, InterfaceAbi>>> - operator ComPtr(){ - return ComPtr(_interface); - } - - ComPtr operator = (std::nullptr_t) { - reset(); - return *this; - } - - ComPtr operator = (const ComPtr& other) { - reset(); - auto ptr = other._interface; - if (ptr != nullptr) { - ptr->addRef(); - } - _interface = ptr; - return *this; - } - - - bool operator == (const ComPtr& other) const { - return _interface == other._interface; - } - - bool operator != (const ComPtr& other) const { - return _interface != other._interface; - } - bool operator == (std::nullptr_t) const { - return _interface == nullptr; - } - - bool operator != (std::nullptr_t) const { - return _interface != nullptr; - } - - InterfacePtr operator*() { - return _interface; - } - - const InterfacePtr operator*() const { - return _interface; - } - - operator bool() const { - return (_interface != nullptr); - } - - InterfacePtr get() const { - return _interface; - } - - void** put() { - return reinterpret_cast(&_interface); - } - - InterfacePtr detach() { - auto result = _interface; - _interface = nullptr; - return result; - } - - void attach(InterfacePtr ptr) { - reset(); - _interface = ptr; - } - void reset() { - auto ptr = _interface; - if (ptr != nullptr) { - _interface = nullptr; - ptr->release(); - } - } - - template - static ComPtr create(TArgs&& ... args) { - if constexpr(IsInterfaceSupported()){ - auto obj = new TImplementer(std::forward(args)...); - return obj->template queryInterface(); - }else{ - static_assert(IsInterfaceSupported(), "Interface not supported"); - } - } -private: - InterfacePtr _interface = nullptr; -}; - - -template -class ComDelegate : public ComImplement, ComObject, TInterface> { -public: - using DelegatedImplementer = TImplementer; - typedef void (TImplementer::*DelegateDestroyCallback)(); - - ComDelegate(TImplementer* implementer, DelegateDestroyCallback destroyCallback) - : _implementer(implementer), _destroyCallback(destroyCallback) { - if constexpr (std::is_base_of_v) { - _implementer->addRef(); - } - } - ~ComDelegate() { - if (_destroyCallback != nullptr) { - ((_implementer)->*(_destroyCallback))(); - } - if constexpr (std::is_base_of_v) { - _implementer->release(); - } - } - TImplementer* getImplementer() { - return _implementer; - } -private: - DelegateDestroyCallback _destroyCallback; - TImplementer* _implementer; -}; - - -template -ComPtr makeComDelegate(TImplementer* implementer, typename ComDelegate::DelegateDestroyCallback delegateDestroyCallback = nullptr) { - return ComPtr::template create>(implementer, delegateDestroyCallback); -} - - -class ArrayOutMarshaler { -public: - using SizeType = std::uint32_t; - typedef void* ContextPtr; - typedef void* (LFRAMEWORK_COM_CALL *ContainerResizeCallback)(ContextPtr context, SizeType size); - - ContextPtr context; - ContainerResizeCallback callback; - - template - ArrayOutMarshaler(std::vector& buffer) { - context = &buffer; - callback = &ArrayOutMarshaler::resizeCallback; - } - - ArrayOutMarshaler(std::string& buffer) { - context = &buffer; - callback = &ArrayOutMarshaler::resizeCallback; - } - template - void operator = (const std::vector& source) { - void* data = callback(context, static_cast(source.size())); - if (data != nullptr && !source.empty()) { - memcpy(data, source.data(), sizeof(T) * source.size()); - } - } - void operator = (const std::string& source) { - void* data = callback(context, static_cast(source.size())); - if (data != nullptr && !source.empty()) { - memcpy(data, source.data(), source.size()); - } - } -private: - template - static void* LFRAMEWORK_COM_CALL resizeCallback(ContextPtr context, SizeType size) { - auto container = reinterpret_cast*>(context); - container->resize(size); - return size == 0 ? nullptr : container->data(); - } - static void* LFRAMEWORK_COM_CALL resizeCallback(ContextPtr context, SizeType size) { - auto container = reinterpret_cast(context); - container->resize(size); - return size == 0 ? nullptr : container->data(); - } - ArrayOutMarshaler() = delete; -}; - -class ArrayInMarshaler { -public: - using SizeType = std::uint32_t; - const void* data; - SizeType itemsCount; - - ArrayInMarshaler(const std::string& source) { - data = source.data(); - itemsCount = static_cast(source.size()); - } - template - ArrayInMarshaler(const std::vector& source) { - data = source.data(); - itemsCount = static_cast(source.size()); - } - operator std::string() const { - return std::string(reinterpret_cast(data), itemsCount); - } - template - operator std::vector() const { - std::vector result; - if (itemsCount != 0) { - result.resize(itemsCount); - memcpy(result.data(), data, sizeof(T) * itemsCount); - } - return result; - } -private: - ArrayInMarshaler() = delete; -}; - - -template<> -class InterfaceWrapper { -public: - template, InterfaceAbi>::value>::type> - ComPtr queryInterface() { - if (_abi == nullptr) { - return {}; - } - ComPtr result{}; - reinterpret_cast*>(_abi)->queryInterface(InterfaceAbi::ID(), reinterpret_cast(&result)); - return result; - } - - uint32_t addRef() { - return reinterpret_cast*>(_abi)->addRef(); - } - uint32_t release() { - return reinterpret_cast*>(_abi)->release(); - } -protected: - void* _abi = nullptr; -}; - - -} diff --git a/Dependencies/LFramework/Src/LFramework/Containers/ByteFifo.h b/Dependencies/LFramework/Src/LFramework/Containers/ByteFifo.h deleted file mode 100644 index cae523c..0000000 --- a/Dependencies/LFramework/Src/LFramework/Containers/ByteFifo.h +++ /dev/null @@ -1,118 +0,0 @@ -#pragma once - -#include -#include -#include - -template -class ByteFifo { -public: - static constexpr std::size_t Capacity = _Capacity; - - bool write(const void* data, std::size_t size){ - std::size_t availableSize = getAvailableSize(); - if(availableSize >= size){ - auto writeOffset = (_begin + _size) % Capacity; - auto distanceToEnd = Capacity - writeOffset; - if(distanceToEnd >= size){ - memcpy(_buffer.data() + writeOffset, data, size); - }else{ - memcpy(_buffer.data() + writeOffset, data, distanceToEnd); - memcpy(_buffer.data(), reinterpret_cast(data) + distanceToEnd, size - distanceToEnd); - } - _size += size; - if(_size >= 100000){ - for(;;); - } - return true; - } - return false; - } - - bool write(std::uint8_t value){ - return write(&value, 1); - } - - bool read(void* data, std::uint8_t size) { - if(_size >= 100000){ - for(;;); - } - if(_size < size){ - return false; - } - - auto distanceToEnd = Capacity - _begin; - - if(distanceToEnd >= size){ - memcpy(data, _buffer.data() + _begin, size); - _begin = (_begin + size) % Capacity; - }else{ - memcpy(data, _buffer.data() + _begin, distanceToEnd); - memcpy(reinterpret_cast(data) + distanceToEnd, _buffer.data(), size - distanceToEnd); - _begin = size - distanceToEnd; - } - if(_size >= 100000){ - for(;;); - } - _size -= size; - if(_size >= 100000){ - for(;;); - } - return true; - } - - std::size_t discard(std::size_t count){ - if(count > _size){ - count = _size; - } - - _begin = (_begin + count) % Capacity; - _size -= count; - if(_size >= 100000){ - for(;;); - } - return count; - } - - bool peek(void* data, std::size_t size) { - if(_size < size){ - return false; - } - - auto distanceToEnd = Capacity - _begin; - - if(distanceToEnd >= size){ - memcpy(data, _buffer.data() + _begin, size); - }else{ - memcpy(data, _buffer.data() + _begin, distanceToEnd); - memcpy(reinterpret_cast(data) + distanceToEnd, _buffer.data(), size - distanceToEnd); - } - return true; - } - - - bool read(std::uint8_t* value) { - return read(value, 1); - } - - std::size_t size() const { - return _size; - } - std::size_t sizeAvailable() const { - return Capacity - _size; - } - bool empty() const { - return _size == 0; - } - void clear() { - _begin = 0; - _size = 0; - } -private: - std::size_t getAvailableSize() const { - return Capacity - _size; - } - std::size_t _size = 0; - std::size_t _begin = 0; - std::array _buffer; -}; diff --git a/Dependencies/LFramework/Src/LFramework/Containers/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/Containers/CMakeLists.txt deleted file mode 100644 index e3594e6..0000000 --- a/Dependencies/LFramework/Src/LFramework/Containers/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - ByteFifo.h - LinkedList.h - StaticVector.h -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/Containers/LinkedList.h b/Dependencies/LFramework/Src/LFramework/Containers/LinkedList.h deleted file mode 100644 index f1df375..0000000 --- a/Dependencies/LFramework/Src/LFramework/Containers/LinkedList.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once - -#include -#include - -class LinkedList; - -class LinkedListItem { -public: - LinkedListItem* next = nullptr; - LinkedListItem* previous = nullptr; - LinkedList* owner = nullptr; -}; - - -class LinkedList { -public: - - LinkedList():_size(0){ - _head.next = &_head; - _head.previous = &_head; - _head.owner = this; - } - - bool pushFront(LinkedListItem* newItem){ - if (newItem->owner == nullptr) { - newItem->owner = this; - newItem->next = _head.next; - newItem->previous = &_head; - _head.next->previous = newItem; - _head.next = newItem; - ++_size; - return true; - } - return false; - } - - bool pushBack(LinkedListItem* newItem) { - if (newItem->owner == nullptr) { - newItem->owner = _head.owner; - newItem->previous = _head.previous; - newItem->next = &_head; - _head.previous->next = newItem; - _head.previous = newItem; - ++_size; - return true; - } - return false; - } - - size_t size() const { - return _size; - } - - void remove(LinkedListItem* item) { - if (item->owner == this) { - item->next->previous = item->previous; - item->previous->next = item->next; - --_size; - item->next = nullptr; - item->previous = nullptr; - item->owner = nullptr; - } - } - - template - void foreach(T functor) { - auto current = _head.next; - while (current != &_head) { - functor(current); - current = current->next; - } - } -private: - size_t _size; - LinkedListItem _head; -}; - diff --git a/Dependencies/LFramework/Src/LFramework/Containers/StaticVector.h b/Dependencies/LFramework/Src/LFramework/Containers/StaticVector.h deleted file mode 100644 index 0e60f75..0000000 --- a/Dependencies/LFramework/Src/LFramework/Containers/StaticVector.h +++ /dev/null @@ -1,172 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace LFramework { - -template -class StaticVector { -public: - typedef ValueType& ValueReference; - typedef const ValueReference& ConstValueReference; - - StaticVector() = default; - - ~StaticVector() { - clear(); - } - - constexpr std::size_t capacity() const { - return Capacity; - } - - std::size_t size() const { - return _size; - } - - bool empty() const { - return _size == 0; - } - - bool full() const { - return _size == Capacity; - } - - void clear() { - for(auto it = begin(); it != end(); ++it) { - it->~value_type(); - } - _size = 0; - } - - ValueType* begin() { - return reinterpret_cast(&_buffer[0]); - } - - const ValueType* begin() const { - return reinterpret_cast(&_buffer[0]); - } - - ValueType* end() { - return reinterpret_cast(&_buffer[_size]); - } - - const ValueType* end() const { - return reinterpret_cast(&_buffer[_size]); - } - - ValueReference back() { - return *reinterpret_cast(&_buffer[_size - 1]); - } - - ConstValueReference back() const { - return *reinterpret_cast(&_buffer[_size - 1]); - } - - template - bool emplace_back(Args&&... args) { - if(!full()) { - ::new(&_buffer[_size++]) ValueType(std::forward(args)...); - return true; - } - return false; - } - - bool push_back(ConstValueReference value) { - if (!full()) { - ::new((void*)&_buffer[_size++]) ValueType(value); - return true; - } - return false; - } - - void erase(const std::size_t first, const std::size_t count) { - std::size_t last = first + count; - if ((last <= first) || (last > _size)) { - return; - } - - //move items - auto writePtr = reinterpret_cast(&_buffer[first]); - for(std::size_t i = last; i < _size; ++i){ - *writePtr = std::move(*reinterpret_cast(&_buffer[i])); - ++writePtr; - } - - //destroy tail - for(std::size_t i = first; i < last; ++i){ - writePtr->~value_type(); - ++writePtr; - } - - _size -= (last - first); - } - - void erase(const ValueType& value) { - for (std::size_t i = 0; i < _size; ++i) { - if (_buffer[i] == value) { - erase(i, 1); - return; - } - } - } - - void erase(const ValueType* itemPtr) { - if(itemPtr < begin()){ - return; - } - std::size_t id = itemPtr - begin(); - erase(id, 1); - } - - void pop_back() { - if (!empty()) { - reinterpret_cast(&_buffer[--_size])->~value_type(); - } - } - - ValueReference operator[](std::size_t i) { - return *reinterpret_cast(&_buffer[i]); - } - - ConstValueReference operator[](std::size_t i) const { - return *reinterpret_cast(&_buffer[i]); - } - - bool contains(ConstValueReference value) { - for (std::size_t i = 0; i < _size; ++i) { - if (_buffer[i] == value) { - return true; - } - } - return false; - } - - std::size_t resize(std::size_t newSize) { - if (newSize > Capacity) { - newSize = Capacity; - } - - for(std::size_t i = _size; i < newSize; ++i){ - ::new(reinterpret_cast(&_buffer[i])) ValueType; - } - - for(std::size_t i = newSize; i < _size; ++i){ - reinterpret_cast(&_buffer[i])->~value_type(); - } - - _size = newSize; - return newSize; - } - -private: - typename std::aligned_storage::type _buffer[Capacity]; - std::size_t _size = 0; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/Debug.h b/Dependencies/LFramework/Src/LFramework/Debug.h deleted file mode 100644 index 73a8749..0000000 --- a/Dependencies/LFramework/Src/LFramework/Debug.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include "IO/Terminal/Terminal.h" - -namespace LFramework::Debug { - - enum class LogLevel { - Debug, - Info, - Warning, - Critical, - Fatal - }; - - inline const char* toString(LogLevel category) { - switch (category) { - case LogLevel::Debug: - return "Debug"; - case LogLevel::Info: - return "Info"; - case LogLevel::Warning: - return "Warning"; - case LogLevel::Critical: - return "Critical"; - case LogLevel::Fatal: - return "Fatal"; - } - return ""; - } - - class LogWriter { - public: - LogWriter(LogLevel level){ - - } - template - LogWriter& operator << (const T& value) { - Terminal::out << value; - return *this; - } - - ~LogWriter() { - Terminal::out << Terminal::NewLine; - } - }; - - inline LogWriter Log() { return LogWriter(LogLevel::Debug); } - inline LogWriter Info() { return LogWriter(LogLevel::Info); } - inline LogWriter Warning() { return LogWriter(LogLevel::Warning); } - inline LogWriter Critical() { return LogWriter(LogLevel::Critical); } - inline LogWriter Fatal() { return LogWriter(LogLevel::Fatal); } - - - #define lfDebug() LFramework::Debug::Log() - #define lfInfo() LFramework::Debug::Info() - #define lfWarning() LFramework::Debug::Warning() - #define lfCritical() LFramework::Debug::Critical() - #define lfFatal() LFramework::Debug::Fatal() - -} diff --git a/Dependencies/LFramework/Src/LFramework/Detect/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/Detect/CMakeLists.txt deleted file mode 100644 index 922aae2..0000000 --- a/Dependencies/LFramework/Src/LFramework/Detect/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - DetectCPU.h - DetectEndianness.h - DetectOS.h -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/Detect/DetectCPU.h b/Dependencies/LFramework/Src/LFramework/Detect/DetectCPU.h deleted file mode 100644 index d583931..0000000 --- a/Dependencies/LFramework/Src/LFramework/Detect/DetectCPU.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef DetectCPU_h__ -#define DetectCPU_h__ - -#define LF_CPU_ARCH_ALPHA 0 -#define LF_CPU_ARCH_AMD64 1 -#define LF_CPU_ARCH_ARM 2 -#define LF_CPU_ARCH_ARM64 3 -#define LF_CPU_ARCH_BLACKFIN 4 -#define LF_CPU_ARCH_CONVEX 5 -#define LF_CPU_ARCH_IX86 6 -#define LF_CPU_ARCH_IA64 7 -#define LF_CPU_ARCH_MOTOROLA68K 8 -#define LF_CPU_ARCH_MIPS 9 -#define LF_CPU_ARCH_POWERPC 10 -#define LF_CPU_ARCH_SPARC 11 - - -#ifndef LF_CPU_ARCH - -#if defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) - #define LF_CPU_ARCH LF_CPU_ARCH_ALPHA -#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) - #define LF_CPU_ARCH LF_CPU_ARCH_AMD64 -#elif defined(__arm__) || defined(__thumb__) || defined(__TARGET_ARCH_ARM) || defined(__TARGET_ARCH_THUMB) || defined(_ARM) || defined(_M_ARM)|| defined(_M_ARMT) || defined(__arm) - #define LF_CPU_ARCH LF_CPU_ARCH_ARM -#elif defined(__aarch64__) - #define LF_CPU_ARCH LF_CPU_ARCH_ARM64 -#elif defined(__bfin) || defined(__BFIN__) - #define LF_CPU_ARCH LF_CPU_ARCH_BLACKFIN -#elif defined(__convex__) - #define LF_CPU_ARCH LF_CPU_ARCH_CONVEX - -#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(__IA32__) \ -|| defined(_M_I86) || defined(_M_IX86) || defined(__X86__) || defined(_X86_) \ -|| defined(__THW_INTEL__) || defined(__I86__) || defined(__INTEL__) || defined(__386) - #define LF_CPU_ARCH LF_CPU_ARCH_IX86 - -#elif defined(__ia64__) || defined(_IA64) || defined(__IA64__) || defined(__ia64) \ -|| defined(_M_IA64) || defined(_M_IA64) || defined(__itanium__) - #define LF_CPU_ARCH LF_CPU_ARCH_IA64 - -#elif defined(__m68k__) || defined(M68000) || defined(__MC68K__) - #define LF_CPU_ARCH LF_CPU_ARCH_MOTOROLA68K - -#elif defined(__mips__) || defined(mips) || defined(__mips) || defined(__MIPS__) - #define LF_CPU_ARCH LF_CPU_ARCH_MIPS - -#elif defined(__powerpc) || defined(__powerpc__) || defined(__powerpc64__) || defined(__POWERPC__) \ -|| defined(__ppc__) || defined(__ppc64__) || defined(__PPC__) || defined(__PPC64__) \ -|| defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_M_PPC) || defined(__ppc) - #define LF_CPU_ARCH LF_CPU_ARCH_POWERPC - -#elif defined(__sparc__) || defined(__sparc) - #define LF_CPU_ARCH LF_CPU_ARCH_MIPS - -#else -#error "Unknown CPU arch" -#endif - -#endif - - -namespace LFramework { - - enum class CpuArchitecture { - Alpha = LF_CPU_ARCH_ALPHA, - AMD64 = LF_CPU_ARCH_AMD64, - ARM = LF_CPU_ARCH_ARM, - ARM64 = LF_CPU_ARCH_ARM64, - Blackfin = LF_CPU_ARCH_BLACKFIN, - Convex = LF_CPU_ARCH_CONVEX, - IX86 = LF_CPU_ARCH_IX86, - IA64 = LF_CPU_ARCH_IA64, - Motorola68K = LF_CPU_ARCH_MOTOROLA68K, - MIPS = LF_CPU_ARCH_MIPS, - PowerPC = LF_CPU_ARCH_POWERPC, - SPARC = LF_CPU_ARCH_SPARC - }; - - namespace Detect { - static constexpr CpuArchitecture cpuArchitecture() { - return static_cast(LF_CPU_ARCH); - } - } -} - -#endif // DetectCPU_h__ diff --git a/Dependencies/LFramework/Src/LFramework/Detect/DetectEndianness.h b/Dependencies/LFramework/Src/LFramework/Detect/DetectEndianness.h deleted file mode 100644 index 4f07247..0000000 --- a/Dependencies/LFramework/Src/LFramework/Detect/DetectEndianness.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef DetectEndianness_h__ -#define DetectEndianness_h__ - -#define LF_ENDIANNESS_UNKNOWN 0 -#define LF_ENDIANNESS_LITTLE 1 -#define LF_ENDIANNESS_BIG 2 - -#ifndef LF_ENDIANNESS - -#if defined(__BIG_ENDIAN__) || defined(__ARMEB__) || defined(__THUMBEB__) \ -|| defined(__AARCH64EB__) || defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) \ -|| (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) \ -|| (defined(__FLOAT_WORD_ORDER__) && (__FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__)) -#define LF_ENDIANNESS LF_ENDIANNESS_BIG - -#elif defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || defined(__THUMBEL__) \ -|| defined(__AARCH64EL__) || defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) \ -|| (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) \ -|| (defined(__FLOAT_WORD_ORDER__) && (__FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__)) -#define LF_ENDIANNESS LF_ENDIANNESS_LITTLE - -#else -#define LF_ENDIANNESS LF_ENDIANNESS_UNKNOWN -#endif - -#endif - -namespace LFramework { - - enum class Endianness { - Unknown = LF_ENDIANNESS_UNKNOWN, - Little = LF_ENDIANNESS_LITTLE, - Big = LF_ENDIANNESS_BIG - }; - - namespace Detect { - - static constexpr Endianness endianness() { - return static_cast(LF_ENDIANNESS); - } - - static Endianness endiannessRuntime() { - union { - uint32_t value; - uint8_t data[sizeof(uint32_t)]; - } number; - - number.data[0] = 0x00; - number.data[1] = 0x01; - number.data[2] = 0x02; - number.data[3] = 0x03; - - switch (number.value){ - case 0x00010203U: return Endianness::Big; - case 0x03020100U: return Endianness::Little; - default: return Endianness::Unknown; - } - } - } -} - - -#endif // DetectEndianness_h__ diff --git a/Dependencies/LFramework/Src/LFramework/Detect/DetectOS.h b/Dependencies/LFramework/Src/LFramework/Detect/DetectOS.h deleted file mode 100644 index edf277b..0000000 --- a/Dependencies/LFramework/Src/LFramework/Detect/DetectOS.h +++ /dev/null @@ -1,121 +0,0 @@ -#pragma once - -//OS Types -#define LF_OS_NONE 0 -#define LF_OS_WINDOWS 1 -#define LF_OS_LINUX 2 -#define LF_OS_ANDROID 3 -#define LF_OS_FREERTOS 4 - -//BSD family -#define LF_OS_BSD_DRAGONFLY 5 -#define LF_OS_BSD_FREE 6 -#define LF_OS_BSD_NET 7 -#define LF_OS_BSD_OPEN 8 -#define LF_OS_BSD_BSDI 9 - -//Apple -#define LF_OS_IPHONE 10 -#define LF_OS_MAC 11 - -#define LF_OS_CYGWIN 12 -#define LF_OS_LYNX 13 -#define LF_OS_MSDOS 14 -#define LF_OS_NUCLEUS_RTOS 15 -#define LF_OS_OS2 16 -#define LF_OS_PALMOS 17 -#define LF_OS_SOLARIS 18 - - -//OS Detect -#if !defined(LF_TARGET_OS) -#if defined(_WIN32) || defined(_WIN16) || defined(_WIN64) || defined(__WIN32__) || defined(__TOS_WIN__) || defined(__WINDOWS__) - #define LF_TARGET_OS LF_OS_WINDOWS -#elif defined(__linux__) - #define LF_TARGET_OS LF_OS_LINUX -#elif defined(__ANDROID__) - #define LF_TARGET_OS LF_OS_ANDROID - -//Detect BDS -#elif defined(__DragonFly__) - #define LF_TARGET_OS LF_OS_BSD_DRAGONFLY -#elif defined(__FreeBSD__) - #define LF_TARGET_OS LF_OS_BSD_FREE -#elif defined(__NetBSD__) - #define LF_TARGET_OS LF_OS_BSD_NET -#elif defined(__OpenBSD__) - #define LF_TARGET_OS LF_OS_BSD_OPEN -#elif defined(__bsdi__) - #define LF_TARGET_OS LF_OS_BSD_BSDI - -//Detect Apple -#elif defined(__APPLE__) && defined(__MACH__) - #include - #if (TARGET_IPHONE_SIMULATOR == 1) || (TARGET_OS_IPHONE == 1) - #define LF_TARGET_OS LF_OS_IPHONE - #elif TARGET_OS_MAC == 1 - #define LF_TARGET_OS LF_OS_MAC - #else - #error "Unknown Apple OS" - #endif - -#elif defined(__CYGWIN__) -#define LF_TARGET_OS LF_OS_CYGWIN -#elif defined(__Lynx__) -#define LF_TARGET_OS LF_OS_LYNX - - -//detect MS-DOS -#elif defined(MSDOS) || defined(__MSDOS__) || defined(_MSDOS) || defined(__DOS__) - #define LF_TARGET_OS LF_OS_MSDOS - -#elif defined(__nucleus__) -#define LF_TARGET_OS LF_OS_NUCLEUS_RTOS - -#elif defined(OS2) || defined(_OS2) || defined(__OS2__) || defined(__TOS_OS2__) -#define LF_TARGET_OS LF_OS_OS2 - -#elif defined(__palmos__) -#define LF_TARGET_OS LF_OS_PALMOS - -#elif defined(sun) || defined(__sun) -#define LF_TARGET_OS LF_OS_SOLARIS - -#else - #error "OS auto detect fail!" -#endif -#endif - -namespace LFramework { - - enum class OSType { - None = LF_OS_NONE, - Windows = LF_OS_WINDOWS, - Linux = LF_OS_LINUX, - Android = LF_OS_ANDROID, - FreeRTOS = LF_OS_FREERTOS, - - BSDDragonfly = LF_OS_BSD_DRAGONFLY, - BSDFree = LF_OS_BSD_FREE, - BSDNet = LF_OS_BSD_NET, - BSDOpen = LF_OS_BSD_OPEN, - BSDI = LF_OS_BSD_BSDI, - - AppleIPhone = LF_OS_IPHONE, - AppleMacOSX = LF_OS_MAC, - - Cygwin = LF_OS_CYGWIN, - Lynx = LF_OS_LYNX, - MSDOS = LF_OS_MSDOS, - NucleusRTOS = LF_OS_NUCLEUS_RTOS, - OS2 = LF_OS_OS2, - PlamOS = LF_OS_PALMOS, - Solaris = LF_OS_SOLARIS - }; - - namespace Detect { - static constexpr inline OSType operatingSystem() { - return static_cast(LF_TARGET_OS); - } - } -} diff --git a/Dependencies/LFramework/Src/LFramework/Guid.h b/Dependencies/LFramework/Src/LFramework/Guid.h deleted file mode 100644 index 782ae2e..0000000 --- a/Dependencies/LFramework/Src/LFramework/Guid.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -#include - - -namespace LFramework { - -struct Guid { - std::uint32_t data1; - std::uint32_t data2_3; - std::uint32_t data4_0; - std::uint32_t data4_1; - - //std::uint16_t data2; - //std::uint16_t data3; - //std::uint8_t data4[8]; - - Guid() = default; - - constexpr Guid(std::uint32_t data1, std::uint32_t data2_3, std::uint32_t data4_0, std::uint32_t data4_1) : data1(data1), data2_3(data2_3), data4_0(data4_0), data4_1(data4_1) {} - - constexpr bool operator ==(const Guid& rhs) const { - return - (data1 == rhs.data1) && - (data2_3 == rhs.data2_3) && - (data4_0 == rhs.data4_0) && - (data4_1 == rhs.data4_1); - } - - constexpr bool operator !=(const Guid& rhs) const { - return !(this->operator ==(rhs)); - } - - bool isZero() const { - return (data1 == 0) && (data2_3 == 0) && (data4_0 == 0) && (data4_1 == 0); - } - - Guid& operator =(const Guid& right) { - data1 = right.data1; - data2_3 = right.data2_3; - data4_0 = right.data4_0; - data4_1 = right.data4_1; - return *this; - } -}; - -} - diff --git a/Dependencies/LFramework/Src/LFramework/GuidUtils.cpp b/Dependencies/LFramework/Src/LFramework/GuidUtils.cpp deleted file mode 100644 index 4264961..0000000 --- a/Dependencies/LFramework/Src/LFramework/GuidUtils.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#ifdef WIN32 -#include -#include -#include -#include - -namespace LFramework::GuidUtils { - LFramework::Guid newGuid() { - LFramework::Guid result; - if (CoCreateGuid((GUID*)&result) != S_OK) { - throw std::runtime_error("Failed to create GUID"); - } - - return result; - } - - LFramework::Guid fromString(const char* str) { - LFramework::Guid iid; - if (IIDFromString(LFramework::Text::Encoding::u8StringToWString(str).c_str(), (GUID*)&iid) != S_OK) { - throw std::runtime_error("Failed to parse GUID"); - } - return iid; - } - - std::string toString(const LFramework::Guid& guid) { - LPOLESTR guid_str = nullptr; - if (StringFromIID(*((const GUID*)&guid), &guid_str) != S_OK) { - throw std::runtime_error("Failed to convert GUID to string"); - } - std::wstring result(guid_str); - CoTaskMemFree(guid_str); - return LFramework::Text::Encoding::wStringToU8String(result); - } -} - -#endif \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/GuidUtils.h b/Dependencies/LFramework/Src/LFramework/GuidUtils.h deleted file mode 100644 index bf15edb..0000000 --- a/Dependencies/LFramework/Src/LFramework/GuidUtils.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include -#include - -namespace LFramework::GuidUtils { - LFramework::Guid newGuid(); - LFramework::Guid fromString(const char* str); - std::string toString(const LFramework::Guid& guid); -} diff --git a/Dependencies/LFramework/Src/LFramework/IO/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/IO/CMakeLists.txt deleted file mode 100644 index c0e6848..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -add_library(LFrameworkIo INTERFACE ) -add_library(LFramework::IO ALIAS LFrameworkIo ) - - -target_sources(LFrameworkIo -INTERFACE - Stream.h - StreamWriter.h - - StreamWriter.cpp -) -add_subdirectory(Terminal) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/IO/Stream.h b/Dependencies/LFramework/Src/LFramework/IO/Stream.h deleted file mode 100644 index b45b991..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Stream.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include -#include - -namespace LFramework { - - -template -class OutputStream { -public: - -}; - -enum class AdjustField { - Left, - Right, - Internal -}; - -template -class OutputStreamFormat { -public: - size_t fillWidth = 0; - TChar fillChar{}; - AdjustField adjust = AdjustField::Right; -}; - -template<> -class OutputStream { -public: - OutputStreamFormat format; - - virtual ~OutputStream() = default; - virtual int write(const char* data, int length) = 0; - -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/IO/StreamWriter.cpp b/Dependencies/LFramework/Src/LFramework/IO/StreamWriter.cpp deleted file mode 100644 index 5fb8764..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/StreamWriter.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "StreamWriter.h" - -namespace LFramework { - -OutputStream& operator <<(OutputStream& stream, const char* value){ - auto len = strlen(value); - OutputStreamFormatter::fieldBegin(stream, len); - stream.write(value, static_cast(len)); - OutputStreamFormatter::fieldEnd(stream, len); - return stream; -} - -OutputStream& operator <<(OutputStream& stream, char value){ - OutputStreamFormatter::fieldBegin(stream, 1); - stream.write(&value, 1); - OutputStreamFormatter::fieldEnd(stream, 1); - return stream; -} - -OutputStream& operator <<(OutputStream& stream, bool value){ - return stream << (value ? "true" : "false"); -} - - -} diff --git a/Dependencies/LFramework/Src/LFramework/IO/StreamWriter.h b/Dependencies/LFramework/Src/LFramework/IO/StreamWriter.h deleted file mode 100644 index 528e67f..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/StreamWriter.h +++ /dev/null @@ -1,178 +0,0 @@ -#pragma once - -#include "Stream.h" - -#include "../TypeTraits/Integral.h" - -namespace LFramework { - - -template>> -struct DecimalFormat { - DecimalFormat(T value) :value(value) {} - T value; -}; - - - -template>> -struct HexFormat { - HexFormat(T value) :value(value) {} - T value; -}; - -template -HexFormat hex(T value) { - return HexFormat(value); -} - - -class OutputStreamFormatter { -public: - - static void writeFiller(OutputStream& stream, size_t itemSize){ - auto fillSize = stream.format.fillWidth - itemSize; - for(size_t i = 0; i < fillSize; ++i){ - stream.write(&stream.format.fillChar, 1); - } - stream.format.fillWidth = 0; - } - - static void fieldBegin(OutputStream& stream, size_t itemSize){ - - if(stream.format.adjust == AdjustField::Right || stream.format.adjust == AdjustField::Internal){ - if(itemSize < stream.format.fillWidth){ - writeFiller(stream, itemSize); - } - stream.format.fillWidth = 0; - } - } - static void fieldEnd(OutputStream& stream, size_t itemSize){ - if(stream.format.adjust == AdjustField::Left){ - if(itemSize < stream.format.fillWidth){ - writeFiller(stream, itemSize); - } - stream.format.fillWidth = 0; - } - } -}; - -template -size_t outputStreamWriteInteger (OutputStream& stream, DecimalFormat formatter){ - auto v = formatter.value; - - static constexpr size_t BufferSize = TypeTraits::Integral::maxDigitsCount() + (::std::is_signed_v ? 1 : 0); //Add space for sign - char result[BufferSize]; - - size_t writePos = BufferSize - 1; - - if constexpr(::std::is_signed_v) { - //print negative numbers - if (v < 0) { - do { - auto next = v / 10; - result[writePos--] = static_cast('0' - (v - (next * 10))); - v = next; - } while (v != 0); - result[writePos] = '-'; - - auto fieldSize = BufferSize - writePos; - - if(fieldSize < stream.format.fillWidth){ - - if(stream.format.adjust == AdjustField::Internal){ - stream.write(&result[writePos], 1); - OutputStreamFormatter::writeFiller(stream, fieldSize); - stream.write(&result[writePos + 1], fieldSize - 1); - }else { - OutputStreamFormatter::fieldBegin(stream, fieldSize); - stream.write(&result[writePos], fieldSize); - OutputStreamFormatter::fieldEnd(stream, fieldSize); - } - - }else{ - stream.write(&result[writePos], fieldSize); - } - - return fieldSize; - } - } - - //print positive numbers - do { - result[writePos--] = static_cast('0' + (v % 10)); - v /= 10; - } while (v != 0); - - auto fieldSize = BufferSize - writePos - 1; - - OutputStreamFormatter::fieldBegin(stream, fieldSize); - stream.write(&result[writePos + 1], fieldSize); - OutputStreamFormatter::fieldEnd(stream, fieldSize); - - return fieldSize; -} - - - -template -OutputStream& operator <<(OutputStream& stream, const HexFormat& formatter){ - auto v = static_cast::type>(formatter.value); - - const auto bufferSize = sizeof(T) * 2; - char buffer[bufferSize]; - size_t end = bufferSize; - - char a = 'a'; - if constexpr(UpperCase) { - a = 'A'; - } - - for(size_t i = 0; i < bufferSize; ++i) { - auto digit = v & 0xf; - if (digit < 10) { - buffer[end - 1] = static_cast('0' + digit); - } - else { - buffer[end - 1] = static_cast(a + (digit - 10)); - } - v >>= 4; - --end; - if(v == 0 && (i + 1) >= MinWidth) { - break; - } - } - - const auto dataSize = bufferSize - end; - - OutputStreamFormatter::fieldBegin(stream, dataSize); - stream.write(&buffer[end], dataSize); - OutputStreamFormatter::fieldEnd(stream, dataSize); - - return stream; -} - - - -OutputStream& operator <<(OutputStream& stream, const char* value); -OutputStream& operator <<(OutputStream& stream, char value); -OutputStream& operator <<(OutputStream& stream, bool value); - -template -OutputStream& operator <<(OutputStream& stream, DecimalFormat formatter){ - outputStreamWriteInteger(stream, formatter); - return stream; -} - - -template && - std::is_arithmetic_v && - !std::is_same_v && - !std::is_same_v ->> -OutputStream& operator <<(OutputStream& stream, T value){ - return stream << DecimalFormat(value); -} - -} diff --git a/Dependencies/LFramework/Src/LFramework/IO/Terminal/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/IO/Terminal/CMakeLists.txt deleted file mode 100644 index 56af2e3..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Terminal/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -add_library(LFrameworkIoTerminal INTERFACE ) -add_library(LFramework::IO::Terminal ALIAS LFrameworkIoTerminal ) - -target_sources(LFrameworkIoTerminal -INTERFACE - Terminal.h - TerminalAnsi.h - TerminalStream.h - - Terminal.cpp - TerminalStreamCout.cpp - TerminalStreamUartStm32.cpp -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/IO/Terminal/Terminal.cpp b/Dependencies/LFramework/Src/LFramework/IO/Terminal/Terminal.cpp deleted file mode 100644 index 8e9ea69..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Terminal/Terminal.cpp +++ /dev/null @@ -1,5 +0,0 @@ -#include "Terminal.h" - -namespace LFramework::Terminal { - Stream out; -} diff --git a/Dependencies/LFramework/Src/LFramework/IO/Terminal/Terminal.h b/Dependencies/LFramework/Src/LFramework/IO/Terminal/Terminal.h deleted file mode 100644 index ecba77f..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Terminal/Terminal.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include "TerminalStream.h" - -namespace LFramework::Terminal { - static const char* NewLine = "\r\n"; - extern Stream out; -} diff --git a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalAnsi.h b/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalAnsi.h deleted file mode 100644 index 0946de1..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalAnsi.h +++ /dev/null @@ -1,142 +0,0 @@ -#pragma once - -#include - -#define LF_TERMINAL_ANSI_ESC "\033" - -#define LF_TERMINAL_ANSI_SS2 LF_TERMINAL_ANSI_ESC"N" -#define LF_TERMINAL_ANSI_SS3 LF_TERMINAL_ANSI_ESC"O" -#define LF_TERMINAL_ANSI_DCS LF_TERMINAL_ANSI_ESC"P" -#define LF_TERMINAL_ANSI_CSI LF_TERMINAL_ANSI_ESC"[" -#define LF_TERMINAL_ANSI_ST LF_TERMINAL_ANSI_ESC"\\" -#define LF_TERMINAL_ANSI_OSC LF_TERMINAL_ANSI_ESC"]" -#define LF_TERMINAL_ANSI_SOS LF_TERMINAL_ANSI_ESC"X" -#define LF_TERMINAL_ANSI_PM LF_TERMINAL_ANSI_ESC"^" -#define LF_TERMINAL_ANSI_APC LF_TERMINAL_ANSI_ESC"_" -#define LF_TERMINAL_ANSI_RIS LF_TERMINAL_ANSI_ESC"c" - -#if defined(LF__TERMINAL_ANSI_CODES_ENABLE) -#define LF_TERMINAL_ANSI_CODE(__id, __suffix) LF_TERMINAL_ANSI_CSI #__id #__suffix -#else -#define LF_TERMINAL_ANSI_CODE(__id, __suffix) "" -#endif - -#define LF_TERMINAL_ANSI_GRAPHICS_CODE(__id) LF_TERMINAL_ANSI_CODE(__id, m) -#define LF_TERMINAL_ANSI_CODE_DEFINE(__codeName, __id) inline const char (& __codeName ())[std::extent>::value] { return LF_TERMINAL_ANSI_GRAPHICS_CODE(__id); } - - -namespace LFramework::Terminal::Ansi { - namespace Color { - - LF_TERMINAL_ANSI_CODE_DEFINE(Black, 30) - LF_TERMINAL_ANSI_CODE_DEFINE(Red, 31) - LF_TERMINAL_ANSI_CODE_DEFINE(Green, 32) - LF_TERMINAL_ANSI_CODE_DEFINE(Yellow, 33) - LF_TERMINAL_ANSI_CODE_DEFINE(Blue, 34) - LF_TERMINAL_ANSI_CODE_DEFINE(Magenta, 35) - LF_TERMINAL_ANSI_CODE_DEFINE(Cyan, 36) - LF_TERMINAL_ANSI_CODE_DEFINE(LightGray, 37) - LF_TERMINAL_ANSI_CODE_DEFINE(DarkGray, 90) - LF_TERMINAL_ANSI_CODE_DEFINE(LightRed, 91) - LF_TERMINAL_ANSI_CODE_DEFINE(LightGreen, 92) - LF_TERMINAL_ANSI_CODE_DEFINE(LightYellow, 93) - LF_TERMINAL_ANSI_CODE_DEFINE(LightBlue, 94) - LF_TERMINAL_ANSI_CODE_DEFINE(LightMagenta, 95) - LF_TERMINAL_ANSI_CODE_DEFINE(LightCyan, 96) - LF_TERMINAL_ANSI_CODE_DEFINE(White, 97) - - //Background - namespace BG { - LF_TERMINAL_ANSI_CODE_DEFINE(Black, 40) - LF_TERMINAL_ANSI_CODE_DEFINE(Red, 41) - LF_TERMINAL_ANSI_CODE_DEFINE(Green, 42) - LF_TERMINAL_ANSI_CODE_DEFINE(Yellow, 43) - LF_TERMINAL_ANSI_CODE_DEFINE(Blue, 44) - LF_TERMINAL_ANSI_CODE_DEFINE(Magenta, 45) - LF_TERMINAL_ANSI_CODE_DEFINE(Cyan, 46) - LF_TERMINAL_ANSI_CODE_DEFINE(LightGray, 47) - LF_TERMINAL_ANSI_CODE_DEFINE(DarkGray, 100) - LF_TERMINAL_ANSI_CODE_DEFINE(LightRed, 101) - LF_TERMINAL_ANSI_CODE_DEFINE(LightGreen, 102) - LF_TERMINAL_ANSI_CODE_DEFINE(LightYellow, 103) - LF_TERMINAL_ANSI_CODE_DEFINE(LightBlue, 104) - LF_TERMINAL_ANSI_CODE_DEFINE(LightMagenta, 105) - LF_TERMINAL_ANSI_CODE_DEFINE(LightCyan, 106) - LF_TERMINAL_ANSI_CODE_DEFINE(White, 107) - } - } - - namespace Format { - LF_TERMINAL_ANSI_CODE_DEFINE(BoldSet, 1) - LF_TERMINAL_ANSI_CODE_DEFINE(BoldReset, 21) - LF_TERMINAL_ANSI_CODE_DEFINE(UnderlinedSet, 4) - LF_TERMINAL_ANSI_CODE_DEFINE(UnderlinedReset, 24) - LF_TERMINAL_ANSI_CODE_DEFINE(BlinkSet, 5) - LF_TERMINAL_ANSI_CODE_DEFINE(BlinkReset, 25) - LF_TERMINAL_ANSI_CODE_DEFINE(ReverseSet, 7) - LF_TERMINAL_ANSI_CODE_DEFINE(ReverseReset, 27) - LF_TERMINAL_ANSI_CODE_DEFINE(ResetAll, 0) - - LF_TERMINAL_ANSI_CODE_DEFINE(Framed, 51) - LF_TERMINAL_ANSI_CODE_DEFINE(Encircled, 52) - LF_TERMINAL_ANSI_CODE_DEFINE(Overlined, 53) - LF_TERMINAL_ANSI_CODE_DEFINE(ClearFramedEncircled, 54) - LF_TERMINAL_ANSI_CODE_DEFINE(ClearOverlined, 55) - } - - - namespace Cursor { - inline const char (& EnableBlinking ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"?12h"; - } - inline const char (& DisableBlinking ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"?12l"; - } - inline const char (& Show ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"?25h"; - } - inline const char (& Hide ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"?25l"; - } - - - inline const char (& MoveHome ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"H"; - } - - inline const char (& SavePosition ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"s"; - } - - inline const char (& RestorePosition ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"u"; - } - } - - namespace TextEdit { - inline const char (& EraseLineCurToBeg ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"K"; - } - inline const char (& EraseLineBegToCur ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"1K"; - } - inline const char (& EraseLine ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"2K"; - } - } - - namespace Viewport { - inline const char (& ClearScreenAfterCursor ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"0J"; - } - inline const char (& ClearScreenBeforeCursor ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"1J"; - } - inline const char (& ClearScreen ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"2J"; - } - inline const char (& ClearScreenAndScrollback ())[std::extent>::value] { - return LF_TERMINAL_ANSI_CSI"3J"; - } - } -} diff --git a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStream.h b/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStream.h deleted file mode 100644 index 0cef1f5..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStream.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "../StreamWriter.h" - -namespace LFramework::Terminal { - class Stream : public OutputStream{ - public: - int write(const char* data, int length) override final; - }; -} - diff --git a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStreamCout.cpp b/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStreamCout.cpp deleted file mode 100644 index e27a4fa..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStreamCout.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "TerminalStream.h" - - -#ifdef LF_TERMINAL_STREAM_COUT - -#include - -namespace LFramework::Terminal { - int LFramework::Terminal::Stream::write(const char* data, int length) { - std::cout.write(data, length); - std::cout.flush(); - return length; - } -} - -#endif diff --git a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStreamUartStm32.cpp b/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStreamUartStm32.cpp deleted file mode 100644 index 54be8d3..0000000 --- a/Dependencies/LFramework/Src/LFramework/IO/Terminal/TerminalStreamUartStm32.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "TerminalStream.h" - -#ifdef LF_TERMINAL_STREAM_USART_STM32 - - -#ifdef STM32F7 -#include -#include -#elif STM32H7 -#include -#include -#endif - -namespace LFramework::Terminal { - - - int LFramework::Terminal::Stream::write(const char* data, int length) { - for(int i = 0; i < length; ++i){ - while (!LL_USART_IsActiveFlag_TXE(LF_TERMINAL_STREAM_USART)) {} - LL_USART_TransmitData8(LF_TERMINAL_STREAM_USART, *data); - ++data; - } - - //if(HAL_OK == HAL_UART_Transmit(&huart1, reinterpret_cast(const_cast(data)), length, HAL_MAX_DELAY)){ - // return length; - //} - return length; - } -} - -#endif diff --git a/Dependencies/LFramework/Src/LFramework/Input/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/Input/CMakeLists.txt deleted file mode 100644 index c0f8834..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -add_library(LFrameworkInput INTERFACE ) -add_library(LFramework::Input ALIAS LFrameworkInput ) - -target_sources(LFrameworkInput -INTERFACE - Input.h - Keyboard.h - KeysStateManager.h - Mouse.h - - Input.cpp - Keyboard.cpp - Mouse.cpp -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/Input/Input.cpp b/Dependencies/LFramework/Src/LFramework/Input/Input.cpp deleted file mode 100644 index 448d9e3..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/Input.cpp +++ /dev/null @@ -1,150 +0,0 @@ -#ifdef _WIN32 - -#include "Input.h" -#include -#include -#include -#include - -Input::Input() { - auto hInst = GetModuleHandle(NULL); - register_input_window_class(hInst); - - _input_window = CreateWindow(_class_name, TEXT("RawInputWindow"), WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL); - - if (_input_window == NULL) { - std::cout << "Failed to create input window!" << std::endl; - } - SetWindowLongPtr(_input_window, GWLP_USERDATA, (LONG_PTR)this); - ShowWindow(_input_window, SW_HIDE); - UpdateWindow(_input_window); - - enumerate_devices(); - - RAWINPUTDEVICE Rid[2]; - - Rid[0].usUsagePage = 0x01; //HID mouse - Rid[0].usUsage = 0x02; - Rid[0].dwFlags = RIDEV_INPUTSINK; - Rid[0].hwndTarget = _input_window; - - Rid[1].usUsagePage = 0x01; //HID keyboard - Rid[1].usUsage = 0x06; - Rid[1].dwFlags = RIDEV_INPUTSINK; - Rid[1].hwndTarget = _input_window; - - if (RegisterRawInputDevices(Rid, 2, sizeof(Rid[0])) == FALSE) { - std::cout << "Failed to register raw input devices!" << std::endl; - } -} - -std::shared_ptr Input::Instance() { - static std::shared_ptr instance(new Input()); - return instance; -} - -const std::vector>& Input::mice() const{ - return _mice; -} - -void Input::strobe(){ - - MSG msg = { 0 }; - while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - - for(auto mouse : _mice){ - mouse->Strobe(); - } - for(auto kb : _keyboards){ - kb->Strobe(); - } -} - -void Input::enumerate_devices() { - _mice.clear(); - - UINT numDevices; - GetRawInputDeviceList(NULL, &numDevices, sizeof(RAWINPUTDEVICELIST)); - if (numDevices == 0) return; - - std::vector deviceList(numDevices); - GetRawInputDeviceList(&deviceList[0], &numDevices, sizeof(RAWINPUTDEVICELIST)); - - std::vector deviceNameData; - std::wstring deviceName; - for (UINT i = 0; i < numDevices; ++i) { - const RAWINPUTDEVICELIST& device = deviceList[i]; - if (device.dwType == RIM_TYPEMOUSE) { - _mice.push_back(std::make_shared(device.hDevice)); - } else if (device.dwType == RIM_TYPEKEYBOARD) { - _keyboards.push_back(std::make_shared(device.hDevice)); - } else { - std::cout << "HID device" << std::endl; - } - } -} - -ATOM Input::register_input_window_class(HINSTANCE hinstance) { - - WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = &Input::wnd_proc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = hinstance; - wcex.hIcon = LoadIcon(wcex.hInstance, IDI_APPLICATION); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); - wcex.lpszMenuName = NULL; - wcex.lpszClassName = _class_name; - wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION); - return RegisterClassEx(&wcex); -} - -const std::vector>& Input::keyboards() const -{ - return _keyboards; -} - -LRESULT CALLBACK Input::wnd_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - auto input = (Input*)GetWindowLongPtr(hWnd, GWLP_USERDATA); - switch (message) { - case WM_DESTROY: - PostQuitMessage(0); - break; - case WM_INPUT: { - UINT dwSize; - GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); - LPBYTE lpb = new BYTE[dwSize]; - - if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) { - OutputDebugString(TEXT("GetRawInputData does not return correct size !\n")); - } - - RAWINPUT* raw = (RAWINPUT*)lpb; - - if (raw->header.dwType == RIM_TYPEKEYBOARD) { - auto device = std::find_if(input->_keyboards.begin(), input->_keyboards.end(), [raw](std::shared_ptr m) {return m->GetHandle() == raw->header.hDevice; }); - if (device != input->_keyboards.end()) { - (*device)->ApplyInput(*raw); - } - } else if (raw->header.dwType == RIM_TYPEMOUSE) { - auto device = std::find_if(input->_mice.begin(), input->_mice.end(), [raw](std::shared_ptr m) {return m->GetHandle() == raw->header.hDevice; }); - if(device != input->_mice.end()){ - (*device)->ApplyInput(*raw); - } - } - } - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - return 0; -} - -#endif diff --git a/Dependencies/LFramework/Src/LFramework/Input/Input.h b/Dependencies/LFramework/Src/LFramework/Input/Input.h deleted file mode 100644 index a168897..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/Input.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include -#include -#include "Mouse.h" -#include "Keyboard.h" - -class Input { -public: - Input(); - static std::shared_ptr Instance(); - const std::vector>& mice() const; - const std::vector>& keyboards() const; - void strobe(); -private: - void enumerate_devices(); - ATOM register_input_window_class(HINSTANCE hinstance); - static LRESULT CALLBACK wnd_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - HWND _input_window; - const TCHAR* _class_name = TEXT("RawInputWindow"); - std::vector> _mice; - std::vector> _keyboards; -}; diff --git a/Dependencies/LFramework/Src/LFramework/Input/Keyboard.cpp b/Dependencies/LFramework/Src/LFramework/Input/Keyboard.cpp deleted file mode 100644 index 5a4b268..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/Keyboard.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#ifdef _WIN32 - -#include "Keyboard.h" -#include - -Keyboard::Keyboard(HANDLE hdevice) :_hdevice(hdevice) { - UINT dataSize; - GetRawInputDeviceInfo(hdevice, RIDI_DEVICENAME, nullptr, &dataSize); - if (dataSize) { - std::wstring name_data; - name_data.resize(dataSize); - UINT result = GetRawInputDeviceInfo(hdevice, RIDI_DEVICENAME, &name_data[0], &dataSize); - if (result != UINT_MAX) { - _name = name_data; - } - } - - RID_DEVICE_INFO deviceInfo; - deviceInfo.cbSize = sizeof deviceInfo; - dataSize = sizeof deviceInfo; - UINT result = GetRawInputDeviceInfo(hdevice, RIDI_DEVICEINFO, &deviceInfo, &dataSize); - _function_keys_count = deviceInfo.keyboard.dwNumberOfFunctionKeys; - _keys_count = deviceInfo.keyboard.dwNumberOfKeysTotal; - _indicators_count = deviceInfo.keyboard.dwNumberOfIndicators; -} - -void Keyboard::Strobe() { - _keys_manager.strobe(); -} - -HANDLE Keyboard::GetHandle() const { - return _hdevice; -} - -bool Keyboard::GetKeyState(uint32_t key_index) const { - return _keys_manager._key_states[key_index]; -} - -bool Keyboard::GetKeyPressed(uint32_t key_index) const { - return _keys_manager._key_pressed[key_index]; -} - -bool Keyboard::GetKeyReleased(uint32_t key_index) const { - return _keys_manager._key_released[key_index]; -} - -void Keyboard::ApplyInput(RAWINPUT input) { - if (input.data.keyboard.Flags == RI_KEY_BREAK) - _keys_manager._key_states[input.data.keyboard.VKey] = false; - else - _keys_manager._key_states[input.data.keyboard.VKey] = true; -} -#endif diff --git a/Dependencies/LFramework/Src/LFramework/Input/Keyboard.h b/Dependencies/LFramework/Src/LFramework/Input/Keyboard.h deleted file mode 100644 index 7c1818d..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/Keyboard.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include -#include -#include "KeysStateManager.h" - -class Keyboard { -public: - friend class Input; - Keyboard(HANDLE hdevice); - - HANDLE GetHandle() const; - bool GetKeyState(uint32_t key_index) const; - bool GetKeyPressed(uint32_t key_index) const; - bool GetKeyReleased(uint32_t key_index) const; -private: - void Strobe(); - void ApplyInput(RAWINPUT input); - HANDLE _hdevice; - std::wstring _name; - uint32_t _function_keys_count; - uint32_t _keys_count; - uint32_t _indicators_count; - - KeysStateManager<0xff, Keyboard> _keys_manager; -}; diff --git a/Dependencies/LFramework/Src/LFramework/Input/KeysStateManager.h b/Dependencies/LFramework/Src/LFramework/Input/KeysStateManager.h deleted file mode 100644 index 5b46dba..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/KeysStateManager.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef KeysStateManager_h__ -#define KeysStateManager_h__ - -template -class KeysStateManager { -public: - friend Owner; - KeysStateManager() - { - for (uint32_t i = 0; i < Count; ++i) { - _key_states[i] = _key_pressed[i] = _key_released[i] = _key_states_previous[i] = false; - } - } - void strobe(); -private: - bool _key_states[Count]; - bool _key_states_previous[Count]; - bool _key_pressed[Count]; - bool _key_released[Count]; -}; - -template -void KeysStateManager::strobe(){ - - - for (uint32_t i = 0; i < Count; ++i) { - if (_key_states[i]) { //if now pressed - if (_key_states_previous[i]) {//if was pressed - _key_pressed[i] = false; - } else { - _key_pressed[i] = true; - } - } else { - _key_pressed[i] = false; - } - if (!_key_states[i]) { //not pressed - if (_key_states_previous[i]) {//if was pressed - _key_released[i] = true; - } else { - _key_released[i] = false; - } - } else { - _key_released[i] = false; - } - _key_states_previous[i] = _key_states[i]; - } -} - - -#endif // KeysStateManager_h__ diff --git a/Dependencies/LFramework/Src/LFramework/Input/Mouse.cpp b/Dependencies/LFramework/Src/LFramework/Input/Mouse.cpp deleted file mode 100644 index 7096b96..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/Mouse.cpp +++ /dev/null @@ -1,80 +0,0 @@ - -#ifdef _WIN32 - -#include "Mouse.h" - -#include - - -Mouse::Mouse(HANDLE handle) :_handle(handle){ - _deltax = _deltay = _deltax_integral = _deltay_integral = 0; - - UINT dataSize; - GetRawInputDeviceInfo(_handle, RIDI_DEVICENAME, nullptr, &dataSize); - if (dataSize) { - _name.resize(dataSize); - UINT result = GetRawInputDeviceInfo(_handle, RIDI_DEVICENAME, &_name[0], &dataSize); - if (result != UINT_MAX) { - _name.assign(_name.begin(), _name.end()); - } - } - - RID_DEVICE_INFO deviceInfo; - deviceInfo.cbSize = sizeof deviceInfo; - dataSize = sizeof deviceInfo; - UINT result = GetRawInputDeviceInfo(_handle, RIDI_DEVICEINFO, &deviceInfo, &dataSize); - if (result != UINT_MAX) { - _buttons_count = deviceInfo.mouse.dwNumberOfButtons; - _has_horizontal_wheel = deviceInfo.mouse.fHasHorizontalWheel == TRUE; - } -} - -HANDLE Mouse::GetHandle() const{ - return _handle; -} - -bool Mouse::GetKeyState(uint32_t key_index) const{ - return _keys_manager._key_states[key_index]; -} - -bool Mouse::GetKeyPressed(uint32_t key_index) const{ - return _keys_manager._key_pressed[key_index]; -} - -bool Mouse::GetKeyReleased(uint32_t key_index) const{ - return _keys_manager._key_released[key_index]; -} - -void Mouse::Strobe() { - _deltax = _deltax_integral; - _deltax_integral = 0; - _deltay = _deltay_integral; - _deltay_integral = 0; - _keys_manager.strobe(); -} - -int32_t Mouse::GetDx() const{ - return _deltax; -} - -int32_t Mouse::GetDy() const{ - return _deltay; -} - -void Mouse::ApplyInput(RAWINPUT input) { - //input.data.mouse.lLastX - _deltax_integral += input.data.mouse.lLastX; - _deltay_integral += input.data.mouse.lLastY; - - RAWMOUSE data = input.data.mouse; - for (uint32_t i = 0; i < maxButtonsCount; ++i){ - if((data.ulButtons & (1 << (i << 1))) != 0){ - _keys_manager._key_states[i] = true; - } - if ((data.ulButtons & (2 << (i << 1))) != 0) { - _keys_manager._key_states[i] = false; - } - } -} -#endif - diff --git a/Dependencies/LFramework/Src/LFramework/Input/Mouse.h b/Dependencies/LFramework/Src/LFramework/Input/Mouse.h deleted file mode 100644 index 41e1647..0000000 --- a/Dependencies/LFramework/Src/LFramework/Input/Mouse.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include "KeysStateManager.h" -#include - -class Mouse { -public: - static constexpr uint32_t maxButtonsCount = 5; - friend class Input; - Mouse(HANDLE handle); - HANDLE GetHandle() const; - bool GetKeyState(uint32_t key_index) const; - bool GetKeyPressed(uint32_t key_index) const; - bool GetKeyReleased(uint32_t key_index) const; - int32_t GetDx() const; - int32_t GetDy() const; -private: - void Strobe(); - void ApplyInput(RAWINPUT input); - LONG _deltax_integral; - LONG _deltay_integral; - LONG _deltax; - LONG _deltay; - KeysStateManager _keys_manager; - HANDLE _handle; - std::wstring _name; - uint32_t _buttons_count; - bool _has_horizontal_wheel; -}; - diff --git a/Dependencies/LFramework/Src/LFramework/MCU/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/MCU/CMakeLists.txt deleted file mode 100644 index 609c9b2..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - Mcu.h -) -add_subdirectory(DMA) -add_subdirectory(stm32) -add_subdirectory(USBDevice) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/MCU/DMA/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/MCU/DMA/CMakeLists.txt deleted file mode 100644 index 87b5482..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/DMA/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - DMA.h -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/MCU/DMA/DMA.h b/Dependencies/LFramework/Src/LFramework/MCU/DMA/DMA.h deleted file mode 100644 index 9f244ee..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/DMA/DMA.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * DMA.h - * - * Created on: 25 ñåíò. 2017 ã. - * Author: l-pro - */ - -#ifndef LFRAMEWORK_MCU_DMA_DMA_H_ -#define LFRAMEWORK_MCU_DMA_DMA_H_ - - -namespace EmbeddedFramework { - -class DMA{ - -}; - -template -class DmaIrqHandler{ - -}; - -template -class DmaCallback { -public: - /*static void error(); - static void complete(); - static void halfComplete();*/ -}; - - -#endif /* LFRAMEWORK_MCU_DMA_DMA_H_ */ diff --git a/Dependencies/LFramework/Src/LFramework/MCU/Mcu.h b/Dependencies/LFramework/Src/LFramework/MCU/Mcu.h deleted file mode 100644 index f5cd123..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/Mcu.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Mcu.h - * - * Created on: 19 July. 2017 ã. - * Author: l-pro - */ - -#ifndef MCUFRAMEWORK_MCU_H_ -#define MCUFRAMEWORK_MCU_H_ - -#include "LFrameworkConfig.h" -#include - -#ifndef CMSIS_DEVICE_FILE -#error "CMSIS_DEVICE_FILE path not defined in McuConfig.h" -#else -#include CMSIS_DEVICE_FILE -#endif - -namespace LFramework { -namespace Mcu { - inline size_t getCurrentInterruptHandlerIndex(){ - return __get_IPSR(); - } - - inline bool isHandlingInterrupt() { - return getCurrentInterruptHandlerIndex() != 0; - } - - inline bool isDebuggerAttached() { - return (CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk) != 0; - } - - inline void setBreakpoint() { - if(isDebuggerAttached){ - __BKPT(0); - } - } -} -} - -#endif /* MCUFRAMEWORK_MCU_H_ */ diff --git a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/CMakeLists.txt deleted file mode 100644 index fb50a6d..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(PHY) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/CMakeLists.txt deleted file mode 100644 index 242fb6c..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - Stm32FsPhy.h - UsbDeviceSoftPhy.h - UsbInternalFsDeviceDriver.h -) - - - diff --git a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/Stm32FsPhy.h b/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/Stm32FsPhy.h deleted file mode 100644 index a688df2..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/Stm32FsPhy.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef Stm32FsPhy_h__ -#define Stm32FsPhy_h__ - -namespace LFramework { - - template - class Stm32FsPhy { - public: - /*void UsbDevice::start() { - HAL_PCD_Start(_pcd); - }*/ - - //UsbDevice(PCD_HandleTypeDef* pcd); - - /*void initPHY() { - - _pcd->Instance = USB_OTG_FS; - _pcd->Init.dev_endpoints = 1; - _pcd->Init.speed = PCD_SPEED_FULL; - _pcd->Init.dma_enable = DISABLE; - _pcd->Init.Sof_enable = DISABLE; - _pcd->Init.ep0_mps = 64; - _pcd->Init.phy_itface = PCD_PHY_EMBEDDED; - _pcd->Init.low_power_enable = DISABLE; - _pcd->Init.lpm_enable = DISABLE; - _pcd->Init.vbus_sensing_enable = DISABLE; - _pcd->Init.use_dedicated_ep1 = DISABLE; - //_pcd->Init.battery_charging_enable = DISABLE; - HAL_PCD_Init(_pcd); - - //HAL_PCD_SetRxFiFo(&USBD_PCD, 0x80); - //HAL_PCD_SetTxFiFo(&USBD_PCD, 0, 0x20); - //HAL_PCD_SetTxFiFo(&USBD_PCD, 1, 0x40); - - HAL_PCD_SetRxFiFo(_pcd, 0x80); - HAL_PCD_SetTxFiFo(_pcd, 0, 0x40); - HAL_PCD_SetTxFiFo(_pcd, 1, 0x80); - }*/ - - void connect() { - //HAL_PCD_DevConnect(_pcd); - } - - void disconnect() { - //HAL_PCD_DevDisconnect(_pcd); - } - - //PCD_HandleTypeDef* _pcd; - }; -} -#endif // Stm32FsPhy_h__ diff --git a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/UsbDeviceSoftPhy.h b/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/UsbDeviceSoftPhy.h deleted file mode 100644 index e223f4d..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/UsbDeviceSoftPhy.h +++ /dev/null @@ -1,211 +0,0 @@ -#ifndef UsbDeviceSoftPhy_h__ -#define UsbDeviceSoftPhy_h__ - -#include -#include -#include - -namespace LFramework { - namespace USB { - - static const char* StageStrings[] = { "WaitForConnection", "Reset1", "GetDeviceDescriptor", "Reset2" }; - - class SoftEndpoint { - public: - bool isIn = false; - bool isOpen = false; - uint8_t maxPacketSize = 0; - bool receiving = false; - std::queue> packets; - }; - - template - class UsbDeviceSoftPhy { - public: - static constexpr uint8_t MaxEndpointsCount = 16; - static constexpr uint8_t MaxPacketSize = 64; - - - void connect() { - _connected = true; - } - - void start() { - if (_running) { - return; - } - - _running = true; - setStage(Stage::WaitForConnection); - _usbThread = std::thread(std::bind(&UsbDeviceSoftPhy::threadHandler, this)); - } - - void stop() { - - if (_running) { - _running = false; - _usbThread.join; - } - } - - enum class Stage { - WaitForConnection, - Reset1, - GetDeviceDescriptor, - Reset2, - StageCount - }; - - - - UsbDeviceSoftPhy() { - _stageHandlers[static_cast(Stage::WaitForConnection)] = &UsbDeviceSoftPhy::stageWaitForConnection; - _stageHandlers[static_cast(Stage::Reset1)] = &UsbDeviceSoftPhy::stageReset1; - _stageHandlers[static_cast(Stage::GetDeviceDescriptor)] = &UsbDeviceSoftPhy::stageGetDeviceDescriptor; - _stageHandlers[static_cast(Stage::Reset2)] = &UsbDeviceSoftPhy::stageReset2; - } - - Device* asDevice() { - return static_cast(this); - } - - static bool isValidPacketSize(uint8_t maxPacketSize, EndpointAddress endpointAddress) { - return true; - } - - bool openEndpoint(EndpointAddress address, uint8_t maxPacketSize, EndpointType type) { - if(!isValidPacketSize(maxPacketSize, address)) { - std::cout << "Failed to open endpoint with address " << address.value << std::endl; - return false; - } - - SoftEndpoint& endpoint = address.isIn() ? _inEndpoints[address.index()] : _outEndpoints[address.index()]; - endpoint.maxPacketSize = maxPacketSize; - endpoint.isOpen = true; - std::cout << "Open endpoint with address " << (int)address.value << std::endl; - return true; - } - - void closeEndpoint(EndpointAddress address) { - SoftEndpoint& endpoint = address.isIn() ? _inEndpoints[address.index()] : _outEndpoints[address.index()]; - endpoint.isOpen = false; - endpoint.packets.clear(); - } - - void beginReceive(EndpointAddress address, void* buffer, uint8_t size) { - auto& ep = _outEndpoints[address.index()]; - ep.receiving = true; - } - - void beginTransmit(EndpointAddress address, void* buffer, uint8_t size) { - auto& ep = _inEndpoints[address.index()]; - size = (std::min)(size, ep.maxPacketSize); - std::vector packet; - if(size != 0) { - packet.insert(packet.end(), (uint8_t*)buffer, (uint8_t*)buffer + size); - } - ep.packets.push(packet); - } - private: - - void setStage(Stage stage) { - std::cout << "Change stage from " << StageStrings[(int)_currentStage] << " to " << StageStrings[(int)stage] << std::endl; - _currentStage = stage; - - if(_currentStage == Stage::WaitForConnection) { - for(auto& ep : _inEndpoints) { - ep.isOpen = false; - ep.receiving = false; - ep.packets = {}; - } - for (auto& ep : _outEndpoints) { - ep.isOpen = false; - ep.receiving = false; - ep.packets = {}; - } - } - } - - SoftEndpoint _inEndpoints[MaxEndpointsCount]; - SoftEndpoint _outEndpoints[MaxEndpointsCount]; - - Stage _currentStage = Stage::WaitForConnection; - - void stageWaitForConnection() { - if (_connected) { - std::cout << "Device connected" << std::endl; - setStage(Stage::Reset1); - - } - } - void stageReset1() { - std::cout << "Device reset1 begin" << std::endl; - asDevice()->onReset(); - std::cout << "Device reset1 end" << std::endl; - setStage(Stage::GetDeviceDescriptor); - } - - - - std::vector controlIn(SetupPacket setup) { - /*SetupPacket setup; - setup.bmRequestType.Direction = RequestDirection::DeviceToHost; - setup.bmRequestType.Recipient = RequestRecipient::Device; - setup.bmRequestType.Type = RequestType::Standard;*/ - - asDevice()->onSetup(&setup); - - - std::vector rxBuffer; - auto& ep = _inEndpoints[0]; - for (;;) { - if(ep.isOpen) { - if(!ep.packets.empty()) { - auto packet = ep.packets.front(); - ep.packets.pop(); - if(packet.empty()) { - return rxBuffer; - }else { - rxBuffer.insert(rxBuffer.end(), packet.begin(), packet.end()); - } - } - - } - Sleep(1); - } - } - void stageGetDeviceDescriptor() { - SetupPacket setup; - setup.bmRequestType.Direction = RequestDirection::DeviceToHost; - setup.bmRequestType.Recipient = RequestRecipient::Device; - setup.bmRequestType.Type = RequestType::Standard; - setup.bRequest = SetupRequest::GetDescriptor; - setup.wIndex = 0; - setup.wValue = ((uint8_t)DescriptorType::DeviceDescriptor << 8) | 0; - setup.wLength = sizeof(DeviceDescriptor); - - auto descriptorData = controlIn(setup); - - for (;;); - } - void stageReset2() { - - } - void threadHandler() { - while (_running) { - (this->*_stageHandlers[static_cast(_currentStage)])(); - Sleep(1); - } - } - - std::array(Stage::StageCount)> _stageHandlers; - - std::thread _usbThread; - bool _connected = false; - bool _running = false; - }; - - } -} - -#endif // UsbDeviceSoftPhy_h__ diff --git a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/UsbInternalFsDeviceDriver.h b/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/UsbInternalFsDeviceDriver.h deleted file mode 100644 index 06fe52b..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/USBDevice/PHY/UsbInternalFsDeviceDriver.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * UsbInternalFsDeviceDriver.h - * - * Created on: 1 îêò. 2017 ã. - * Author: l-pro - */ - -#ifndef LFRAMEWORK_MCU_USBDEVICE_USBINTERNALFSDEVICEDRIVER_H_ -#define LFRAMEWORK_MCU_USBDEVICE_USBINTERNALFSDEVICEDRIVER_H_ - -namespace LFramework { -namespace USB { - -} -} - - - -#endif /* LFRAMEWORK_MCU_USBDEVICE_USBINTERNALFSDEVICEDRIVER_H_ */ diff --git a/Dependencies/LFramework/Src/LFramework/MCU/stm32/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/MCU/stm32/CMakeLists.txt deleted file mode 100644 index 0eb28f9..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/stm32/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - HalLibrary.h - HardFaultHandler.h - - HardFaultHandler.cpp -) - diff --git a/Dependencies/LFramework/Src/LFramework/MCU/stm32/HalLibrary.h b/Dependencies/LFramework/Src/LFramework/MCU/stm32/HalLibrary.h deleted file mode 100644 index 3afafd9..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/stm32/HalLibrary.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HalLibrary.h - * - * Created on: 17 ñåíò. 2017 ã. - * Author: l-pro - */ - -#ifndef LFRAMEWORK_MCU_STM32_HALLIBRARY_H_ -#define LFRAMEWORK_MCU_STM32_HALLIBRARY_H_ - - - - - -#endif /* LFRAMEWORK_MCU_STM32_HALLIBRARY_H_ */ diff --git a/Dependencies/LFramework/Src/LFramework/MCU/stm32/HardFaultHandler.cpp b/Dependencies/LFramework/Src/LFramework/MCU/stm32/HardFaultHandler.cpp deleted file mode 100644 index edcb62c..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/stm32/HardFaultHandler.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef _WIN32 - - -#include -#include - -extern "C" { - void HardFaultHandlerExtended(unsigned int * hardfault_args){ - unsigned int stacked_r0; - unsigned int stacked_r1; - unsigned int stacked_r2; - unsigned int stacked_r3; - unsigned int stacked_r12; - unsigned int stacked_lr; - unsigned int stacked_pc; - unsigned int stacked_psr; - - stacked_r0 = ((unsigned int)hardfault_args[0]); - stacked_r1 = ((unsigned int)hardfault_args[1]); - stacked_r2 = ((unsigned int)hardfault_args[2]); - stacked_r3 = ((unsigned int)hardfault_args[3]); - - stacked_r12 = ((unsigned int)hardfault_args[4]); - stacked_lr = ((unsigned int)hardfault_args[5]); - stacked_pc = ((unsigned int)hardfault_args[6]); - stacked_psr = ((unsigned int)hardfault_args[7]); - - lfFatal() << "----------"; - lfFatal() << "Hard fault"; - lfFatal() << "----------"; - - lfFatal() << "stacked_lr: 0x" << LFramework::HexFormat(stacked_lr) ; - lfFatal() << "stacked_pc: 0x" << LFramework::HexFormat(stacked_pc) ; - - while(true){ - asm("nop"); - } - - } -} -#endif diff --git a/Dependencies/LFramework/Src/LFramework/MCU/stm32/HardFaultHandler.h b/Dependencies/LFramework/Src/LFramework/MCU/stm32/HardFaultHandler.h deleted file mode 100644 index c1688ac..0000000 --- a/Dependencies/LFramework/Src/LFramework/MCU/stm32/HardFaultHandler.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#define HARD_FAULT_HANDLER \ -__asm( ".syntax unified\n" \ - "MOVS R0, #4 \n" \ - "MOV R1, LR \n" \ - "TST R0, R1 \n" \ - "BEQ _MSP \n" \ - "MRS R0, PSP \n" \ - "B HardFaultHandlerExtended \n" \ - "_MSP: \n" \ - "MRS R0, MSP \n" \ - "B HardFaultHandlerExtended \n" \ - ".syntax divided\n") ; diff --git a/Dependencies/LFramework/Src/LFramework/Macro/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/Macro/CMakeLists.txt deleted file mode 100644 index 1230836..0000000 --- a/Dependencies/LFramework/Src/LFramework/Macro/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - ForEach.h -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/Macro/ForEach.h b/Dependencies/LFramework/Src/LFramework/Macro/ForEach.h deleted file mode 100644 index a8cba6a..0000000 --- a/Dependencies/LFramework/Src/LFramework/Macro/ForEach.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef ForEach_h__ -#define ForEach_h__ - -#define UNPACK(...) __VA_ARGS__ - -//Count of commas == max args count (32) -#define CNT_PREFIX__CNT_POSTFIX ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0 - -#define COUNTER_SEQUENCE 32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 - -#define ARGS_CNT2(_0,_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, N, ...) N -#define ARGS_CNT1(__ARGS) ARGS_CNT2 __ARGS -#define ARGS_CNT(...) UNPACK(ARGS_CNT1((CNT_PREFIX_ ## __VA_ARGS__ ## _CNT_POSTFIX, COUNTER_SEQUENCE))) - -#define CONCAT(arg1, arg2) CONCAT1(arg1, arg2) -#define CONCAT1(arg1, arg2) CONCAT2(arg1, arg2) -#define CONCAT2(arg1, arg2) arg1##arg2 - -#define FOR_EACH_0(macro, runner, ...) -#define FOR_EACH_1(macro, runner, x) runner(macro, 0, LAST, x) -#define FOR_EACH_2(macro, runner, x, ...) runner(macro, 1, NOT_LAST, x) UNPACK(FOR_EACH_1(macro, runner, __VA_ARGS__)) -#define FOR_EACH_3(macro, runner, x, ...) runner(macro, 2, NOT_LAST, x) UNPACK(FOR_EACH_2(macro, runner, __VA_ARGS__)) -#define FOR_EACH_4(macro, runner, x, ...) runner(macro, 3, NOT_LAST, x) UNPACK(FOR_EACH_3(macro, runner, __VA_ARGS__)) -#define FOR_EACH_5(macro, runner, x, ...) runner(macro, 4, NOT_LAST, x) UNPACK(FOR_EACH_4(macro, runner, __VA_ARGS__)) -#define FOR_EACH_6(macro, runner, x, ...) runner(macro, 5, NOT_LAST, x) UNPACK(FOR_EACH_5(macro, runner, __VA_ARGS__)) -#define FOR_EACH_7(macro, runner, x, ...) runner(macro, 6, NOT_LAST, x) UNPACK(FOR_EACH_6(macro, runner, __VA_ARGS__)) -#define FOR_EACH_8(macro, runner, x, ...) runner(macro, 7, NOT_LAST, x) UNPACK(FOR_EACH_7(macro, runner, __VA_ARGS__)) -#define FOR_EACH_9(macro, runner, x, ...) runner(macro, 8, NOT_LAST, x) UNPACK(FOR_EACH_8(macro, runner, __VA_ARGS__)) -#define FOR_EACH_10(macro, runner, x, ...) runner(macro, 9, NOT_LAST, x) UNPACK(FOR_EACH_9(macro, runner, __VA_ARGS__)) -#define FOR_EACH_11(macro, runner, x, ...) runner(macro, 10, NOT_LAST, x) UNPACK(FOR_EACH_10(macro, runner, __VA_ARGS__)) -#define FOR_EACH_12(macro, runner, x, ...) runner(macro, 11, NOT_LAST, x) UNPACK(FOR_EACH_11(macro, runner, __VA_ARGS__)) -#define FOR_EACH_13(macro, runner, x, ...) runner(macro, 12, NOT_LAST, x) UNPACK(FOR_EACH_12(macro, runner, __VA_ARGS__)) -#define FOR_EACH_14(macro, runner, x, ...) runner(macro, 13, NOT_LAST, x) UNPACK(FOR_EACH_13(macro, runner, __VA_ARGS__)) -#define FOR_EACH_15(macro, runner, x, ...) runner(macro, 14, NOT_LAST, x) UNPACK(FOR_EACH_14(macro, runner, __VA_ARGS__)) -#define FOR_EACH_16(macro, runner, x, ...) runner(macro, 15, NOT_LAST, x) UNPACK(FOR_EACH_15(macro, runner, __VA_ARGS__)) -#define FOR_EACH_17(macro, runner, x, ...) runner(macro, 16, NOT_LAST, x) UNPACK(FOR_EACH_16(macro, runner, __VA_ARGS__)) -#define FOR_EACH_18(macro, runner, x, ...) runner(macro, 17, NOT_LAST, x) UNPACK(FOR_EACH_17(macro, runner, __VA_ARGS__)) -#define FOR_EACH_19(macro, runner, x, ...) runner(macro, 18, NOT_LAST, x) UNPACK(FOR_EACH_18(macro, runner, __VA_ARGS__)) -#define FOR_EACH_20(macro, runner, x, ...) runner(macro, 19, NOT_LAST, x) UNPACK(FOR_EACH_19(macro, runner, __VA_ARGS__)) -#define FOR_EACH_21(macro, runner, x, ...) runner(macro, 20, NOT_LAST, x) UNPACK(FOR_EACH_20(macro, runner, __VA_ARGS__)) -#define FOR_EACH_22(macro, runner, x, ...) runner(macro, 21, NOT_LAST, x) UNPACK(FOR_EACH_21(macro, runner, __VA_ARGS__)) -#define FOR_EACH_23(macro, runner, x, ...) runner(macro, 22, NOT_LAST, x) UNPACK(FOR_EACH_22(macro, runner, __VA_ARGS__)) -#define FOR_EACH_24(macro, runner, x, ...) runner(macro, 23, NOT_LAST, x) UNPACK(FOR_EACH_23(macro, runner, __VA_ARGS__)) -#define FOR_EACH_25(macro, runner, x, ...) runner(macro, 24, NOT_LAST, x) UNPACK(FOR_EACH_24(macro, runner, __VA_ARGS__)) -#define FOR_EACH_26(macro, runner, x, ...) runner(macro, 25, NOT_LAST, x) UNPACK(FOR_EACH_25(macro, runner, __VA_ARGS__)) -#define FOR_EACH_27(macro, runner, x, ...) runner(macro, 26, NOT_LAST, x) UNPACK(FOR_EACH_26(macro, runner, __VA_ARGS__)) -#define FOR_EACH_28(macro, runner, x, ...) runner(macro, 27, NOT_LAST, x) UNPACK(FOR_EACH_27(macro, runner, __VA_ARGS__)) -#define FOR_EACH_29(macro, runner, x, ...) runner(macro, 28, NOT_LAST, x) UNPACK(FOR_EACH_28(macro, runner, __VA_ARGS__)) -#define FOR_EACH_30(macro, runner, x, ...) runner(macro, 29, NOT_LAST, x) UNPACK(FOR_EACH_29(macro, runner, __VA_ARGS__)) -#define FOR_EACH_31(macro, runner, x, ...) runner(macro, 30, NOT_LAST, x) UNPACK(FOR_EACH_30(macro, runner, __VA_ARGS__)) -#define FOR_EACH_32(macro, runner, x, ...) runner(macro, 31, NOT_LAST, x) UNPACK(FOR_EACH_31(macro, runner, __VA_ARGS__)) - - -#define FOREACH_SIMPLE_RUNNER(macro, id, isLast, x) macro(x) -#define FOREACH_INDEXED_RUNNER(macro, id, isLast, x) macro(id, x) - -#define FOREACH_SIMPLE_RUNNER_ISLAST(macro, id, isLast, x) macro(isLast, x) - -#define FOR_EACH1_R(macro, runner, N, ...) UNPACK(CONCAT(FOR_EACH_, N)(macro, runner, __VA_ARGS__)) -#define FOR_EACH_R(macro, runner, ...) UNPACK(FOR_EACH1_R(macro, runner, ARGS_CNT(__VA_ARGS__), __VA_ARGS__)) - -#define FOR_EACH(macro, ...) FOR_EACH_R(macro, FOREACH_SIMPLE_RUNNER, __VA_ARGS__) - -#define FOR_EACH_N(macro, ...) FOR_EACH_R(macro, FOREACH_INDEXED_RUNNER, __VA_ARGS__) -#define FOR_EACH_L(macro, ...) FOR_EACH_R(macro, FOREACH_SIMPLE_RUNNER_ISLAST, __VA_ARGS__) - -static_assert(ARGS_CNT() == 0, "ARGS_CNT test fail"); -static_assert(ARGS_CNT(a) == 1, "ARGS_CNT test fail"); -static_assert(ARGS_CNT(a, a) == 2, "ARGS_CNT test fail"); -static_assert(ARGS_CNT(a, a, a, a) == 4, "ARGS_CNT test fail"); -static_assert(ARGS_CNT(a, a, a, a, a, a, a, a) == 8, "ARGS_CNT test fail"); -static_assert(ARGS_CNT(a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a) == 16, "ARGS_CNT test fail"); -static_assert(ARGS_CNT(a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a) == 32, "ARGS_CNT test fail"); - - -#endif // ForEach_h__ diff --git a/Dependencies/LFramework/Src/LFramework/Reflection/Reflection.h b/Dependencies/LFramework/Src/LFramework/Reflection/Reflection.h deleted file mode 100644 index a3dd89c..0000000 --- a/Dependencies/LFramework/Src/LFramework/Reflection/Reflection.h +++ /dev/null @@ -1,71 +0,0 @@ -#include "../Macro/ForEach.h" - -#define COMMA_LAST(x) x -#define COMMA_NOT_LAST(x) x , - -#define JOIN_IMPL(last, x) COMMA_##last(x) - -#define JOIN2(...) UNPACK(FOR_EACH_L(JOIN_IMPL, __VA_ARGS__)) -#define JOIN(...) UNPACK( JOIN2 (__VA_ARGS__) ) - -template -struct Reflect { - -}; - - -#define GEN_FIELD2(type_, name_) type_ name_; -#define GEN_FIELD(field_) GEN_FIELD2 field_ - -#define GEN_FIELD_GETTER2(id_, type_, name_) if constexpr(ID == FieldsCount - 1 - id_) return object. name_; -#define GEN_FIELD_GETTER1(id_, ...) UNPACK(GEN_FIELD_GETTER2(id_, __VA_ARGS__)) -#define GEN_FIELD_GETTER(id_, ...) GEN_FIELD_GETTER1(id_, UNPACK __VA_ARGS__ ) - - -#define DEFINE_STRUCT_RTTI(structName_, publicFields_) \ -template<> struct Reflect { \ -static const char* Name() {return #structName_; } \ - static constexpr size_t FieldsCount = ARGS_CNT(UNPACK publicFields_) ; \ - template static auto& getField(structName_& object){ \ - FOR_EACH_N(GEN_FIELD_GETTER, UNPACK publicFields_) ; \ - } \ -}; -#define DEFINE_STRUCT_TYPE(structName_, publicFields_) struct structName_ { FOR_EACH(GEN_FIELD, UNPACK publicFields_) }; - - -#define DEFINE_STRUCT(structName_, publicFields_) \ - DEFINE_STRUCT_TYPE(structName_, publicFields_) \ - DEFINE_STRUCT_RTTI(structName_, publicFields_) - - - -#define UNPACK_TEMPLATE_PARAMS1(last_, type_, name_) COMMA_##last_(type_ name_) -#define UNPACK_TEMPLATE_PARAM1(last, ...) UNPACK( UNPACK_TEMPLATE_PARAMS1(last, __VA_ARGS__ )) -#define UNPACK_TEMPLATE_PARAM(last, x) UNPACK_TEMPLATE_PARAM1(last, UNPACK x) - - -#define UNPACK_TEMPLATE_ARGS1(last_, type_, name_) COMMA_##last_(name_) -#define UNPACK_TEMPLATE_ARG1(last, ...) UNPACK( UNPACK_TEMPLATE_ARGS1(last, __VA_ARGS__ )) -#define UNPACK_TEMPLATE_ARG(last, x) UNPACK_TEMPLATE_ARG1(last, UNPACK x) - -#define UNPACK_TEMPLATE_PARAMS(...) UNPACK (FOR_EACH_L(UNPACK_TEMPLATE_PARAM, __VA_ARGS__) ) - - - -#define UNPACK_TEMPLATE_ARGS(...) UNPACK (FOR_EACH_L(UNPACK_TEMPLATE_ARG, __VA_ARGS__) ) - - -#define DEFINE_TEMPLATE_STRUCT_RTTI(templateParams_, structName_, publicFields_) \ -template< UNPACK_TEMPLATE_PARAMS templateParams_ > struct Reflect > { \ -static const char* Name() {return #structName_; } \ - static constexpr size_t FieldsCount = ARGS_CNT(UNPACK publicFields_) ; \ - template static auto& getField(structName_ < UNPACK_TEMPLATE_ARGS templateParams_ > & object){ \ - FOR_EACH_N(GEN_FIELD_GETTER, UNPACK publicFields_) ; \ - } \ -}; - -#define DEFINE_TEMPLATE_STRUCT_TYPE(templateParams_, structName_, publicFields_) template< UNPACK_TEMPLATE_PARAMS templateParams_ > struct structName_ { FOR_EACH(GEN_FIELD, UNPACK publicFields_) }; - -#define DEFINE_TEMPLATE_STRUCT(templateParams_, structName_, publicFields_) \ - DEFINE_TEMPLATE_STRUCT_TYPE(templateParams_, structName_, publicFields_) \ - DEFINE_TEMPLATE_STRUCT_RTTI(templateParams_, structName_, publicFields_) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/Syscalls.cpp b/Dependencies/LFramework/Src/LFramework/Syscalls.cpp deleted file mode 100644 index cf12da4..0000000 --- a/Dependencies/LFramework/Src/LFramework/Syscalls.cpp +++ /dev/null @@ -1,167 +0,0 @@ -#include "Detect/DetectOS.h" -#include "Assert.h" - -#if defined(LF_NEWLIB_TO_RTOS_MALLOC) -#include "FreeRTOS.h" -#endif - -#if defined(LF_SYSCALLS_STUBS) || defined(LF_NEWLIB_TO_RTOS_MALLOC) -#include -#include -#include -#include -#include -#include -#include "Debug.h" -#include "System.h" -#include -#endif//Todo check right files for different configuration - -extern "C" { - -#if defined(LF_SYSCALLS_STUBS) - -//extern int errno; -//register char * stack_ptr asm("sp"); - -#ifndef __errno_r -#include -#define __errno_r(reent) reent->_errno -#endif - -caddr_t _sbrk(int incr) { - static_cast(incr); - //std::terminate(); //Do not use newlib memory management - for(;;); - return nullptr; -} - -int _write_r(struct _reent* r, int file, char* ptr, int len){ - static_cast(r); - static_cast(ptr); - - if(stdout->_file != file && stderr->_file != file){ - for(;;);//Assert: unknown file descriptor - } - -#if defined(AF_TERMINAL_STDIO) - Terminal::write(ptr, len); -#endif - - return len; -} - -int _read_r(struct _reent *r, int file, char * ptr, int len) -{ - (void)r; - (void)file; - (void)ptr; - (void)len; - __errno_r(r) = EINVAL; - return -1; -} - -int _lseek_r(struct _reent *r, int file, int ptr, int dir){ - (void)r; - (void)file; - (void)ptr; - (void)dir; - return 0; -} - -int _close_r(struct _reent *r, int file){ - (void)r; - (void)file; - return 0; -} - -int _open_r ( struct _reent *ptr, const char *file, int flags, int mode ){ - static_cast(ptr); - static_cast(file); - static_cast(flags); - static_cast(mode); - int fd = -1; - return fd; -} - -int _fstat_r(struct _reent *r, int file, struct stat * st){ - (void)r; - (void)file; - memset(st, 0, sizeof(*st)); - st->st_mode = S_IFCHR; - return 0; -} - -int _isatty_r(struct _reent *r, int fd){ - (void)r; - (void)fd; - return 1; -} - -int _kill (int a, int b){ - (void)a; - (void)b; - return 0; -} -int _getpid(int a){ - (void)a; - return 0; -} - -#endif -//memory management - -#if LF_TARGET_OS == LF_OS_FREERTOS || defined(LF_SYSCALLS_STUBS) - -void __assert_func(const char * file, int line, const char * func, const char * error){ - lfDebug() << "libc assert"; - lfDebug() << "File: " << file; - //lfDebug() << "Line: " << line; - lfDebug() << "Function: " << func; - lfDebug() << "Expression: " << error; - for(;;); -} -void _exit(int status){ - lfDebug() << "_exit called"; - for(;;); -} - -#endif - - -#if defined(LF_NEWLIB_TO_RTOS_MALLOC) - - -void* _realloc_r(struct _reent *re, void* oldAddr, size_t newSize) { - static_cast(re); - static_cast(oldAddr); - static_cast(newSize); - lfAssert(false); //No mechanism is currently available to correctly reallocate memory, so just don't allow it for now - return nullptr; -} - -void* _calloc_r(struct _reent *re, size_t num, size_t size) { - static_cast(re); - void* result = pvPortMalloc(num*size); - if(result){ - //calloc should zero-initialize allocated memory - uint8_t* bytes = (uint8_t*)result; - for(size_t i = 0; i < (num * size); ++i){ - bytes[i] = 0; - } - } - return result; -} - -void* _malloc_r(struct _reent *re, size_t size) { - static_cast(re); - return pvPortMalloc(size); -} - -void _free_r(struct _reent *re, void* ptr) { - static_cast(re); - vPortFree(ptr); -} -#endif - -} //extern "C" diff --git a/Dependencies/LFramework/Src/LFramework/System.h b/Dependencies/LFramework/Src/LFramework/System.h deleted file mode 100644 index 090762e..0000000 --- a/Dependencies/LFramework/Src/LFramework/System.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef System_h__ -#define System_h__ - -#include - -#include "Detect/DetectOS.h" - - -#if LF_TARGET_OS == LF_OS_FREERTOS -#include "SystemArmCortexM.h" -#elif LF_TARGET_OS == LF_OS_WINDOWS -#include "SystemWindows.h" -#endif - - -#endif // System_h__ diff --git a/Dependencies/LFramework/Src/LFramework/SystemArmCortexM.h b/Dependencies/LFramework/Src/LFramework/SystemArmCortexM.h deleted file mode 100644 index cbf12b1..0000000 --- a/Dependencies/LFramework/Src/LFramework/SystemArmCortexM.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include - -#ifndef CMSIS_DEVICE_FILE -#error "CMSIS_DEVICE_FILE path not defined in McuConfig.h" -#else -#include CMSIS_DEVICE_FILE -#endif - -namespace LFramework { - namespace System { - inline size_t getCurrentInterruptHandlerIndex() { - return __get_IPSR(); - } - - inline bool isHandlingInterrupt() { - return getCurrentInterruptHandlerIndex() != 0; - } - - inline bool isDebuggerAttached() { - return (CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk) != 0; - } - - inline void setBreakpoint() { - if (isDebuggerAttached) { - __BKPT(0); - } - } - } -} diff --git a/Dependencies/LFramework/Src/LFramework/SystemWindows.h b/Dependencies/LFramework/Src/LFramework/SystemWindows.h deleted file mode 100644 index 3b85380..0000000 --- a/Dependencies/LFramework/Src/LFramework/SystemWindows.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef SystemWindows_h__ -#define SystemWindows_h__ - -#include - -namespace LFramework { - namespace System { - inline size_t getCurrentInterruptHandlerIndex() { - return 0; - } - - inline bool isHandlingInterrupt() { - return false; - } - - inline bool isDebuggerAttached() { - return IsDebuggerPresent() == TRUE; - } - - inline void setBreakpoint() { - if (isDebuggerAttached()) { - DebugBreak(); - } - } - } -} - -#endif // SystemWindows_h__ diff --git a/Dependencies/LFramework/Src/LFramework/Text/Encoding.h b/Dependencies/LFramework/Src/LFramework/Text/Encoding.h deleted file mode 100644 index a8fea5f..0000000 --- a/Dependencies/LFramework/Src/LFramework/Text/Encoding.h +++ /dev/null @@ -1,87 +0,0 @@ -#pragma once - -#include -#include - -namespace LFramework::Text { - class Encoding { - public: -#if defined(_MSC_VER) && _MSC_VER >= 1900 - // https://social.msdn.microsoft.com/Forums/en-US/8f40dcd8-c67f-4eba-9134-a19b9178e481/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral -#define _MSVC_CONVERT_WORKAROUND -#endif - - -#if defined(_MSVC_CONVERT_WORKAROUND) - static inline std::wstring_convert, int32_t> s_u32Converter; - static inline std::wstring_convert, int16_t> s_u16Converter; -#else - static inline std::wstring_convert, char32_t> s_u32Converter; - static inline std::wstring_convert, char16_t> s_u16Converter; -#endif - - static std::wstring u8StringToWString(const std::string& src) { - std::wstring_convert> converter; - return converter.from_bytes(src); - } - - static std::string wStringToU8String(const std::wstring& src) { - std::wstring_convert> convert; - return convert.to_bytes(src); - } - - static std::u32string u16StringToU32String(const std::u16string& u16String) - { - std::string temp{ u16StringToU8String(u16String) }; - - return u8StringToU32String(temp); - } - - static std::string u16StringToU8String(const std::u16string& u16String) - { -#if defined(_MSVC_CONVERT_WORKAROUND) - using workaround_str = std::basic_string, std::allocator >; - workaround_str workaround(reinterpret_cast(u16String.c_str())); - return s_u16Converter.to_bytes(workaround); -#else - return s_u16Converter.to_bytes(u16String); -#endif - } - - static std::string u32StringToU8String(const std::u32string& u32String) - { -#if defined(_MSVC_CONVERT_WORKAROUND) - using workaround_str = std::basic_string, std::allocator >; - workaround_str workaround(reinterpret_cast(u32String.c_str())); - return s_u32Converter.to_bytes(workaround); -#else - return s_u32Converter.to_bytes(u32String); -#endif - } - - static std::u16string u8StringToU16String(const std::string& u8String) - { -#if defined(_MSVC_CONVERT_WORKAROUND) - auto&& workaround = s_u16Converter.from_bytes(u8String); - return std::u16string(reinterpret_cast(workaround.c_str())); -#else - return s_u16Converter.from_bytes(u8String); -#endif - } - - static std::u32string u8StringToU32String(const std::string& u8String) - { -#if defined(_MSVC_CONVERT_WORKAROUND) - auto&& workaround = s_u32Converter.from_bytes(u8String); - return std::u32string(reinterpret_cast(workaround.c_str())); -#else - return s_u32Converter.from_bytes(u8String); -#endif - } - }; -} - - -#ifdef _MSVC_CONVERT_WORKAROUND -#undef _MSVC_CONVERT_WORKAROUND -#endif \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/Threading/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/Threading/CMakeLists.txt deleted file mode 100644 index 0647f4e..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -add_library(LFrameworkThreading INTERFACE ) -add_library(LFramework::Threading ALIAS LFrameworkThreading ) - -target_sources(LFrameworkThreading -INTERFACE - CriticalSection.h - CriticalSectionFreeRTOS.h - CriticalSectionStd.h - Semaphore.h - SemaphoreFreeRTOS.h - SemaphoreStd.h - Thread.h - ThreadFreeRTOS.h - ThreadPlatform.h - ThreadStd.h - - CriticalSectionStd.cpp - SemaphoreStdTest.cpp - Thread.cpp - ThreadTest.cpp -) diff --git a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSection.h b/Dependencies/LFramework/Src/LFramework/Threading/CriticalSection.h deleted file mode 100644 index 8e6e72c..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSection.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -#if LF_TARGET_OS == LF_OS_FREERTOS -#include "CriticalSectionFreeRTOS.h" -#elif (LF_TARGET_OS == LF_OS_WINDOWS) || (LF_TARGET_OS == LF_OS_LINUX) -#include "CriticalSectionStd.h" -#endif - diff --git a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionFreeRTOS.h b/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionFreeRTOS.h deleted file mode 100644 index ab978d6..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionFreeRTOS.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include "FreeRTOS.h" -#include "task.h" -#include "stm32f746xx.h" - -namespace LFramework::Threading { - - class CriticalSection { - public: - CriticalSection() { - _status = lock(); - } - - ~CriticalSection() { - unlock(); - } - - void unlock() { - unlock(_status); - } - - static size_t getCurrentInterruptNumber() { - return __get_IPSR(); - } - - static bool isInterruptHandling() { - return getCurrentInterruptNumber() != 0; - } - - static uint32_t lock() { - if (isInterruptHandling()) { - return taskENTER_CRITICAL_FROM_ISR(); - } - else { - taskENTER_CRITICAL(); - } - return 0; - } - - static void unlock(uint32_t irqStatus) { - if (isInterruptHandling()) { - taskEXIT_CRITICAL_FROM_ISR(irqStatus); - } - else { - taskEXIT_CRITICAL(); - } - } - - private: - uint32_t _status = 0; - }; -} diff --git a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionStd.cpp b/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionStd.cpp deleted file mode 100644 index b42bd13..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionStd.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include - -#if (LF_TARGET_OS == LF_OS_WINDOWS) || (LF_TARGET_OS == LF_OS_LINUX) -#include - -std::recursive_mutex LFramework::Threading::CriticalSection::_lock; -#endif diff --git a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionStd.h b/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionStd.h deleted file mode 100644 index f24b79c..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/CriticalSectionStd.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#include -#include - -namespace LFramework::Threading { - -class CriticalSection { -public: - CriticalSection() { - lock(); - } - - ~CriticalSection() { - unlock(0); - } - - static uint32_t lock() { - _lock.lock(); - return 0; - } - - static void unlock(int ) { - _lock.unlock(); - } - -private: - static std::recursive_mutex _lock; -}; - - -} diff --git a/Dependencies/LFramework/Src/LFramework/Threading/Semaphore.h b/Dependencies/LFramework/Src/LFramework/Threading/Semaphore.h deleted file mode 100644 index a788baa..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/Semaphore.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -#if LF_TARGET_OS == LF_OS_FREERTOS -#include "SemaphoreFreeRTOS.h" -#elif (LF_TARGET_OS == LF_OS_WINDOWS) || (LF_TARGET_OS == LF_OS_LINUX) -#include "SemaphoreStd.h" -#endif - diff --git a/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreFreeRTOS.h b/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreFreeRTOS.h deleted file mode 100644 index d1a681f..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreFreeRTOS.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - - -#include "../MCU/Mcu.h" -#include -#include - -#include "FreeRTOS.h" -#include "portable.h" -#include "queue.h" -#include "semphr.h" - - -namespace LFramework::Threading { - -class Semaphore { -public: - ~Semaphore(){ - vSemaphoreDelete(_handle); - } - - size_t messagesWaiting() const { - return (size_t)uxQueueMessagesWaiting(_handle); - } - - bool take(TickType_t wait = portMAX_DELAY) { - if (LFramework::Mcu::isHandlingInterrupt()) { - portBASE_TYPE taskWoken = pdFALSE; - if (xSemaphoreTakeFromISR(_handle, &taskWoken) != pdTRUE) { - return false; - } - portEND_SWITCHING_ISR(taskWoken); - return true; - } else { - return xSemaphoreTake(_handle, wait) == pdTRUE; - } - } - - bool give() { - if (LFramework::Mcu::isHandlingInterrupt()) { - portBASE_TYPE taskWoken = pdFALSE; - if (xSemaphoreGiveFromISR(_handle, &taskWoken) != pdTRUE) { - return false; - } - portEND_SWITCHING_ISR(taskWoken); - return true; - } else { - return xSemaphoreGive(_handle) == pdTRUE; - } - } - -protected: - SemaphoreHandle_t _handle; -}; - -class BinarySemaphore : public Semaphore{ -public: - BinarySemaphore(){ - _handle = xSemaphoreCreateBinary(); - assert(_handle != nullptr); - } -}; - -class CountingSemaphore : public Semaphore{ -public: - CountingSemaphore(UBaseType_t maxCount, UBaseType_t initialCount){ - _handle = xSemaphoreCreateCounting(maxCount, initialCount); - assert(_handle != nullptr); - } -}; - -} - diff --git a/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreStd.h b/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreStd.h deleted file mode 100644 index 8540fe6..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreStd.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace LFramework::Threading { - - class CountingSemaphore { - public: - static constexpr std::size_t InfiniteTimeout = -1; - CountingSemaphore(std::size_t maxCount, std::size_t initialCount) :_maxCount(maxCount), _count(initialCount) { - - } - bool take() { - std::unique_lock lk(_mutex); - _conditional.wait(lk, [this] { return _count > 0; }); - --_count; - return true; - } - - bool take(std::size_t milliseconds) { - std::unique_lock lk(_mutex); - if (_conditional.wait_for(lk, ::std::chrono::milliseconds(milliseconds), [this] { return _count > 0; })) { - --_count; - return true; - } - return false; - } - - bool tryTake() { - std::lock_guard<::std::mutex> lk(_mutex); - if (_count > 0) { - --_count; - return true; - } - else { - return false; - } - } - - bool give(std::size_t count) { - if(count == 0){ - return true; - } - std::lock_guard<::std::mutex> lk(_mutex); - if ((_count + count) <= _maxCount) { - _count += count; - if(count > 1){ - _conditional.notify_all(); - }else{ - _conditional.notify_one(); - } - return true; - } - return false; - } - - bool give() { - std::lock_guard<::std::mutex> lk(_mutex); - if (_count < _maxCount) { - ++_count; - _conditional.notify_one(); - return true; - } - return false; - } - - std::size_t messagesWaiting() const { - return _count.load(std::memory_order_relaxed); - } - - private: - std::size_t _maxCount = -1; - std::atomic _count = 0; - std::mutex _mutex; - std::condition_variable _conditional; - }; - - class BinarySemaphore : public CountingSemaphore { - public: - BinarySemaphore(bool startWithValue = false) : CountingSemaphore(1, startWithValue ? 1 : 0){ } - }; - -} diff --git a/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreStdTest.cpp b/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreStdTest.cpp deleted file mode 100644 index 3ee772f..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/SemaphoreStdTest.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "../UnitTest/UnitTest.h" - -#ifdef LF_THREADING - -#include "SemaphoreStd.h" -#include "Thread.h" - -#include - -using namespace LFramework; - - -TEST(SemaphoreStd_SyncUsage) { - Semaphore s0; - - TEST_TRUE(s0.available() == 0); - s0.give(); - TEST_TRUE(s0.available() == 1); - s0.give(9); - TEST_TRUE(s0.available() == 10); - - s0.take(0); - TEST_TRUE(s0.available() == 10); - s0.take(); - TEST_TRUE(s0.available() == 9); - s0.take(9); - TEST_TRUE(s0.available() == 0); -} - -TEST(SemaphoreStd_AsyncUsage) { - static constexpr size_t initialCount = 25; - - Semaphore resources(initialCount); - - Thread consumerThread0 = Thread("", 0, ThreadPriority::Normal, [&resources]() { - for(size_t i = 0; i < 100; ++i) { - resources.take(); - ThisThread::sleepForMs(1); - } - }); - - Thread consumerThread1 = Thread("", 0, ThreadPriority::Normal, [&resources]() { - for (size_t i = 0; i < 10; ++i) { - resources.take(10); - ThisThread::sleepForMs(2); - } - }); - - for(size_t i = 0; i < (200 - initialCount); i += 5) { - resources.give(5); - } - - consumerThread0.join(); - consumerThread1.join(); -} - -#endif diff --git a/Dependencies/LFramework/Src/LFramework/Threading/Thread.cpp b/Dependencies/LFramework/Src/LFramework/Threading/Thread.cpp deleted file mode 100644 index fddff69..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/Thread.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include -#include -#include - - -namespace LFramework::Threading { - - Thread::Thread(const char* name, size_t stackSize, ThreadPriority priority, std::function&& func) { - _impl = new Thread::Impl(name, stackSize, priority, std::move(func)); - } - - - Thread::Thread() noexcept = default; - - Thread::Thread(Thread&& other) noexcept{ - moveTask(other); - } - - Thread::~Thread() { - assert(!joinable()); - //_impl.reset(); - } - bool Thread::joinable() const noexcept { - return _impl != nullptr; - } - void Thread::join() { - assert(joinable()); - assert(ThisThread::getId() != getId()); //Can't join self - _impl->join(); - delete _impl; - _impl = nullptr; - } - void Thread::swap(Thread& other) { - std::swap(_impl, other._impl); - } - /*Thread::NativeHandleType Thread::nativeHandle() const { - assert(joinable()); - return _impl->getNativeHandle(); - }*/ - Thread::ID Thread::getId() const noexcept { - if (_impl != nullptr) { - return _impl->getId(); - } - return Thread::ID{}; - } - ThreadPriority Thread::getPriority() const { - assert(joinable()); - return _impl->getPriority(); - } - void Thread::setPriority(ThreadPriority priority) const { - assert(joinable()); - _impl->setPriority(priority); - } - void Thread::suspend() { - assert(joinable()); - _impl->suspend(); - } - void Thread::resume() { - assert(joinable()); - _impl->resume(); - } - Thread& Thread::operator = (Thread&& other) noexcept { - return moveTask(other); - } - const char* Thread::getName() const { - assert(joinable()); - return _impl->getName(); - } - - Thread& Thread::moveTask(Thread& other) { - assert(!joinable()); - _impl = std::move(other._impl); - other._impl = nullptr; - return *this; - } - -} //LFramework diff --git a/Dependencies/LFramework/Src/LFramework/Threading/Thread.h b/Dependencies/LFramework/Src/LFramework/Threading/Thread.h deleted file mode 100644 index 8612395..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/Thread.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include - -namespace LFramework::Threading { - -enum class ThreadPriority{ - Idle, - Low, - BelowNormal, - Normal, - AboveNormal, - High, - Realtime, - Error -}; - -class Thread { -public: - using ID = ThreadID; - - explicit Thread(const char* name, size_t stackSize, ThreadPriority priority, std::function&& func); - - ~Thread(); - Thread() noexcept; - Thread(const Thread&) = delete; - Thread(Thread&& other) noexcept; - - Thread& operator = (const Thread&) = delete; - Thread& operator = (Thread&& other) noexcept; - - void swap(Thread& other); - - bool joinable() const noexcept; - void join(); - //TODO: detach - - ID getId() const noexcept; - //NativeHandleType nativeHandle() const noexcept; - - const char* getName() const; - - ThreadPriority getPriority() const; - void setPriority(ThreadPriority priority) const; - - void suspend(); - void resume(); -private: - class Impl; - Thread& moveTask(Thread& other); - Impl* _impl = nullptr; -}; - -namespace ThisThread { - Thread::ID getId(); - ThreadPriority getPriority(); - void setPriority(ThreadPriority priority); - void sleepForMs(size_t milliseconds); -} - -} diff --git a/Dependencies/LFramework/Src/LFramework/Threading/ThreadFreeRTOS.h b/Dependencies/LFramework/Src/LFramework/Threading/ThreadFreeRTOS.h deleted file mode 100644 index 123ecf5..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/ThreadFreeRTOS.h +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once -#include -#include "../Detect/DetectOS.h" - - -#if LF_TARGET_OS == LF_OS_FREERTOS -#include -#include "task.h" -#endif - - -namespace LFramework::Threading { - -#if LF_TARGET_OS == LF_OS_FREERTOS - static Thread::ID makeThreadId(TaskHandle_t handle) { - return reinterpret_cast(handle); - } - - static ThreadPriority makeThreadPriority(portBASE_TYPE osPriority) { - return static_cast(osPriority); - } - - static portBASE_TYPE makeOsPriority(ThreadPriority priority) { - return static_cast(priority); - } - - - class Thread::Impl { - public: - explicit Impl(const char* name, size_t stackSize, ThreadPriority priority, std::function&& body) :_body(std::move(body)) { - xTaskCreate(&Impl::staticTaskHandler, name, stackSize, this, (UBaseType_t)priority, &_rtosTaskHandle); - } - - void join(){ - _joinSemaphore.take(); - } - - Thread::ID getId() const { - return makeThreadId(_rtosTaskHandle); - } - - TaskHandle_t getNativeHandle() const { - return _rtosTaskHandle; - } - - const char* getName() const { - return pcTaskGetTaskName(_rtosTaskHandle); - } - void suspend() { - vTaskSuspend(_rtosTaskHandle); - } - void resume() { - vTaskResume(_rtosTaskHandle); - } - ThreadPriority getPriority() const { - return makeThreadPriority(uxTaskPriorityGet(_rtosTaskHandle)); - } - void setPriority(ThreadPriority priority) const { - vTaskPrioritySet(_rtosTaskHandle, makeOsPriority(priority)); - } - private: - static void staticTaskHandler(void* param) { - Impl* _this = (Impl*)param; - _this->taskHandler(); - } - void taskHandler() { - _body(); - assert(_joinSemaphore.give()); - vTaskDelete(xTaskGetCurrentTaskHandle()); - } - TaskHandle_t _rtosTaskHandle = nullptr; - std::function _body; - Threading::BinarySemaphore _joinSemaphore; - }; - - - namespace ThisThread { - Thread::ID getId() { - return makeThreadId(xTaskGetCurrentTaskHandle()); - } - ThreadPriority getPriority() { - return makeThreadPriority(uxTaskPriorityGet(xTaskGetCurrentTaskHandle())); - } - void setPriority(ThreadPriority priority) { - vTaskPrioritySet(xTaskGetCurrentTaskHandle(), makeOsPriority(priority)); - } - void sleepForMs(size_t milliseconds){ - vTaskDelay(milliseconds); - } - } -#endif -} diff --git a/Dependencies/LFramework/Src/LFramework/Threading/ThreadPlatform.h b/Dependencies/LFramework/Src/LFramework/Threading/ThreadPlatform.h deleted file mode 100644 index 8562051..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/ThreadPlatform.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include "../Detect/DetectOS.h" - -#if LF_TARGET_OS == LF_OS_FREERTOS - #include "FreeRTOS.h" - #include "task.h" - -namespace LFramework::Threading { - using ThreadID = TaskHandle_t; -} -#else -#include -namespace LFramework::Threading { - using ThreadID = std::thread::id; -} -#endif diff --git a/Dependencies/LFramework/Src/LFramework/Threading/ThreadStd.h b/Dependencies/LFramework/Src/LFramework/Threading/ThreadStd.h deleted file mode 100644 index 08b1259..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/ThreadStd.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#if defined(LF_THREAD_STD) - -#include -#include -#include -#include - -namespace LFramework::Threading { - class Thread::Impl { - public: - explicit Impl(const char* name, size_t stackSize, ThreadPriority priority, std::function&& body):_name(name){ - _thread = std::thread(body); - } - void join() { - _thread.join(); - } - Thread::ID getId() const { - return _thread.get_id(); - } - const char* getName() const { - return _name.c_str(); - } - void suspend() { - - } - void resume() { - - } - ThreadPriority getPriority() const { - return ThreadPriority::Normal; - } - void setPriority(ThreadPriority priority) const { - - } - private: - std::string _name; - std::thread _thread; - }; - - namespace ThisThread { - inline Thread::ID getId() { - return std::this_thread::get_id(); - } - void sleepForMs(size_t milliseconds) { - - std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); - } - /*ThreadPriority getPriority() { - return Private::makeThreadPriority(uxTaskPriorityGet(xTaskGetCurrentTaskHandle())); - } - void setPriority(ThreadPriority priority) { - vTaskPrioritySet(xTaskGetCurrentTaskHandle(), Private::makeOsPriority(priority)); - }*/ - } -} - -#endif - diff --git a/Dependencies/LFramework/Src/LFramework/Threading/ThreadTest.cpp b/Dependencies/LFramework/Src/LFramework/Threading/ThreadTest.cpp deleted file mode 100644 index c808dd1..0000000 --- a/Dependencies/LFramework/Src/LFramework/Threading/ThreadTest.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include "../UnitTest/UnitTest.h" - -#ifdef LF_THREADING - -using namespace LFramework::Threading; - -void test(int& counter) { - counter = 100500; -} - -TEST(Thread_Create) { - int counter = 0; - Thread t; - TEST_TRUE(t.joinable() == false); - - t = Thread("123", 123, ThreadPriority::Normal, [&](){ - test(counter); - }); - t.join(); - - TEST_TRUE(counter == 100500); - TEST_TRUE(!t.joinable()); -} - -#endif diff --git a/Dependencies/LFramework/Src/LFramework/Time/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/Time/CMakeLists.txt deleted file mode 100644 index 296c79a..0000000 --- a/Dependencies/LFramework/Src/LFramework/Time/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -target_sources(${PROJECT_NAME} -INTERFACE - Stopwatch.h -) - - diff --git a/Dependencies/LFramework/Src/LFramework/Time/Stopwatch.h b/Dependencies/LFramework/Src/LFramework/Time/Stopwatch.h deleted file mode 100644 index 88c72da..0000000 --- a/Dependencies/LFramework/Src/LFramework/Time/Stopwatch.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef Stopwatch_h__ -#define Stopwatch_h__ - -#include -#include - -namespace LFramework { - class Stopwatch { - public: - Stopwatch() { - Reset(); - } - typedef std::chrono::high_resolution_clock clock_t; - - void Reset() { - _startTime = clock_t::now(); - } - clock_t::duration Check() { - _lastDelta = clock_t::now() - _startTime; - return _lastDelta; - } - std::chrono::milliseconds CheckMs() { - return std::chrono::duration_cast(Check()); - } - clock_t::duration GetLastDelta() { - return _lastDelta; - } - private: - clock_t::time_point _startTime; - clock_t::duration _lastDelta; - }; -} - -#endif // Stopwatch_h__ \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/TupleUtils.h b/Dependencies/LFramework/Src/LFramework/TupleUtils.h deleted file mode 100644 index 446e5b7..0000000 --- a/Dependencies/LFramework/Src/LFramework/TupleUtils.h +++ /dev/null @@ -1,318 +0,0 @@ -#ifndef TUPLEUTILS_H -#define TUPLEUTILS_H - -#include -#include - -namespace LFramework { - - -template -struct Tuple; - -template <> -struct Tuple<> {}; - -template -struct Tuple{ - T first; - Tuple rest; - constexpr Tuple() = default; - template ::type>::value>::type> - constexpr Tuple(U&& u, Us&&...tail) : first(::std::forward(u)), rest(::std::forward(tail)...) {} -}; - -template -struct Tuple{ - T first; - constexpr Tuple() = default; - template ::type>::value>::type> - constexpr Tuple(U&& u) : first(::std::forward(u)) {} -}; - -template -struct IsTuple : std::false_type {}; - -template -struct IsTuple> : std::true_type {}; - - -#pragma pack(push, 1) -template -struct PackedTuple; - -template <> -struct PackedTuple<> {}; - -template -struct PackedTuple{ - T first; - Tuple rest; - PackedTuple() = default; - template ::type>::value>::type> - PackedTuple(U&& u, Us&&...tail) : first(::std::forward(u)), rest(::std::forward(tail)...) {} -}; - -template -struct PackedTuple{ - T first; - PackedTuple() = default; - template ::type>::value>::type> - PackedTuple(U&& u) : first(::std::forward(u)) {} -}; -#pragma pack(pop) - -template -struct IsPackedTuple : std::false_type {}; - -template -struct IsPackedTuple> : std::true_type {}; - - -namespace details { - template - auto& Get(Tuple& t) { - if constexpr (Index == CurrentIndex) { - return t.first; - } - else if constexpr (sizeof...(Types) > 1) { - return details::Get(t.rest); - } - else { - static_assert(sizeof(t) == 0, "Invalid tuple index"); - } - } -} - -template -struct tupleSizeHelper { - static constexpr size_t size = 0; -}; - -template -struct tupleSizeHelper> { - static constexpr size_t size = sizeof...(T); -}; - - - -template -constexpr size_t tupleSize = tupleSizeHelper::size; - - -template -auto& Get(Tuple& t) { - return details::Get(t); -} - - -namespace details { - template - auto& Get(PackedTuple& t) { - if constexpr (Index == CurrentIndex) { - return t.first; - } - else if constexpr (sizeof...(Types) > 1) { - return details::Get(t.rest); - } - else { - static_assert(sizeof(t) == 0, "Invalid tuple index"); - } - } -} - -template -auto& Get(PackedTuple& t) { - return details::Get(t); -} - -struct TupleSkipType {}; - -struct TupleStepInType {}; - -namespace details { - template - auto tupleCatImpl(Tuple done, Tuple t) { - return Tuple{}; - }; - - - template - using tupleCat = decltype(tupleCatImpl(std::declval(), std::declval())); - - template - auto tupleSelectImpl(F f, const Tuple& tuple, const Tuple& intermediate) { - if constexpr(sizeof...(T) > 1) { - using SelectedType = decltype(f(tuple.first)); - - if constexpr (std::is_same_v) { - return tupleCat())), decltype(tupleSelectImpl(f, tuple.rest, Tuple()))>{}; - }else if constexpr (std::is_same_v) { - return tupleSelectImpl(f, tuple.rest, Tuple()); - } - else { - return tupleSelectImpl(f, tuple.rest, Tuple()); - } - } - else { - using SelectedType = decltype(f(tuple.first)); - if constexpr (std::is_same_v) { - return tupleSelectImpl(f, tuple.first, Tuple<>()); - } - else if constexpr (std::is_same_v) { - return Tuple(); - } - else { - return Tuple(); - } - } - } - - template - auto tupleSelectType_(F f, const Tuple& tuple) { - return tupleSelectImpl(f, tuple, Tuple<>{}); - } - - - - - template - using tupleAppendFront = tupleCat, B>; - - template - using tupleAppendBack = tupleCat>; - - - template - struct tupleFlattenImpl { - using type = Tuple<>; - }; - - template - struct tupleFlattenImpl { - using type = tupleAppendFront::type>; - }; - - template - struct tupleFlattenImpl { - using type = Tuple; - }; - - template - struct tupleFlattenImpl, T...> { - using type = tupleCat::type, typename tupleFlattenImpl::type>; - }; - - template - auto tupleFlatten_(const Tuple& tuple) { - return typename tupleFlattenImpl::type{}; - } -} - - - -template -struct tupleSelectTypeHelp { - typedef decltype(details::tupleSelectType_(std::declval(), std::declval())) type; -}; - -template -using tupleSelectType = typename tupleSelectTypeHelp::type; - - -template -using tupleFlatten = decltype(details::tupleFlatten_(std::declval())); - -template -struct TupleTypeSelector { - template - auto operator () (const T& t) { - if constexpr (IsTuple::value) { - if constexpr (Recurse) { - return TupleStepInType{}; - } - else { - return TupleSkipType{}; - } - } - else { - if constexpr (std::is_base_of_v) { - return T{}; - } - else { - return TupleSkipType{}; - } - } - - } -}; - -namespace details { - template - auto tupleSelectImpl(F f, PackedTuple tuple, PackedTuple intermediate) { - if constexpr(sizeof...(T) > 1) { - return tupleSelectImpl(f, tuple.rest, PackedTuple()); - } - else { - return PackedTuple(); - } - } - - template - auto tupleSelectType_(F f, PackedTuple tuple) { - return tupleSelectImpl(f, tuple, PackedTuple<>{}); - } -} - -template -using packedTupleSelectType = decltype(details::tupleSelectType_(std::declval(), std::declval())); - - - - - - - - - -template -void forEach(T&& t, F f, std::index_sequence) { - auto l = { (f(std::get(t)), 0)... }; -} - -template -void forEachIndexed(T&& t, F f, std::index_sequence) { - auto l = { (f(std::get(t), Is), 0)... }; -} - -template -void forEachInTuple(std::tuple const& t, F f) { - forEach(t, f, std::index_sequence_for()); -} - -template -void forEachInTupleIndexed(std::tuple const& t, F f) { - forEachIndexed(t, f, std::index_sequence_for()); -} - -template -bool executeOnIndex(std::tuple& t, int id, Functor f) { - if constexpr (ID < sizeof...(Types)) { - if (id == ID) { - f(std::get(t)); - return true; - } - else { - return executeOnIndex(t, id, f); - } - } - else { - return false; - } -} - -} - - - -#endif // TUPLEUTILS_H diff --git a/Dependencies/LFramework/Src/LFramework/TypeTraits/FunctionTraits.h b/Dependencies/LFramework/Src/LFramework/TypeTraits/FunctionTraits.h deleted file mode 100644 index 99a5cf7..0000000 --- a/Dependencies/LFramework/Src/LFramework/TypeTraits/FunctionTraits.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include - -namespace LFramework { - -template -struct FunctionTraits; - -template -struct FunctionTraits { - using ReturnType = R; - - static constexpr std::size_t Arity = sizeof...(Args); - - template - struct ArgumentHelper { - static_assert(N < Arity, "error: invalid parameter index."); - using Type = typename std::tuple_element>::type; - }; - - template - using Argument = typename ArgumentHelper::Type; -}; - -// function pointer -template -struct FunctionTraits : public FunctionTraits { -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/TypeTraits/Integral.h b/Dependencies/LFramework/Src/LFramework/TypeTraits/Integral.h deleted file mode 100644 index 13a42a8..0000000 --- a/Dependencies/LFramework/Src/LFramework/TypeTraits/Integral.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace LFramework::TypeTraits::Integral { - - template>> - static constexpr std::size_t digitsCount(T value) { - return value == 0 ? 0 : 1 + digitsCount(value / 10); - } - - template - static constexpr std::size_t digitsCountBase10(T value) { - std::size_t result = 0; - while (value != 0) { - ++result; - value /= 10; - } - return result; - } - - template>> - static constexpr std::size_t maxDigitsCount() { - return (::std::max)(digitsCount((::std::numeric_limits::min)()), digitsCount((::std::numeric_limits::max)())); - } - - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/USB/CMakeLists.txt deleted file mode 100644 index 1aa9d3a..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ - - -add_library(LFrameworkUsb INTERFACE ) -add_library( LFramework::Usb ALIAS LFrameworkUsb ) - -target_sources(LFrameworkUsb -INTERFACE - USBDevice_Deprecated.h - usbd_conf.h - UsbEndpoint.h - UsbException.h - UsbInterface.h - UsbMicrosoftTypes.h - UsbPollingTransfer.h - UsbTransfer.h - USBTypes.h - USBTypesTest.cpp -) - -add_subdirectory(Device) -add_subdirectory(Host) - - -target_include_directories(LFrameworkUsb -INTERFACE - . -) diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/USB/Device/CMakeLists.txt deleted file mode 100644 index 5e4fe6b..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -add_library(LFrameworkUsbDevice INTERFACE ) -add_library(LFramework::Usb::Device ALIAS LFrameworkUsbDevice ) - -target_sources(LFrameworkUsbDevice -INTERFACE - UsbDBulkInterface.h - UsbDDeviceContext.h - UsbDEndpoint.h - UsbDDevice.h - UsbDInterface.h - - UsbDEndpoint.cpp - USBDDevice.cpp - UsbDLowLevel.cpp - UsbDDeviceCallbacks.cpp -) - - -target_compile_definitions(LFrameworkUsbDevice -INTERFACE - USBD_SUPPORT_USER_STRING_DESC=1 -) - -target_include_directories(LFrameworkUsbDevice -INTERFACE - . -) \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/USBDDevice.cpp b/Dependencies/LFramework/Src/LFramework/USB/Device/USBDDevice.cpp deleted file mode 100644 index 545bfcd..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/USBDDevice.cpp +++ /dev/null @@ -1,344 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -using namespace LFramework; - -extern "C" { - extern PCD_HandleTypeDef hpcd_USB_OTG_FS; -} - -namespace LFramework::USB { - __attribute__((used)) USBD_HandleTypeDef UsbDevice::hUsbDevice{}; - __attribute__((used)) UsbDDeviceContext* _context = nullptr; - - - - -//For other-speed description -__ALIGN_BEGIN volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc __ALIGN_END { - USB::UsbVersion(2), - USB::UsbClass::Device::UseInterfaceClass(), - 64, - 1, - 0 -}; - -#define USB_VENDOR_CODE_WINUSB 'P' - -__ALIGN_BEGIN volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor __ALIGN_END = { - (uint8_t)USB_VENDOR_CODE_WINUSB -}; - - -extern volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc; -extern volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor; - -__attribute__((used)) std::aligned_storage_t _descriptorsBuffer; - - -UsbDDeviceContext* UsbDevice::getContext(){ - return _context; -} - - - -void hang(){ - while(true){ - asm("nop"); - } -} - - -__attribute__((used)) const USBD_DescriptorsTypeDef UsbDevice::_descriptorsTable = { - &UsbDevice::getDeviceDescriptor, - &UsbDevice::getLangidStrDescriptor, - &UsbDevice::getManufacturerStringDescriptor, - &UsbDevice::getProductStringDescriptor, - &UsbDevice::getSerialStringDescriptor, - &UsbDevice::getConfigStringDescriptor, - &UsbDevice::getInterfaceStringDescriptor -}; - -__attribute__((used)) const USBD_ClassTypeDef UsbDevice::_usbClassBinding = { - &UsbDevice::coreInit, - &UsbDevice::coreDeinit, - &UsbDevice::coreSetup, - 0, //USBD_NDC_EP0_TxReady, - &UsbDevice::coreEp0RxReady, - &UsbDevice::coreDataIn, - &UsbDevice::coreDataOut, - &UsbDevice::coreSof, - &UsbDevice::coreIsoInIncomplete, - &UsbDevice::coreIsoOutIncomplete, - &UsbDevice::coreGetCfgDesc, - &UsbDevice::coreGetCfgDesc, - &UsbDevice::coreGetCfgDesc, - &UsbDevice::coreGetDeviceQualifierDesc, - &UsbDevice::coreGetUserStringDesc -}; - - -uint8_t UsbDevice::coreInit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){ - //TODO: use configuration id - for(size_t i = 0; i < _context->getInterfaceCount(); ++i){ - auto interface = _context->getInterface(i); - if(interface != nullptr){ - if(!interface->init(pdev)){ - return USBD_FAIL; - } - } - } - return USBD_OK; -} - - -uint8_t UsbDevice::coreDeinit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){ - //TODO: use configuration id - - for(size_t i = 0; i < _context->getInterfaceCount(); ++i){ - auto interface = _context->getInterface(i); - if(interface != nullptr){ - if(!interface->deinit(pdev)){ - //return USBD_FAIL; - } - } - } - return USBD_OK; -} - -uint8_t UsbDevice::coreImplSetup(USBD_SetupReqTypedef request, void* data){ - switch ( request.bmRequest & USB_REQ_RECIPIENT_MASK ){ - case USB_REQ_RECIPIENT_INTERFACE:{ - if(_context != nullptr){ - auto* interface = _context->getInterface(request.wValue); - if(interface != nullptr){ - hang(); - /*if(interface->control(&hUsbDevice, request.bRequest, (uint8_t*)data, request.wLength)){ - return USBD_OK; - }*/ - } - } - break; - } - - case USB_REQ_RECIPIENT_ENDPOINT: - hang(); - /*if(_usb_device_context != nullptr){ - if(request.bRequest == USB_REQ_CLEAR_FEATURE){ //reset pipe is called at host side - //do reset pipe - if(_clearFeatureCallback != nullptr){ - _clearFeatureCallback(request.wIndex); - } - } - }*/ - break; - case USB_REQ_RECIPIENT_DEVICE: - default: - break; - } - return USBD_OK; -} - - -uint8_t UsbDevice::coreSetup(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef *req){ - hang(); - /*if (req->wLength){ - //Request with data stage{ - if((req->bmRequest & USB_REQ_DATA_PHASE_MASK) == USB_REQ_DATA_PHASE_DEVICE_TO_HOST){ - //device to host data stage => handler should send data - return coreImplSetup(*req, 0); - }else{ //host to device data stage! Can't execute now, read data first & execute later in Ep0Receive callback - last_request = *req; - USBD_CtlPrepareRx (pdev, (uint8_t*)&ep0Buffer[0], req->wLength); - } - } else {//No data stage => simple request => execute now - return coreImplSetup(*req, 0); - }*/ - return USBD_OK; -} - - - -uint8_t UsbDevice::coreEp0RxReady(USBD_HandleTypeDef* pdev){ - hang(); - //coreImplSetup(last_request, &ep0Buffer[0]); //data in stage complete => execute request - //last_request.bRequest = 0xff; - return USBD_OK; -} - - - -UsbDInterface* UsbDevice::findInterfaceByEndpointAddress(uint8_t address){ - if(_context == nullptr){ - return nullptr; - } - auto if_cnt = _context->getInterfaceCount(); - for(uint32_t i = 0; i < if_cnt; ++i){ - auto interface = _context->getInterface(i); - if(interface != nullptr){ - auto endpoint = interface->getEndpoint(address); - if(endpoint != nullptr){ - return interface; - } - } - } - return nullptr; -} - - - -uint8_t UsbDevice::coreDataIn(USBD_HandleTypeDef* pdev, uint8_t epnum){ - auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeIn(epnum));//TODO: cleanup - if(interface != nullptr){ - interface->txComplete(epnum | 0x80); - } - return USBD_OK; -} -uint8_t UsbDevice::coreDataOut(USBD_HandleTypeDef* pdev, uint8_t epnum){ - - uint32_t rxLen = USBD_LL_GetRxDataSize (pdev, epnum); - auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeOut(epnum)); - if(interface != nullptr){ - interface->rxComplete(rxLen, epnum); - } - return USBD_OK; -} -uint8_t UsbDevice::coreSof(USBD_HandleTypeDef* pdev){ - hang(); - return USBD_OK; -} - -uint8_t UsbDevice::coreIsoInIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){ - hang(); - return USBD_OK; -} - -uint8_t UsbDevice::coreIsoOutIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){ - hang(); - return USBD_OK; -} - -uint8_t* UsbDevice::coreGetCfgDesc(uint16_t* length){ - auto* mem = reinterpret_cast(&_descriptorsBuffer); - auto* buffer = mem; - USB::ConfigurationDescriptor* cd = new(buffer) USB::ConfigurationDescriptor(); - cd->wTotalLength = 0; - cd->bNumInterfaces = (uint8_t)_context->getInterfaceCount(); - cd->bConfigurationValue = 0x01; - cd->iConfiguration = USBD_IDX_CONFIG_STR; - cd->bmAttributes = USB::UsbAttributes().value; - cd->bMaxPower = 500; - buffer += sizeof(USB::ConfigurationDescriptor); - - for(uint32_t i = 0; i < _context->getInterfaceCount(); ++i){ - auto emptySize = (mem + sizeof(_descriptorsBuffer)) - buffer; - auto size = _context->getInterface(i)->getDescriptor(buffer, emptySize, i); - buffer += size; - cd->wTotalLength += size; - } - cd->wTotalLength += sizeof(USB::ConfigurationDescriptor); - - *length = cd->wTotalLength; - return reinterpret_cast(&_descriptorsBuffer); -} - - -uint8_t* UsbDevice::getDeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ - auto mem = reinterpret_cast(&_descriptorsBuffer); - auto& desc = *new(mem) USB::DeviceDescriptor(); - *length = sizeof(USB::DeviceDescriptor); - - desc.bcdUSB = 0x0200; - desc.classDescription = USB::UsbClassDescriptor(0,0,0); - desc.bMaxPacketSize0 = 64; - desc.idVendor = 0x0301; - desc.idProduct = 0x1111; - desc.bcdDevice = USB::UsbVersion(2); - desc.iManufacturer = USBD_IDX_MFC_STR; - desc.iProduct = USBD_IDX_PRODUCT_STR; - desc.iSerialNumber = USBD_IDX_SERIAL_STR; - desc.bNumConfigurations = 1; - return reinterpret_cast(&desc); -} - -struct USBDDummyClassData{ - uint32_t reserved; -}; - - - -__attribute__((used)) static USBDDummyClassData _classData = {}; - -void UsbDevice::start(UsbDDeviceContext* context){ - _context = context; - - hUsbDevice.pClassData = &_classData; //Otherwise USBD_Reset handler would not disable interfaces (( - //hUsbDevice.pClassData = nullptr; //Init? - hUsbDevice.dev_speed = USBD_SPEED_FULL; - - USBD_Init(&hUsbDevice, const_cast(&_descriptorsTable), 0); - - USBD_RegisterClass(&hUsbDevice, const_cast(&_usbClassBinding)); - USBD_Start(&hUsbDevice); - -} -uint8_t* UsbDevice::coreGetDeviceQualifierDesc (uint16_t *length){ - *length = sizeof (USBD_NDC_DeviceQualifierDesc); - return (uint8_t*)&USBD_NDC_DeviceQualifierDesc; -} - -uint8_t* UsbDevice::coreGetUserStringDesc(USBD_HandleTypeDef* pdev, uint8_t index, uint16_t* length){ - *length = 0; - if ( 0xEE == index ){ - *length = sizeof (NDC_StringDescriptor); - return (uint8_t*)&NDC_StringDescriptor; - } - return NULL; -} - -uint8_t* UsbDevice::getLangidStrDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ - auto mem = static_cast(&_descriptorsBuffer); - auto& desc = *new(mem) USB::LanguageIDStringDescriptor<1>(); - *length = sizeof(USB::LanguageIDStringDescriptor<1>); - desc.languages[0] = USB::LanguageID::EnglishUnitedStates; - return reinterpret_cast(&desc); -} -uint8_t* UsbDevice::getManufacturerStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ - return USB::MakeStringDescriptor(_context->manufacturerStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); -} -uint8_t* UsbDevice::getProductStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ - return USB::MakeStringDescriptor(_context->productStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); -} - - -uint8_t* UsbDevice::getSerialStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ - return USB::MakeStringDescriptor(_context->serialStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); -} -uint8_t* UsbDevice::getConfigStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ - return USB::MakeStringDescriptor(_context->configurationStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); -} -uint8_t* UsbDevice::getInterfaceStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ - return USB::MakeStringDescriptor(_context->interfaceStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); -} - - -USBD_StatusTypeDef UsbDevice::interfaceRequest(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef* req){ - uint8_t interface_id = (uint8_t)req->wValue; //TODO: bug! wIndex == interface id - auto interface = _context->getInterface(interface_id); - if(interface == nullptr){ - return USBD_FAIL; - } - return interface->interfaceRequest(pdev, req); -} - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDBulkInterface.h b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDBulkInterface.h deleted file mode 100644 index 9465efd..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDBulkInterface.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include "UsbDInterface.h" -#include - -namespace LFramework::USB { - -class UsbDBulkInterface : public UsbDInterface { -public: - UsbDBulkInterface(){ - _descriptor.bNumEndpoints = 2; - _descriptor.classDescription = USB::UsbClass::Interface::VendorSpecific<0,0>(); - _descriptor.iInterface = USBD_IDX_INTERFACE_STR; - - USB::EndpointDescriptor desc; - desc.bEndpointAddress = USB::EndpointAddress::makeIn(1); - desc.bmAttributes.setType(EndpointType::Bulk); - desc.wMaxPacketSize = 64; - _inEp.emplace(desc); - - desc.bEndpointAddress = USB::EndpointAddress::makeOut(1); - _outEp.emplace(desc); - } - bool init(USBD_HandleTypeDef* pdev) override final { - auto status = UsbDInterface::init(pdev); - - /*if(status &) { - _initListener->onBulkInterfaceInitComplete(); - }*/ - - return status; - } - bool deinit(USBD_HandleTypeDef* pdev) override final { - return UsbDInterface::deinit(pdev); - } - UsbEndpoint* getEndpoint(bool isInEndpoint, uint8_t id)override final { - if(id != 0){ - return nullptr; - } - return isInEndpoint ? &_inEp.value() : &_outEp.value(); - } - const UsbEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) const override final { - if(id != 0){ - return nullptr; - } - return isInEndpoint ? &_inEp.value() : &_outEp.value(); - } - - const USB::InterfaceDescriptor& getInterfaceDescriptor() const override final { - return _descriptor; - } - -private: - USB::InterfaceDescriptor _descriptor; - std::optional _inEp; - std::optional _outEp; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDevice.h b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDevice.h deleted file mode 100644 index 9ea74d1..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDevice.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include -#include "UsbDDeviceContext.h" - -namespace LFramework::USB { - -class UsbDevice { -public: - friend class UsbDEndpoint; - - static void start(UsbDDeviceContext* context); - - static UsbDDeviceContext* getContext(); - - static USBD_StatusTypeDef interfaceRequest(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef* req); - - //Descriptors - static uint8_t* getDeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getLangidStrDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getManufacturerStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getProductStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getSerialStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getConfigStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getInterfaceStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - - //USB device core interface - static uint8_t* coreGetCfgDesc(uint16_t* length); - static uint8_t coreSof(USBD_HandleTypeDef* pdev); - static uint8_t coreIsoInIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum); - static uint8_t coreIsoOutIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum); - static uint8_t coreSetup(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef *req); - static uint8_t coreEp0RxReady(USBD_HandleTypeDef* pdev); - static uint8_t coreDataIn(USBD_HandleTypeDef* pdev, uint8_t epnum); - static uint8_t coreDataOut(USBD_HandleTypeDef* pdev, uint8_t epnum); - static uint8_t* coreGetDeviceQualifierDesc (uint16_t *length); - static uint8_t coreInit(USBD_HandleTypeDef* pdev, uint8_t cfgidx); - static uint8_t coreDeinit(USBD_HandleTypeDef* pdev, uint8_t cfgidx); - static uint8_t* coreGetUserStringDesc(USBD_HandleTypeDef* pdev, uint8_t index, uint16_t* length); - static uint8_t coreImplSetup(USBD_SetupReqTypedef request, void* data); -private: - static UsbDInterface* findInterfaceByEndpointAddress(uint8_t address); - static const USBD_DescriptorsTypeDef _descriptorsTable; - static const USBD_ClassTypeDef _usbClassBinding; - static USBD_HandleTypeDef hUsbDevice; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDeviceCallbacks.cpp b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDeviceCallbacks.cpp deleted file mode 100644 index 9d8d3f8..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDeviceCallbacks.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include -#include - -#include -#include -#include - -using namespace LFramework; - -volatile USB::Microsoft::CompatId::WinUSBFunction _winusbFunctionDescriptor(0); - - -extern "C" USBD_StatusTypeDef USBD_hook_device_request(USBD_HandleTypeDef * pdev, USBD_SetupReqTypedef * req) { - if ((req->bmRequest & USB_REQ_TYPE_MASK) == USB_REQ_TYPE_VENDOR) { - if (req->bRequest == (uint8_t)USB_VENDOR_CODE_WINUSB) { - if (req->wIndex == 0x04) { - USBD_CtlSendData(pdev, (uint8_t*)&_winusbFunctionDescriptor, req->wLength); - return USBD_OK; - } - } - } - return USBD_FAIL; -} -extern "C" USBD_StatusTypeDef USBD_hook_interface_request(USBD_HandleTypeDef * pdev, USBD_SetupReqTypedef * req) { - return USB::UsbDevice::interfaceRequest(pdev, req); -} - - -extern "C" void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef * hpcd) { - USBD_HandleTypeDef* pdev = (USBD_HandleTypeDef*)hpcd->pData; - - //Hack to support WinUSB requests :( - USBD_ParseSetupRequest(&pdev->request, (uint8_t*)hpcd->Setup); - pdev->ep0_state = USBD_EP0_SETUP; - pdev->ep0_data_len = pdev->request.wLength; - - switch (pdev->request.bmRequest & 0x1F) { - case USB_REQ_RECIPIENT_DEVICE: - if (USBD_hook_device_request(pdev, &pdev->request) == USBD_OK) { - return; - } - break; - case USB_REQ_RECIPIENT_INTERFACE: - if (USBD_hook_interface_request(pdev, &pdev->request) == USBD_OK) { - return; - } - break; - } - - USBD_LL_SetupStage((USBD_HandleTypeDef*)hpcd->pData, (uint8_t*)hpcd->Setup); -} - -extern "C" void HAL_PCD_SOFCallback2(PCD_HandleTypeDef * hpcd) { - while (true) { - //asm("nop"); - } -} - - - -extern "C" void HAL_PCD_ResetCallback(PCD_HandleTypeDef * hpcd) { - USBD_SpeedTypeDef speed = USBD_SPEED_FULL; - switch (hpcd->Init.speed) { - case PCD_SPEED_FULL: - speed = USBD_SPEED_FULL; - break; - default: - speed = USBD_SPEED_FULL; - break; - } - USBD_LL_SetSpeed((USBD_HandleTypeDef*)hpcd->pData, speed); - USBD_LL_Reset((USBD_HandleTypeDef*)hpcd->pData); -} - -extern "C" void HAL_PCD_SuspendCallback(PCD_HandleTypeDef * hpcd) { - //Inform USB library that core enters in suspend Mode - if (hpcd->pData != 0) { - USBD_LL_Suspend((USBD_HandleTypeDef*)hpcd->pData); - } - - //Enter in STOP mode - if (hpcd->Init.low_power_enable) { - //Set SLEEPDEEP bit and SleepOnExit of Cortex System Control Register - SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); - } -} - -extern "C" void HAL_PCD_ResumeCallback(PCD_HandleTypeDef * hpcd) { - while (true) { - asm("nop"); - } -} - -extern "C" void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef * hpcd, uint8_t epnum) { - while (true) { - asm("nop"); - } -} - -extern "C" void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef * hpcd, uint8_t epnum) { - while (true) { - asm("nop"); - } -} - -extern "C" void HAL_PCD_ConnectCallback(PCD_HandleTypeDef * hpcd) { - while (true) { - asm("nop"); - } -} - -extern "C" void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef * hpcd) { - while (true) { - asm("nop"); - } -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDeviceContext.h b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDeviceContext.h deleted file mode 100644 index 432cab7..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDDeviceContext.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include "UsbInterface.h" - -#include -#include -#include "UsbDInterface.h" - -namespace LFramework::USB { - -class UsbDDeviceContext { -public: - - UsbDDeviceContext(UsbDInterface* usbInterface) : _interface(usbInterface){} - - size_t getInterfaceCount() { - return 1; - } - UsbDInterface* getInterface(size_t id) { - return _interface; - } - - const char* manufacturerStringDescriptor = nullptr; - const char* productStringDescriptor = nullptr; - const char* serialStringDescriptor = nullptr; - const char* configurationStringDescriptor = nullptr; - const char* interfaceStringDescriptor = nullptr; - -private: - UsbDInterface* _interface = nullptr; - - /*static uint8_t* getDeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getLangidStrDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getManufacturerStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getProductStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getSerialStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getConfigStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length); - static uint8_t* getInterfaceStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* lengt*/ -}; -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDEndpoint.cpp b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDEndpoint.cpp deleted file mode 100644 index 720b362..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDEndpoint.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "UsbDEndpoint.h" -#include "UsbDDevice.h" - -namespace LFramework::USB { - -bool UsbDEndpoint::transferAsync(UsbTransfer* transfer){ - //CriticalSectionLock lock; - - if(transfer == nullptr || _activeTransfer != nullptr || !isOpen()){ - return false; - } - - _activeTransfer = transfer; - - if(getDescriptor().bEndpointAddress.isIn()){ - if(USBD_OK != USBD_LL_Transmit(&UsbDevice::hUsbDevice, getDescriptor().bEndpointAddress.value, (uint8_t*)transfer->buffer, transfer->size)){ - _activeTransfer = nullptr; - return false; - } - }else{ - if(USBD_OK != USBD_LL_PrepareReceive(&UsbDevice::hUsbDevice, getDescriptor().bEndpointAddress.value, (uint8_t*)transfer->buffer, transfer->size)){ - _activeTransfer = nullptr; - return false; - } - } - return true; -} - -void UsbDEndpoint::onTxCompleteIsr(){ - finalizeTransfer(true, 0); -} - -void UsbDEndpoint::onRxCompleteIsr(uint32_t rxLength){ - finalizeTransfer(true, rxLength); -} - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDEndpoint.h b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDEndpoint.h deleted file mode 100644 index b2fb564..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDEndpoint.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#include -#include -#include -#include "../UsbEndpoint.h" -#include "../UsbTransfer.h" - -namespace LFramework::USB { - -class UsbDEndpoint : public UsbEndpoint { -public: - UsbDEndpoint(LFramework::USB::EndpointDescriptor descriptor):UsbEndpoint(descriptor){ - - } - - bool open(USBD_HandleTypeDef *pdev){ - _isOpen = USBD_OK == USBD_LL_OpenEP(pdev, getDescriptor().bEndpointAddress.value, (uint8_t)getDescriptor().bmAttributes.getType(), getDescriptor().wMaxPacketSize); - - //FIX для L0 ядра и подобных. Зачем-то в них эндпоинты запускаются не с NAK статусом -#if defined(STM32F0) - PCD_HandleTypeDef* hpcd = (PCD_HandleTypeDef*)pdev->pData; - if(isInDirection()){ //TX EP - PCD_SET_EP_TX_STATUS(hpcd->Instance, id, USB_EP_TX_NAK); - }else{ - PCD_SET_EP_RX_STATUS(hpcd->Instance, id, USB_EP_RX_NAK); - } -#endif - return _isOpen; - } - - void close(USBD_HandleTypeDef *pdev){ - USBD_LL_CloseEP(pdev, getDescriptor().bEndpointAddress.value); - _isOpen = false; - //finalizeTransfer(false, 0); - } - bool transferAsync(UsbTransfer* transfer); - - bool isOpen() const { - return _isOpen; - } - void onTxCompleteIsr(); - void onRxCompleteIsr(uint32_t rxLength); -protected: - void finalizeTransfer(bool success, uint32_t size){ - if(_activeTransfer != nullptr){ - auto transfer = _activeTransfer; - _activeTransfer = nullptr; - transfer->actualSize = size; - if(transfer->callback != nullptr){ - transfer->callback(transfer, success); - } - } - } -private: - UsbTransfer* _activeTransfer = nullptr; - - bool _isOpen = false; -}; -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDInterface.h b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDInterface.h deleted file mode 100644 index dd66e73..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDInterface.h +++ /dev/null @@ -1,130 +0,0 @@ -#pragma once - -#include "../UsbInterface.h" - -#include "usbd_def.h" -#include -#include -#include -#include - -#include "UsbDEndpoint.h" -#define USB_VENDOR_CODE_WINUSB 'P' - - -namespace LFramework::USB { - -class UsbDInterface : public UsbInterface { -public: - virtual bool init(USBD_HandleTypeDef* pdev) { - - - for(uint32_t i = 0;; ++i){ - auto ep = getEndpoint(false, i); - if(ep == nullptr){ - break; - } - static_cast(ep)->open(pdev); - } - - for(uint32_t i = 0;; ++i){ - auto ep = getEndpoint(true, i); - if(ep == nullptr){ - break; - } - static_cast(ep)->open(pdev); - } - - _isOpen = true; - return true; - } - virtual bool deinit(USBD_HandleTypeDef* pdev) { - for(uint32_t i = 0;; ++i){ - auto ep = getEndpoint(false, i); - if(ep == nullptr){ - break; - } - static_cast(ep)->close(pdev); - } - - for(uint32_t i = 0;; ++i){ - auto ep = getEndpoint(true, i); - if(ep == nullptr){ - break; - } - static_cast(ep)->close(pdev); - } - _isOpen = false; - return true; - } - - uint32_t getDescriptor(uint8_t* buffer, uint32_t bufferSize, uint32_t interface_id) const { - *reinterpret_cast(buffer) = getInterfaceDescriptor(); - buffer += sizeof(LFramework::USB::InterfaceDescriptor); - - for(uint8_t i = 0;; ++i){ - auto ep = getEndpoint(false, i); - if(ep == nullptr){ - break; - } - makeEndpointDescriptor(buffer, ep); - buffer += sizeof(LFramework::USB::EndpointDescriptor); - } - - for(uint8_t i = 0;; ++i){ - auto ep = getEndpoint(true, i); - if(ep == nullptr){ - break; - } - makeEndpointDescriptor(buffer, ep); - buffer += sizeof(LFramework::USB::EndpointDescriptor); - } - - return sizeof(LFramework::USB::InterfaceDescriptor) + getInterfaceDescriptor().bNumEndpoints * sizeof(LFramework::USB::EndpointDescriptor); - } - - Microsoft::Property::InterfaceGuid _interfaceGuidDescriptor; - - USBD_StatusTypeDef interfaceRequest(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef* req) { - if((req->bmRequest & USB_REQ_TYPE_MASK) == USB_REQ_TYPE_VENDOR){ - if(req->bRequest == (uint8_t)USB_VENDOR_CODE_WINUSB){ - if (req->wIndex == 0x05){ - if(req->wLength != 10){ - USBD_CtlSendData (pdev, (uint8_t*)&_interfaceGuidDescriptor, req->wLength); - }else { - USBD_CtlSendData (pdev, (uint8_t*)&_interfaceGuidDescriptor, req->wLength); - } - return USBD_OK; - }else{ - USBD_CtlError(pdev, req); - return USBD_OK; - } - } - } - return USBD_FAIL; - } - - static void makeEndpointDescriptor(uint8_t* buffer, const UsbEndpoint* ep){ - *reinterpret_cast(buffer) = ep->getDescriptor(); - } - - virtual void txComplete(uint8_t epnum) { - auto ep = getEndpoint(USB::EndpointAddress::makeIn(epnum)); - if(ep != nullptr){ - static_cast(ep)->onTxCompleteIsr(); - } - } - virtual void rxComplete(uint32_t rx_length, uint8_t epnum) { - auto ep = getEndpoint(USB::EndpointAddress::makeOut(epnum)); - if(ep != nullptr){ - static_cast(ep)->onRxCompleteIsr(rx_length); - } - } - bool isOpen() const { - return _isOpen; - } -private: - bool _isOpen = false; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDLowLevel.cpp b/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDLowLevel.cpp deleted file mode 100644 index c741b0e..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Device/UsbDLowLevel.cpp +++ /dev/null @@ -1,175 +0,0 @@ -#include -#include -#include -#include "UsbDDevice.h" - -using namespace LFramework::USB; - -extern "C" { - extern PCD_HandleTypeDef hpcd_USB_OTG_FS; -} - -extern "C" USBD_StatusTypeDef halToUsbdStatus(HAL_StatusTypeDef status){ - if(status == HAL_OK){ - return USBD_OK; - }else if(status == HAL_ERROR){ - return USBD_FAIL; - }else if((status == HAL_BUSY) || (status == HAL_TIMEOUT)){ - return USBD_BUSY; - } - return USBD_FAIL; -} - -extern "C" USBD_StatusTypeDef USBD_LL_OpenEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t ep_type, uint16_t ep_mps){ - USBD_StatusTypeDef status = USBD_LL_FlushEP(pdev, ep_addr); - if(status != USBD_OK){ - return status; - } - return HAL_PCD_EP_Open((PCD_HandleTypeDef*)pdev->pData,ep_addr, ep_mps, ep_type) == HAL_OK ? USBD_OK : USBD_FAIL; -} - -USBD_StatusTypeDef USBD_LL_FlushEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr){ -#if defined(STM32L4)//Fix for set start NACK status - PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef *)pdev->pData; - uint32_t USBx_BASE = (uint32_t)hpcd->Instance; - if((ep_addr & 0x80) != 0){ - USBx_INEP(ep_addr & 0x7f)->DIEPCTL |= USB_OTG_DIEPCTL_SNAK; - }else{ - USBx_OUTEP(ep_addr & 0x7f)->DOEPCTL |= USB_OTG_DOEPCTL_SNAK; - } - -#endif - return HAL_PCD_EP_Flush((PCD_HandleTypeDef*)pdev->pData, ep_addr) == HAL_OK ? USBD_OK : USBD_FAIL; -} - -USBD_StatusTypeDef USBD_LL_CloseEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr){ -#if defined(STM32F4) || defined(STM32L4) - PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef *)pdev->pData; - USB_OTG_GlobalTypeDef *USBx = (USB_OTG_GlobalTypeDef *)hpcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - if((ep_addr & 0x80) != 0){ - USBx_INEP(ep_addr & 0x7f)->DIEPCTL |= USB_OTG_DIEPCTL_EPDIS; - }else{ - USBx_OUTEP(ep_addr & 0x7f)->DOEPCTL |= USB_OTG_DOEPCTL_EPDIS; - } -#endif - return HAL_PCD_EP_Close((PCD_HandleTypeDef*)pdev->pData, ep_addr) == HAL_OK ? USBD_OK : USBD_FAIL; -} - -extern "C" USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev){ - return HAL_PCD_Start((PCD_HandleTypeDef*)pdev->pData) == HAL_OK ? USBD_OK : USBD_FAIL; -} - -USBD_StatusTypeDef USBD_LL_Stop (USBD_HandleTypeDef *pdev){ - return HAL_PCD_Stop((PCD_HandleTypeDef*)pdev->pData) == HAL_OK ? USBD_OK : USBD_FAIL; -} - -extern "C" USBD_StatusTypeDef USBD_LL_StallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr){ - return HAL_PCD_EP_SetStall((PCD_HandleTypeDef*)pdev->pData, ep_addr) == HAL_OK ? USBD_OK : USBD_FAIL; -} - -extern "C" USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size){ - return halToUsbdStatus(HAL_PCD_EP_Receive((PCD_HandleTypeDef*)pdev->pData, ep_addr, pbuf, size)); -} - -extern "C" USBD_StatusTypeDef USBD_LL_ClearStallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr){ -/*#if defined(STM32F0) - PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef *)pdev->pData; - PCD_EPTypeDef *ep; - - if ((0x80 & ep_addr) == 0x80){ - ep = &hpcd->IN_ep[ep_addr & 0x7F]; - } - else{ - ep = &hpcd->OUT_ep[ep_addr]; - } - - ep->is_stall = 0; - ep->num = ep_addr & 0x7F; - ep->is_in = ((ep_addr & 0x80) == 0x80); - - __HAL_LOCK(hpcd); - - if (ep->is_in){ - PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); - //PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_NAK); - } else{ - PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); - //PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_NAK); - } - __HAL_UNLOCK(hpcd); -#elif defined(STM32F4) || defined(STM32L4)*/ - HAL_PCD_EP_ClrStall((PCD_HandleTypeDef*)pdev->pData, ep_addr); - //HAL_PCD_EP_ClrStall_Ex((PCD_HandleTypeDef*)pdev->pData, ep_addr); -/*#else - -#error "Not supported controller" -#endif*/ - return USBD_OK; -} - -extern "C" uint8_t USBD_LL_IsStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr){ - PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef*)pdev->pData; - if((ep_addr & 0x80) == 0x80){ - return hpcd->IN_ep[ep_addr & 0x7F].is_stall; - } else{ - return hpcd->OUT_ep[ep_addr & 0x7F].is_stall; - } -} - - - -extern "C" USBD_StatusTypeDef USBD_LL_SetUSBAddress (USBD_HandleTypeDef *pdev, uint8_t dev_addr){ - return halToUsbdStatus(HAL_PCD_SetAddress((PCD_HandleTypeDef*)pdev->pData, dev_addr)); -} - -extern "C" USBD_StatusTypeDef USBD_LL_Transmit(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size){ - return halToUsbdStatus(HAL_PCD_EP_Transmit((PCD_HandleTypeDef*)pdev->pData, ep_addr, pbuf, size)); -} - -extern "C" uint32_t USBD_LL_GetRxDataSize (USBD_HandleTypeDef *pdev, uint8_t ep_addr){ - return HAL_PCD_EP_GetRxCount((PCD_HandleTypeDef*)pdev->pData, ep_addr); -} - -extern "C" void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum){ - USBD_LL_DataOutStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->OUT_ep[epnum].xfer_buff); -} - -extern "C" void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum){ - USBD_LL_DataInStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->IN_ep[epnum].xfer_buff); -} - -extern "C" USBD_StatusTypeDef USBD_LL_Init (USBD_HandleTypeDef* pdev){ - auto* device = UsbDevice::getContext(); - - /* Link the driver to the stack. */ - hpcd_USB_OTG_FS.pData = pdev; - pdev->pData = &hpcd_USB_OTG_FS; - - hpcd_USB_OTG_FS.Instance = USB_OTG_FS; - hpcd_USB_OTG_FS.Init.dev_endpoints = 6; - hpcd_USB_OTG_FS.Init.speed = PCD_SPEED_FULL; - hpcd_USB_OTG_FS.Init.dma_enable = DISABLE; - hpcd_USB_OTG_FS.Init.phy_itface = PCD_PHY_EMBEDDED; - hpcd_USB_OTG_FS.Init.Sof_enable = DISABLE; - hpcd_USB_OTG_FS.Init.low_power_enable = DISABLE; - hpcd_USB_OTG_FS.Init.lpm_enable = DISABLE; - hpcd_USB_OTG_FS.Init.vbus_sensing_enable = DISABLE; - hpcd_USB_OTG_FS.Init.use_dedicated_ep1 = DISABLE; - if (HAL_PCD_Init(&hpcd_USB_OTG_FS) != HAL_OK) - { - for(;;){ - asm("nop"); - } - } - - HAL_PCDEx_SetRxFiFo(&hpcd_USB_OTG_FS, 0x80); - HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 0, 0x40); - HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 1, 0x80); - - return USBD_OK; -} - -extern "C" USBD_StatusTypeDef USBD_LL_DeInit (USBD_HandleTypeDef *pdev){ - return HAL_PCD_DeInit((PCD_HandleTypeDef*)pdev->pData) == HAL_OK ? USBD_OK : USBD_FAIL; -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/USB/Host/CMakeLists.txt deleted file mode 100644 index 7b8ceeb..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/CMakeLists.txt +++ /dev/null @@ -1,64 +0,0 @@ -add_library(LFrameworkUsbHost INTERFACE ) -add_library(LFramework::Usb::Host ALIAS LFrameworkUsbHost ) - - -target_sources(LFrameworkUsbHost -INTERFACE - IUsbDevice.h - IUsbHostEndpoint.h - IUsbInterface.h - IUsbService.h - IUsbTransfer.h - UsbException.h -) - - -if(CMAKE_SYSTEM_NAME MATCHES "Linux") - -target_sources(LFrameworkUsbHost -INTERFACE - Linux/NetlinkClient.h - Linux/NetlinkClient.cpp - Linux/NetlinkReader.h - Linux/UsbService.h - Linux/UsbService.cpp - Linux/UsbDevice.h - Linux/UsbDevice.cpp - Linux/UsbInterface.h - Linux/UsbHostEndpoint.h - Linux/UsbHostEndpoint.cpp - Linux/UsbIoctl.h - Linux/UsbBulkTransfer.h -) - -endif() - - -if(CMAKE_SYSTEM_NAME MATCHES "Windows") - -target_link_libraries(LFrameworkUsbHost -INTERFACE - Winusb - #User32 - #Advapi32 - #Ole32 - SetupAPI -) - - -target_sources(LFrameworkUsbHost -INTERFACE - Windows/USBHDevice.cpp - Windows/UsbHDevice.h - Windows/UsbHostEndpoint.h - Windows/UsbHException.h - Windows/UsbHInterface.h - Windows/UsbHostManager.cpp - Windows/UsbHostManager.h - Windows/UsbNotifyWindow.h - Windows/UsbService.cpp - Windows/UsbService.h -) - -endif() - diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbDevice.h b/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbDevice.h deleted file mode 100644 index de6ed66..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbDevice.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include "IUsbInterface.h" -#include -#include - -namespace LFramework::USB { - -class IUsbDevice { -public: - virtual std::shared_ptr getInterface(std::size_t id) = 0; - virtual std::size_t getInterfaceCount() const = 0; -}; - -IUsbDevice* openUsbDevice(const std::string& path); - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbHostEndpoint.h b/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbHostEndpoint.h deleted file mode 100644 index 83b1366..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbHostEndpoint.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "../UsbEndpoint.h" -#include "IUsbTransfer.h" -#include - -namespace LFramework::USB { - -class IUsbHostEndpoint : public UsbEndpoint { -public: - IUsbHostEndpoint(const USB::EndpointDescriptor& descriptor):UsbEndpoint(descriptor){} - virtual ~IUsbHostEndpoint() = default; - virtual std::shared_ptr transferAsync(void* buffer, size_t size) = 0; -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbInterface.h b/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbInterface.h deleted file mode 100644 index 0529892..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbInterface.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "IUsbHostEndpoint.h" - -namespace LFramework::USB { - -class IUsbInterface { -public: - virtual IUsbHostEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) = 0; - virtual const IUsbHostEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) const = 0; - virtual const USB::InterfaceDescriptor& getInterfaceDescriptor() const = 0; -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbService.h b/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbService.h deleted file mode 100644 index fd2428c..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbService.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace LFramework::USB { - -struct UsbDeviceInfo { - std::uint16_t vid; - std::uint16_t pid; - std::string serialNumber; - std::string path; -}; - -class IUsbService { -public: - virtual ~IUsbService() = default; - virtual UsbDeviceInfo getUsbDeviceInfo(const std::string& path) = 0; - virtual std::vector enumerateDevices() = 0; - virtual bool startEventsListening(std::function deviceChangeCallback) = 0; - virtual void stopEventsListening() = 0; -}; - -IUsbService* createUsbService(); - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbTransfer.h b/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbTransfer.h deleted file mode 100644 index 723264b..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/IUsbTransfer.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -namespace LFramework::USB { - -class IUsbTransfer { -public: - virtual ~IUsbTransfer() = default; - virtual std::size_t wait() = 0; -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkClient.cpp b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkClient.cpp deleted file mode 100644 index eccca2f..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkClient.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "NetlinkClient.h" -#include "../UsbException.h" -#include -#include -#include -#include -#include -#include - -#define NL_GROUP_KERNEL 1 - -namespace LFramework::USB { - -NetlinkClient::NetlinkClient() { - sockaddr_nl socketAddressClient = {}; - socketAddressClient.nl_family = AF_NETLINK; - socketAddressClient.nl_groups = NL_GROUP_KERNEL; - auto socketType = SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC; - _socket = socket(PF_NETLINK, socketType, NETLINK_KOBJECT_UEVENT); - if ((_socket < 0) && errno == EINVAL) { - socketType = SOCK_RAW; - _socket = socket(PF_NETLINK, socketType, NETLINK_KOBJECT_UEVENT); - } - - if (_socket < 0){ - throw UsbException(std::string("Failed to create Netlink socket: ") + strerror(errno)); - } - - //set non blocking mode - int flags; - if (!static_cast(socketType & SOCK_NONBLOCK)) { - flags = fcntl(_socket, F_GETFL); - fcntl(_socket, F_SETFL, flags | O_NONBLOCK); - } - - if(bind(_socket, reinterpret_cast(&socketAddressClient), sizeof(socketAddressClient)) < 0) { - close(_socket); - throw UsbException(std::string("Failed to bing Netlink socket: ") + strerror(errno)); - } - - int optValue = 1; - if (setsockopt(_socket, SOL_SOCKET, SO_PASSCRED, &optValue, sizeof(optValue)) < 0) { - close(_socket); - throw UsbException(std::string("Failed to set Netlink socket option: ") + strerror(errno)); - } -} - -NetlinkClient::~NetlinkClient(){ - if(_socket >= 0){ - close(_socket); - } -} - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkClient.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkClient.h deleted file mode 100644 index 40dff11..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkClient.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -namespace LFramework::USB { - -class NetlinkClient { -public: - NetlinkClient(); - ~NetlinkClient(); - int getSocketFileDescriptor() const { - return _socket; - } -private: - int _socket = -1; -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkReader.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkReader.h deleted file mode 100644 index 477d8e1..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/NetlinkReader.h +++ /dev/null @@ -1,200 +0,0 @@ -#pragma once - -#include "NetlinkClient.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace LFramework::USB { - -#define NL_GROUP_KERNEL 1 - -class NetlinkReader { -public: - struct DeviceEvent { - bool removed; - std::uint8_t busNumber; - std::uint8_t deviceNumber; - std::string sysfsFileName; - }; - - using EventCallback = std::function; - - NetlinkReader(std::shared_ptr client, EventCallback callback) : _client(client), _callback(callback){ - _epoll = epoll_create(1); - - epoll_event epollEvent = {}; - epollEvent.events = EPOLLIN | EPOLLERR; - epollEvent.data.fd = client->getSocketFileDescriptor(); - - if(epoll_ctl(_epoll, EPOLL_CTL_ADD, epollEvent.data.fd, &epollEvent) < 0){ - close(_epoll); - throw std::runtime_error("epoll_ctl failed on Netlink socket"); - } - - _isRunning = true; - _pollingThread = std::thread([this](){ - readNetlinkThreadHandler(); - }); - } - - ~NetlinkReader(){ - _isRunning = false; - epoll_ctl(_epoll, EPOLL_CTL_DEL, _client->getSocketFileDescriptor(), nullptr); - close(_epoll); - if(_pollingThread.joinable()){ - _pollingThread.join(); - } - } - -private: - std::shared_ptr _client; - EventCallback _callback; - int _epoll = -1; - std::thread _pollingThread; - bool _isRunning = false; - - - void readNetlinkThreadHandler() { - epoll_event event{}; - while(_isRunning) { - auto epollFileDescriptors = epoll_wait(_epoll, &event, 1, 100); - if(epollFileDescriptors <= 0){ - continue; - } - if (static_cast(event.events & EPOLLIN)){ - std::vector message; - if(readNetlinkMessage(_client->getSocketFileDescriptor(), message)){ - - auto subsystem = getNetlinkVariableValue("SUBSYSTEM", message); - if(!subsystem.has_value() || subsystem.value() != "usb"){ - continue; //Not USB subsystem message - } - - auto devtype = getNetlinkVariableValue("DEVTYPE", message); - if(!devtype.has_value() || (devtype != "usb_device")){ - continue; //Not USB device ? - } - - auto action = getNetlinkVariableValue("ACTION", message); - bool removed = false; - if(!action.has_value()){ - continue; - }else if(action.value() == "remove"){ - removed = true; - }else if(action.value() != "add"){ - continue; //Not interesting message - } - - DeviceEvent event; - event.removed = removed; - - - auto busnum = getNetlinkVariableValue("BUSNUM", message); - if(busnum.has_value()){ - event.busNumber = std::atoi(busnum.value().c_str()); - auto devnum = getNetlinkVariableValue("DEVNUM", message); - if(!devnum.has_value()){ - //Well, this is not expected. Maybe report error here!? - continue; - } - event.deviceNumber = std::atoi(devnum.value().c_str()); - }else{ - //Some old format device path? - - auto devicePath = getNetlinkVariableValue("DEVICE", message); - if(!devicePath.has_value()){ - continue; - } - - auto slashPos = devicePath.value().find_last_of('/'); - auto devNumStr = devicePath.value().substr(slashPos + 1); - auto busNumStr = devicePath.value().substr(slashPos - 3); - - event.busNumber = std::atoi(busNumStr.c_str()); - event.deviceNumber = std::atoi(devNumStr.c_str()); - - } - - auto devicePath = getNetlinkVariableValue("DEVPATH", message); - if(devicePath.has_value()){ - auto slashPos = devicePath.value().find_last_of('/'); - event.sysfsFileName = devicePath.value().substr(slashPos + 1); - }else{ - continue; - } - - if(_callback != nullptr){ - _callback(event); - } - } - } - } - } - - std::optional getNetlinkVariableValue(const char* key, const std::vector& data){ - auto keyLength = strlen(key); - for(const auto& s : data){ - if((strncmp(key, s.c_str(), keyLength) == 0) && (s[keyLength] == '=')){ - return s.substr(keyLength + 1); - } - } - return std::nullopt; - } - - static std::vector parseNetlinkMessageBuffer(const char* buffer, int bufferLength){ - std::vector result; - const char *end = buffer + bufferLength; - - while (buffer < end && *buffer) { - result.push_back(buffer); - buffer += strlen(buffer) + 1; - } - - return result; - } - - bool readNetlinkMessage(int netlinkFd, std::vector& messageData){ - auto result = true; - char buffer[CMSG_SPACE(sizeof(struct ucred))]; - constexpr size_t messageBufferLength = 2048; - char messageBuffer[messageBufferLength]; - sockaddr_nl socketAddress{}; - iovec iov {}; - iov.iov_base = messageBuffer; - iov.iov_len = sizeof(messageBuffer); - msghdr msg{}; - msg.msg_iov = &iov; - msg.msg_iovlen = 1; - msg.msg_control = buffer; - msg.msg_controllen = sizeof(buffer); - msg.msg_name = &socketAddress; - msg.msg_namelen = sizeof(socketAddress); - ssize_t length = recvmsg(netlinkFd, &msg, 0); - if (length == -1 && errno != EAGAIN && errno != EINTR) - result = false; - if ((msg.msg_flags & MSG_TRUNC) != 0) - result = false; - if (socketAddress.nl_groups != NL_GROUP_KERNEL || socketAddress.nl_pid != 0) - result = false; - auto cmsg = CMSG_FIRSTHDR(&msg); - if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS) - result = false; - auto cred = (ucred *)CMSG_DATA(cmsg); - if (cred->uid != 0) - result = false; - if(result) - messageData = parseNetlinkMessageBuffer(messageBuffer, length); - return result; - } -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/SysfsUtils.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/SysfsUtils.h deleted file mode 100644 index 4a22051..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/SysfsUtils.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace LFramework::USB::SysfsUtils { - - inline bool isUsbDeviceName(const std::string& name){ - return !( - std::any_of(name.begin(), name.end(), [](char c){ return std::isalpha(c); }) - || name == "." || name == ".." - || name.find(':') != std::string::npos - || name.find("usb") != std::string::npos); - } - - inline std::string readDeviceAttribute(const std::string &devicePath, const char *attributeName) { - std::string attributeValue = ""; - auto attributeFilePath = devicePath + attributeName; - std::ifstream attributeFile; - attributeFile.open(attributeFilePath); - if(attributeFile.is_open()) { - attributeFile >> attributeValue; - } - attributeFile.close(); - return attributeValue; - } - - template - inline T readIntDeviceAttribute(const std::string &devicePath, const char *attributeName, uint base){ - auto strValue = readDeviceAttribute(devicePath, attributeName); - return static_cast(std::strtol(strValue.c_str(), nullptr, base)); - } -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbBulkTransfer.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbBulkTransfer.h deleted file mode 100644 index eb09d73..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbBulkTransfer.h +++ /dev/null @@ -1,141 +0,0 @@ -#pragma once - -#include "../IUsbTransfer.h" -#include -#include "UsbIoctl.h" -#include -#include -#include - -#include -#include - -namespace LFramework::USB { - -class UsbBulkTransfer : public IUsbTransfer { -public: - - UsbBulkTransfer(int usbDeviceFileDescriptor, std::uint32_t deviceCaps, std::uint8_t endpointAddress, const void* data, std::size_t size) - : _usbDeviceFileDescriptor(usbDeviceFileDescriptor){ - - //std::cout << "BulkTransfer: address = 0x" << std::hex << (uint32_t)endpointAddress << std::dec << " size = " << size << std::endl; - - bool supportsBulkContinuation = (deviceCaps & UsbCaps::BulkContinuation) != 0; - - std::size_t blockSize = calculateMaxUrbSize(deviceCaps, size); - std::size_t urbCount = size == 0 ? 1 : ((size + (blockSize - 1)) / blockSize); - bool isLastUrbPartial = ((size != 0) && (size % blockSize != 0)); - - _urb.reserve(urbCount); - - const std::uint8_t* buffer = reinterpret_cast(data); - - //Create URBs - for(std::size_t i = 0; i < urbCount; ++i){ - - UsbUrb urb = {}; - - urb.userContext = this; - urb.type = UsbUrbType::UsbUrbTypeBulk; - urb.endpoint = endpointAddress; - urb.buffer = const_cast(buffer); - - if(size == 0){ - urb.flags |= UsbUrbFlags::ZeroPacket; - } - - bool isLastUrb = i == (urbCount - 1); - if(((endpointAddress & 0x80) != 0) && !isLastUrb){ - urb.flags |= UsbUrbFlags::ShortNotOk; - } - - //If multiple URBs and bulk continuation supported - if((i != 0) && supportsBulkContinuation){ - urb.flags |= UsbUrbFlags::BulkContinuation; - } - - - if(isLastUrb && isLastUrbPartial){ - urb.bufferLength = static_cast(size % blockSize); - }else { - urb.bufferLength = static_cast((size == 0) ? 0 : blockSize); - } - - - auto ioctlResult = ioctl(_usbDeviceFileDescriptor, IOCTL_USBFS_SUBMITURB, &_urb.emplace_back(urb)); - if(ioctlResult < 0){ - discard(); - throw std::runtime_error("Failed to submit USB URB"); - } - - - buffer += blockSize; - } - } - - void notify(UsbUrb* urb){ - std::lock_guard lock(_urbMutex); - - if(urb->status == 0){ - _finishedBytes += urb->actualLength; - _finishedUrbCount++; - if(_finishedUrbCount == _urb.size()){ - _urbCv.notify_one(); - } - }else{ - _error = true; - discard(); - _urbCv.notify_one(); - } - } - - std::size_t wait() override { - - std::unique_lock lock(_urbMutex); - - while(!_error && (_finishedUrbCount != _urb.size())){ - _urbCv.wait(lock, [this](){ - return _error || (_finishedUrbCount == _urb.size()); - }); - } - - if(_error) { - throw std::runtime_error("UbsBulkTransfer error"); - } - - return _finishedBytes; - } -private: - std::vector _urb; - int _usbDeviceFileDescriptor; - std::size_t _finishedUrbCount = 0; - std::size_t _finishedBytes = 0; - bool _error = false; - - std::mutex _urbMutex; - std::condition_variable _urbCv; - - - void discard() { - auto urbIterator = _urb.begin(); - auto iterator = std::next(urbIterator, _finishedUrbCount); - while (iterator != _urb.end()) { - auto& urb = (*iterator); - ioctl(_usbDeviceFileDescriptor, IOCTL_USBFS_DISCARDURB, &urb); - urb.userContext = nullptr; - iterator++; - } - } - - static std::size_t calculateMaxUrbSize(std::uint32_t deviceCaps, std::size_t fullTransferSize) { - constexpr std::size_t maxBlockSize = 16384; - - if((deviceCaps & (UsbCaps::BulkScatterGather | UsbCaps::NoPacketSizeLim)) != 0){ - return fullTransferSize; - } - - return std::min(maxBlockSize, fullTransferSize); - } -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbDevice.cpp b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbDevice.cpp deleted file mode 100644 index 38a5ac8..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbDevice.cpp +++ /dev/null @@ -1,173 +0,0 @@ -#include "UsbDevice.h" -#include "UsbInterface.h" -#include "SysfsUtils.h" -#include "UsbIoctl.h" -#include "UsbBulkTransfer.h" - -#include - -#include -#include -#include - -#include -#include - -#include - -namespace LFramework::USB { - -static bool fileExist(const std::string &filePath) { - auto result = false; - std::ifstream attributeFile; - attributeFile.open(filePath); - if(attributeFile.is_open()) { - result = true; - } - attributeFile.close(); - return result; -} - - -static void prependZeroes(std::string &str) { - const uint8_t desiredLength = 3; - const auto valueToInsert = '0'; - auto len = static_cast(str.length()); - str.insert(str.begin(), desiredLength - len, valueToInsert); -} - -static std::string getDeviceNodePath(const std::string &path) { - auto busnum = SysfsUtils::readDeviceAttribute(path, "busnum"); - auto devnum = SysfsUtils::readDeviceAttribute(path, "devnum"); - prependZeroes(busnum); - prependZeroes(devnum); - auto nodePath = "/dev/bus/usb/" + busnum + '/' + devnum; - return nodePath; -} - - -UsbDevice::UsbDevice(const std::string& path) { - auto deviceNodePath = getDeviceNodePath(path); - - _deviceFileDescriptor = open(deviceNodePath.c_str(), O_RDWR | O_NONBLOCK | O_ASYNC); - if(_deviceFileDescriptor.value() < 0){ - throw std::runtime_error("Failed to open USB device"); - } - - _epoll.emplace(_deviceFileDescriptor.value(), EPOLLIN | EPOLLOUT | EPOLLERR); - - _deviceCaps = getUsbDeviceCapabilities(_deviceFileDescriptor.value()); - - enumerateInterfaces(path); - - _epollThreadRunning = true; - _epollThread = std::thread([this](){ - epollThreadHandler(); - }); -} - -UsbDevice::~UsbDevice(){ - _interfaces.clear(); - _epoll.reset(); - _deviceFileDescriptor.close(); - _epollThreadRunning = false; - - if(_epollThread.joinable()) { - _epollThread.join(); - } -} - -void UsbDevice::enumerateInterfaces(const std::string& sysfsDevicePath){ - dirent *directoryEntry; - DIR *directory = nullptr; - directory = opendir(sysfsDevicePath.c_str()); - while ((directoryEntry = readdir(directory)) != nullptr) { - if (directoryEntry->d_type != DT_DIR) { - continue; - } - if (!static_cast(isdigit(directoryEntry->d_name[0]))) { - continue; - } - auto interfaceDirectory = std::string(sysfsDevicePath + directoryEntry->d_name + '/'); - auto interfaceClassFilePath = interfaceDirectory + "bInterfaceClass"; - if (!fileExist(interfaceClassFilePath)) { - continue; - } - - _interfaces.push_back(std::make_shared(_deviceFileDescriptor.value(), sysfsDevicePath, interfaceDirectory, _deviceCaps) ); - - //UsbInterfaceParameters interfaceParameters; - //initInterface(interfaceDirectory, &interfaceParameters); - //interfaces.emplace_back(interfaceParameters); - } - closedir(directory); -} - -void UsbDevice::epollThreadHandler(){ - UsbUrb *context = nullptr; - epoll_event event{}; - while(_epollThreadRunning){ - auto readyFileDescriptors = epoll_wait(_epoll->fileDescriptor()->value(), &event, 1, 100); - - //TODO: check if device file descriptor is still valid? - if(readyFileDescriptors < 0){ - int err = errno; - if(err == EINTR){ - continue; - }else{ - break; - } - - } - - if(((event.events & EPOLLERR) != 0) || - (errno == EBADF) || - (errno == EFAULT) || - (errno == EINVAL) ) { - break; - } - - if(errno == EAGAIN) { //Timeout - continue; - } - - if((readyFileDescriptors > 0) && ((event.events & EPOLLOUT) != 0)){ - int urbCompletionStatus = ioctl(_deviceFileDescriptor.value(), IOCTL_USBFS_REAPURB, &context); - - int err = errno; - if(urbCompletionStatus < 0){ - if (errno == EAGAIN) - continue; - if (errno == ENODEV) - continue; - } - - if (context != nullptr) { - auto transfer = static_cast(context->userContext); - if(transfer != nullptr){ - transfer->notify(context); - } - } - } - } - - std::cout << "Device Epoll thread exit" << std::endl; -} - - -std::shared_ptr UsbDevice::getInterface(std::size_t id) { - if(id >= _interfaces.size()){ - throw std::runtime_error("Invalid interface ID"); - } - return _interfaces[id]; -} -std::size_t UsbDevice::getInterfaceCount() const { - return _interfaces.size(); -} - - -IUsbDevice* openUsbDevice(const std::string& path){ - return new UsbDevice(path); -} - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbDevice.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbDevice.h deleted file mode 100644 index 59de63e..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbDevice.h +++ /dev/null @@ -1,100 +0,0 @@ -#pragma once - -#include "../IUsbDevice.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace LFramework::USB { - -struct FileDescriptor { - FileDescriptor() = default; - explicit FileDescriptor(int value) : _value(value){} - FileDescriptor(const FileDescriptor&) = delete; - - FileDescriptor& operator =(int newValue){ - if(_value != newValue){ - close(); - _value = newValue; - } - return *this; - } - - void close() { - if(_value >= 0){ - ::close(_value); - _value = -1; - } - } - - int value() const { - return _value; - } - - ~FileDescriptor() { - close(); - } -private: - int _value = -1; -}; - -struct EpollContext { -public: - EpollContext(int pollTargetDescriptor, uint32_t events) { - _epollFileDescriptor.emplace(epoll_create(1)); - if(_epollFileDescriptor.value().value() < 0) { - throw std::runtime_error("epoll_create failed"); - } - - _epollEvent.events = events; //EPOLLIN | EPOLLOUT | EPOLLERR; - _epollEvent.data.fd = pollTargetDescriptor; - auto epollCtlResult = epoll_ctl(_epollFileDescriptor.value().value(), EPOLL_CTL_ADD, pollTargetDescriptor, &_epollEvent); - - if (epollCtlResult < 0){ - _epollFileDescriptor.reset(); - throw std::runtime_error("epoll_ctl failed"); - } - } - - ~EpollContext() { - epoll_ctl(_epollFileDescriptor.value().value(), EPOLL_CTL_DEL, _epollEvent.data.fd , &_epollEvent); - _epollFileDescriptor.reset(); - } - const std::optional& fileDescriptor() const { - return _epollFileDescriptor; - } -private: - epoll_event _epollEvent = {}; - std::optional _epollFileDescriptor; -}; - - -class UsbDevice : public IUsbDevice { -public: - UsbDevice(const std::string& path); - ~UsbDevice(); - std::shared_ptr getInterface(std::size_t id) override; - std::size_t getInterfaceCount() const override; -private: - FileDescriptor _deviceFileDescriptor; - std::vector> _interfaces; - std::uint32_t _deviceCaps; - - std::thread _epollThread; - std::optional _epoll; - - bool _epollThreadRunning = false; - - void enumerateInterfaces(const std::string& sysfsDevicePath); - - void epollThreadHandler(); - - -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbHostEndpoint.cpp b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbHostEndpoint.cpp deleted file mode 100644 index b1acf3b..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbHostEndpoint.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "UsbHostEndpoint.h" -#include "UsbBulkTransfer.h" -#include - -namespace LFramework::USB { - - -UsbHostEndpoint::UsbHostEndpoint(const USB::EndpointDescriptor& descriptor, int deviceFileDescriptor, std::uint32_t deviceCaps) - :IUsbHostEndpoint(descriptor), _deviceFileDescriptor(deviceFileDescriptor), _deviceCaps(deviceCaps){ - -} - -std::shared_ptr UsbHostEndpoint::transferAsync(void* buffer, size_t size) { - if(getDescriptor().bEndpointAddress.isIn()){ - return readAsync(buffer, size); - }else{ - return writeAsync(buffer, size); - } -} - - -std::shared_ptr UsbHostEndpoint::readAsync(void* buffer, size_t size){ - return std::make_shared(_deviceFileDescriptor, _deviceCaps, getDescriptor().bEndpointAddress.value, buffer, size); -} -std::shared_ptr UsbHostEndpoint::writeAsync(void* buffer, size_t size){ - return std::make_shared(_deviceFileDescriptor, _deviceCaps, getDescriptor().bEndpointAddress.value, buffer, size); -} - - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbHostEndpoint.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbHostEndpoint.h deleted file mode 100644 index 8e05bbb..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbHostEndpoint.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "../IUsbHostEndpoint.h" - -namespace LFramework::USB { - -class UsbHostEndpoint : public IUsbHostEndpoint { -public: - UsbHostEndpoint(const USB::EndpointDescriptor& descriptor, int deviceFileDescriptor, std::uint32_t deviceCaps); - std::shared_ptr transferAsync(void* buffer, size_t size) override; -private: - int _deviceFileDescriptor; - std::uint32_t _deviceCaps; - - std::shared_ptr readAsync(void* buffer, size_t size); - std::shared_ptr writeAsync(void* buffer, size_t size); -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbInterface.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbInterface.h deleted file mode 100644 index 0ba3c54..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbInterface.h +++ /dev/null @@ -1,124 +0,0 @@ -#pragma once - -#include "../IUsbInterface.h" -#include "UsbHostEndpoint.h" -#include -#include "SysfsUtils.h" -#include -#include "UsbIoctl.h" - -#include -#include -#include - -#include -#include - -namespace LFramework::USB { - - -EndpointType toEndpointType(const std::string &endpointTypeStr) { - if(endpointTypeStr == "Bulk"){ - return EndpointType::Bulk; - }else if(endpointTypeStr == "Interrupt"){ - return EndpointType::Interrupt; - }else if(endpointTypeStr == "Control"){ - return EndpointType::Control; - }else if(endpointTypeStr == "Isochronous"){ - return EndpointType::Isochronous; - }else { - throw std::runtime_error("Unknown endpoint type"); - } -} - - -class UsbInterface : public IUsbInterface { -public: - UsbInterface(int deviceFileDescriptor, const std::string& deviceDirPath, const std::string& interfaceDirPath, std::uint32_t deviceCaps) - : _deviceFileDescriptor(deviceFileDescriptor), _deviceDirPath(deviceDirPath), _interfaceDirPath(interfaceDirPath), _deviceCaps(deviceCaps){ - - _descriptor.bAlternateSetting = SysfsUtils::readIntDeviceAttribute(interfaceDirPath, "bAlternateSetting", 16); - _descriptor.bInterfaceNumber = SysfsUtils::readIntDeviceAttribute(interfaceDirPath, "bInterfaceNumber", 16); - _descriptor.bNumEndpoints = SysfsUtils::readIntDeviceAttribute(interfaceDirPath, "bNumEndpoints", 16); - _descriptor.classDescription.classId = SysfsUtils::readIntDeviceAttribute(interfaceDirPath, "bInterfaceClass", 16); - _descriptor.classDescription.protocol = SysfsUtils::readIntDeviceAttribute(interfaceDirPath, "bInterfaceProtocol", 16); - _descriptor.classDescription.subClassId = SysfsUtils::readIntDeviceAttribute(interfaceDirPath, "bInterfaceSubClass", 16); - - //TODO: implement somehow - //_descriptor.iInterface - - claimInterface(_deviceFileDescriptor, _descriptor.bInterfaceNumber); - - enumerateEndpoints(); - } - - ~UsbInterface() { - releaseInterface(_deviceFileDescriptor, _descriptor.bInterfaceNumber); - } - - IUsbHostEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) override{ - return const_cast(getEndpointImpl(isInEndpoint, id)); - } - const IUsbHostEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) const override{ - return getEndpointImpl(isInEndpoint, id); - } - const USB::InterfaceDescriptor& getInterfaceDescriptor() const override{ - return _descriptor; - } -private: - USB::InterfaceDescriptor _descriptor; - int _deviceFileDescriptor; - std::string _deviceDirPath; - std::string _interfaceDirPath; - - std::vector> _inEndpoints; - std::vector> _outEndpoints; - - std::uint32_t _deviceCaps; - - const IUsbHostEndpoint* getEndpointImpl(bool isInEndpoint, uint8_t id) const { - auto& endpoints = isInEndpoint ? _inEndpoints : _outEndpoints; - if(id >= endpoints.size()){ - return nullptr; - } - return endpoints[id].get(); - } - - - void enumerateEndpoints() { - - dirent *dirEntry; - DIR *directory = nullptr; - directory = opendir(_interfaceDirPath.c_str()); - if(directory == nullptr) { - return; - } - while ((dirEntry = readdir(directory)) != nullptr) { - if (dirEntry->d_type != DT_DIR) { - continue; - } - if ((dirEntry->d_name[0] != 'e') || (dirEntry->d_name[1] != 'p') || (dirEntry->d_name[2] != '_')) { - continue; - } - - std::string endpointDirPath = _interfaceDirPath + dirEntry->d_name + "/"; - - USB::EndpointDescriptor endpointDescriptor; - endpointDescriptor.wMaxPacketSize = SysfsUtils::readIntDeviceAttribute(endpointDirPath, "wMaxPacketSize", 16); - endpointDescriptor.bInterval = SysfsUtils::readIntDeviceAttribute(endpointDirPath, "bInterval", 16); - endpointDescriptor.bEndpointAddress = SysfsUtils::readIntDeviceAttribute(endpointDirPath, "bEndpointAddress", 16); - endpointDescriptor.bmAttributes.setType(toEndpointType(SysfsUtils::readDeviceAttribute(endpointDirPath, "type"))); - - if(endpointDescriptor.bEndpointAddress.isIn()){ - _inEndpoints.push_back(std::make_shared(endpointDescriptor, _deviceFileDescriptor, _deviceCaps)); - }else{ - _outEndpoints.push_back(std::make_shared(endpointDescriptor, _deviceFileDescriptor, _deviceCaps)); - } - } - closedir(directory); - - - } -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbIoctl.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbIoctl.h deleted file mode 100644 index d9760e3..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbIoctl.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -#include -#include -#include - -#define IOCTL_USBFS_RESETEP _IOR('U', 3, unsigned int) -#define IOCTL_USBFS_SETCONFIG _IOR('U', 5, unsigned int) -#define IOCTL_USBFS_SUBMITURB _IOR('U', 10, struct UsbUrb) -#define IOCTL_USBFS_DISCARDURB _IO('U', 11) -#define IOCTL_USBFS_REAPURB _IOW('U', 12, void *) -#define IOCTL_USBFS_REAPURBNDELAY _IOW('U', 13, void *) -#define IOCTL_USBFS_CLAIMINTF _IOR('U', 15, unsigned int) -#define IOCTL_USBFS_RELEASEINTF _IOR('U', 16, unsigned int) -#define IOCTL_USBFS_RESET _IO('U', 20) -#define IOCTL_USBFS_CLEAR_HALT _IOR('U', 21, unsigned int) -#define IOCTL_USBFS_DISCONNECT _IO('U', 22) -#define IOCTL_USBFS_CONNECT _IO('U', 23) -#define IOCTL_USBFS_CLAIM_PORT _IOR('U', 24, unsigned int) -#define IOCTL_USBFS_RELEASE_PORT _IOR('U', 25, unsigned int) -#define IOCTL_USBFS_GET_CAPABILITIES _IOR('U', 26, uint32_t) - - -#define USBFS_CAP_ZERO_PACKET 0x01 -#define USBFS_CAP_BULK_CONTINUATION 0x02 -#define USBFS_CAP_NO_PACKET_SIZE_LIM 0x04 -#define USBFS_CAP_BULK_SCATTER_GATHER 0x08 - -namespace LFramework::USB { - -struct UsbIsoPacketDesc { - unsigned int length; - unsigned int actual_length; - unsigned int status; -}; - -namespace UsbCaps { - static constexpr std::uint32_t ZeroPacket = 0x01; - static constexpr std::uint32_t BulkContinuation = 0x02; - static constexpr std::uint32_t NoPacketSizeLim = 0x04; - static constexpr std::uint32_t BulkScatterGather = 0x08; -}; - -enum class UsbUrbType : unsigned char { - UsbUrbTypeIso = 0x0, - UsbUrbTypeInterrupt = 0x1, - UsbUrbTypeControl = 0x2, - UsbUrbTypeBulk = 0x3, -}; - - -namespace UsbUrbFlags { - static constexpr unsigned int ShortNotOk = 0x01; - static constexpr unsigned int BulkContinuation = 0x04; - static constexpr unsigned int QueueBulk = 0x10; - static constexpr unsigned int ZeroPacket = 0x40; -}; - - -struct UsbUrb { - UsbUrb() = default; - UsbUrbType type; - unsigned char endpoint; - int status; - unsigned int flags; - void *buffer; - int bufferLength; - int actualLength; - int startFrame; - int numberOfPackets; - int errorCount; - unsigned int signr; - void *userContext; - struct UsbIsoPacketDesc isoFrameDesc[0]; -}; - - -inline uint32_t getUsbDeviceCapabilities(int usbDeviceFileDescriptor) { - uint32_t result; - auto errorCode = ioctl(usbDeviceFileDescriptor, IOCTL_USBFS_GET_CAPABILITIES, &result); - if (errorCode < 0) { - result = (USBFS_CAP_ZERO_PACKET | USBFS_CAP_BULK_CONTINUATION); - } - return result; -} - - -inline void claimInterface(int usbDeviceFileDescriptor, std::uint8_t interfaceNumber) { - ioctl(usbDeviceFileDescriptor, IOCTL_USBFS_CLAIMINTF, interfaceNumber); -} - -inline void releaseInterface(int usbDeviceFileDescriptor, std::uint8_t interfaceNumber) { - ioctl(usbDeviceFileDescriptor, IOCTL_USBFS_RELEASEINTF, interfaceNumber); -} - - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbService.cpp b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbService.cpp deleted file mode 100644 index eda4635..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbService.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "UsbService.h" - -namespace LFramework::USB { - -IUsbService* createUsbService(){ - return new UsbService(); -} - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbService.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbService.h deleted file mode 100644 index 34bad9a..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Linux/UsbService.h +++ /dev/null @@ -1,121 +0,0 @@ -#pragma once - -#include "../IUsbService.h" -#include "NetlinkClient.h" -#include "NetlinkReader.h" -#include - -#include -#include -#include - -#include -#include - -#include -#include - -#include - -#include "SysfsUtils.h" - -namespace LFramework::USB { - -class UsbService : public IUsbService { -public: - UsbService(){ - - } - UsbDeviceInfo getUsbDeviceInfo(const std::string& path) override { - UsbDeviceInfo result; - - std::string idVendor = SysfsUtils::readDeviceAttribute(path, "idVendor"); - if(idVendor.empty()){ - throw std::runtime_error("Failed to read vendor id"); - } - std::string idProduct = SysfsUtils::readDeviceAttribute(path, "idProduct"); - if(idProduct.empty()){ - throw std::runtime_error("Failed to read product id"); - } - - std::string serial = SysfsUtils::readDeviceAttribute(path, "serial"); - - UsbDeviceInfo info = {}; - info.path = path; - info.vid = std::strtol(idVendor.c_str(), nullptr, 16); - info.pid = std::strtol(idProduct.c_str(), nullptr, 16); - info.serialNumber = serial; - - return info; - } - - - - std::vector enumerateDevices() override { - std::vector result; - dirent *entry = nullptr; - DIR *devices = opendir("/sys/bus/usb/devices/"); - if(devices == nullptr) { - throw std::runtime_error("Failed to open sysfs devices directory"); - } - while ((entry = readdir(devices)) != nullptr) { - std::string deviceName = entry->d_name; - - - if(!SysfsUtils::isUsbDeviceName(deviceName)) { - continue; - } - std::string devicePath = "/sys/bus/usb/devices/" + deviceName + '/'; - - std::string idVendor = SysfsUtils::readDeviceAttribute(devicePath, "idVendor"); - if(idVendor.empty()){ - continue; - } - std::string idProduct = SysfsUtils::readDeviceAttribute(devicePath, "idProduct"); - if(idProduct.empty()){ - continue; - } - - std::string serial = SysfsUtils::readDeviceAttribute(devicePath, "serial"); - - UsbDeviceInfo info = {}; - info.path = devicePath; - info.vid = std::strtol(idVendor.c_str(), nullptr, 16); - info.pid = std::strtol(idProduct.c_str(), nullptr, 16); - info.serialNumber = serial; - - - result.emplace_back(info); - } - closedir(devices); - return result; - } - bool startEventsListening(std::function deviceChangeCallback) override { - try{ - _deviceChangeCallback = deviceChangeCallback; - auto netlinkClient = std::make_shared(); - _netlink = std::make_shared(netlinkClient, [this](const NetlinkReader::DeviceEvent& event){ onUsbEvent(event); }); - return true; - }catch(...){ - _deviceChangeCallback = nullptr; - return false; - } - - - } - void stopEventsListening() override { - _netlink = nullptr; - _deviceChangeCallback = nullptr; - - } - -private: - std::function _deviceChangeCallback; - std::shared_ptr _netlink; - - void onUsbEvent(const NetlinkReader::DeviceEvent& event){ - _deviceChangeCallback(); - } -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/UsbException.h b/Dependencies/LFramework/Src/LFramework/USB/Host/UsbException.h deleted file mode 100644 index 98807be..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/UsbException.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include -#include - -namespace LFramework::USB { - -class UsbException : public std::exception{ -public: - UsbException(const std::string& message):_message(message){ - - } - char const* what() const noexcept override { - return _message.data(); - } -private: - std::string _message; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/USBHDevice.cpp b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/USBHDevice.cpp deleted file mode 100644 index 7a925e2..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/USBHDevice.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include - -#ifdef _WIN32 - -#include "UsbHDevice.h" -#include "../UsbException.h" -//#include "../USBTypes.h" - -namespace LFramework::USB { - -UsbHDevice::UsbHDevice(const std::string& deviceFilePath){ - _deviceHandle = CreateFileA(deviceFilePath.c_str(), - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_WRITE | FILE_SHARE_READ, - nullptr, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, - nullptr); - - if(_deviceHandle == INVALID_HANDLE_VALUE){ - throw UsbException("Failed top open device file"); - } - - enumerateInterfaces(); -} - - -IUsbDevice* openUsbDevice(const std::string& path){ - return new UsbHDevice(path); -} - -} - -#endif - diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHDevice.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHDevice.h deleted file mode 100644 index eaef437..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHDevice.h +++ /dev/null @@ -1,106 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include "UsbHostEndpoint.h" -#include "UsbHInterface.h" -#include - -namespace LFramework::USB { - -class UsbHDevice : public IUsbDevice { -public: - - UsbHDevice(const std::string& deviceFilePath); - std::shared_ptr getInterface(size_t id) { - if(id >= _interfaces.size()){ - return nullptr; - } - return _interfaces[id]; - } - - std::size_t getInterfaceCount() const { - return _interfaces.size(); - } - -private: - HANDLE _deviceHandle; - WINUSB_INTERFACE_HANDLE _interfaceHandle = nullptr; - - void enumerateInterfaces() { - auto result = true; - - if(WinUsb_Initialize(_deviceHandle, &_interfaceHandle) == FALSE){ - throw UsbException("WinUsb_Initialize failed"); - } - - USB_INTERFACE_DESCRIPTOR interfaceDescriptor{}; - UCHAR alternateSetting = 0; - - //TODO: use WinUsb_GetAssociatedInterface to enumerate ALL interfaces - - if(WinUsb_QueryInterfaceSettings(_interfaceHandle, alternateSetting, &interfaceDescriptor) == FALSE){ - throw UsbException("Failed to get interface descriptor"); - } - - USB::InterfaceDescriptor descriptor{}; - descriptor.iInterface = interfaceDescriptor.iInterface; - descriptor.bNumEndpoints = interfaceDescriptor.bNumEndpoints; - descriptor.bInterfaceNumber = interfaceDescriptor.bInterfaceNumber; - descriptor.bAlternateSetting = interfaceDescriptor.bAlternateSetting; - descriptor.classDescription.classId = interfaceDescriptor.bInterfaceClass; - descriptor.classDescription.subClassId = interfaceDescriptor.bInterfaceSubClass; - descriptor.classDescription.protocol = interfaceDescriptor.bInterfaceProtocol; - - _interfaces.push_back(std::make_shared(descriptor, _deviceHandle, _interfaceHandle)); - - /*if (querySettingsResult) { - interfaceParameters->interfaceSubClass = interfaceDescriptor.bInterfaceSubClass; - interfaceParameters->interfaceClass = interfaceDescriptor.bInterfaceClass; - for (UCHAR index = 0; index < interfaceDescriptor.bNumEndpoints; index++) { - auto queryPipeResult = static_cast(WinUsb_QueryPipe(interfaceHandle, 0, index, &pipe)); - if (queryPipeResult ){ - UsbEndpointParameters endpointParameters{}; - - endpointParameters.endpointType = castWinUsbEndpointType(pipe.PipeType); - endpointParameters.maxPacketSize = pipe.MaximumPacketSize; - endpointParameters.interval = pipe.Interval; - endpointParameters.address = pipe.PipeId; - if(USB_ENDPOINT_DIRECTION_IN(pipe.PipeId)){ - interfaceParameters->inEndpoints.push_back(UsbEndpoint(endpointParameters)); - } - else{ - interfaceParameters->outEndpoints.push_back(UsbEndpoint(endpointParameters)); - } - } - } - }*/ - - - /*auto nextInterfaceHandle = interfaceHandle; - UCHAR index = 0; - auto getInterfaceResult = true; - while(getInterfaceResult){ - UsbInterfaceParameters interfaceParameters; - initInterface(nextInterfaceHandle, &interfaceParameters); - interfaces.push_back(UsbInterface(interfaceParameters)); - interfaceHandles.push_back(nextInterfaceHandle); - for (auto &outEndpoint : interfaceParameters.outEndpoints) - endpointsMap.insert(std::make_pair(outEndpoint.getAddress(), index)); - for (auto &inEndpoint : interfaceParameters.inEndpoints) - endpointsMap.insert(std::make_pair(inEndpoint.getAddress(), index)); - getInterfaceResult = static_cast(WinUsb_GetAssociatedInterface(interfaceHandle, ++index, &nextInterfaceHandle)); - }*/ - - - } - -private: - std::vector> _interfaces; -}; - -} - diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHException.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHException.h deleted file mode 100644 index 0cc9279..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHException.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace LFramework::USB { - -class UsbHException : public std::exception{ -public: - UsbHException(const std::string& message):_message(message){ - - } - char const* what() const override { - return _message.data(); - } -private: - std::string _message; -}; - - -class UsbHWinusbErrorCodeException : public UsbHException { -public: - UsbHWinusbErrorCodeException(const std::string& customDescription):UsbHException (customDescription + " " + getErrorText()){ - - } - UsbHWinusbErrorCodeException():UsbHException (getErrorText()){ - - } - static std::string getErrorText(){ - auto errorCode = GetLastError(); - LPSTR messageBuffer = nullptr; - auto messageLength = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, errorCode, - MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), LPSTR(&messageBuffer), 0, nullptr); - - std::string message(messageBuffer, messageLength); - LocalFree(messageBuffer); - return "[" + std::to_string(errorCode) + "] " + message; - } -}; - - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHInterface.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHInterface.h deleted file mode 100644 index b5cfc92..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHInterface.h +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once - -#include "../IUsbInterface.h" -#include -#include -#include -#include -#include "../UsbException.h" -#include "UsbHostEndpoint.h" - -namespace LFramework::USB { - -class UsbHInterface : public IUsbInterface { -public: - UsbHInterface(const USB::InterfaceDescriptor& descriptor, HANDLE device, WINUSB_INTERFACE_HANDLE handle):_descriptor(descriptor), _handle(handle){ - - - for (UCHAR epId = 0; epId < descriptor.bNumEndpoints; epId++) { - WINUSB_PIPE_INFORMATION pipe{}; - if(WinUsb_QueryPipe(_handle, descriptor.bAlternateSetting, epId, &pipe) == FALSE){ - throw UsbException("Failed to query endpoint descriptor"); - } - - USB::EndpointDescriptor endpointDescriptor; - endpointDescriptor.wMaxPacketSize = pipe.MaximumPacketSize; - endpointDescriptor.bInterval = pipe.Interval; - endpointDescriptor.bEndpointAddress = pipe.PipeId; - endpointDescriptor.bmAttributes.setType(static_cast(pipe.PipeType)); - - if(endpointDescriptor.bEndpointAddress.isIn()){ - _inEndpoints.push_back(std::make_shared(endpointDescriptor, device, handle)); - }else{ - _outEndpoints.push_back(std::make_shared(endpointDescriptor, device, handle)); - } - } - } - - UsbHostEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) override { - return const_cast(getEndpointImpl(isInEndpoint, id)); - } - const UsbHostEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) const override { - return getEndpointImpl(isInEndpoint, id); - } - const USB::InterfaceDescriptor& getInterfaceDescriptor() const override { - return _descriptor; - } -private: - const UsbHostEndpoint* getEndpointImpl(bool isInEndpoint, uint8_t id) const { - auto& endpoints = isInEndpoint ? _inEndpoints : _outEndpoints; - if(id >= endpoints.size()){ - return nullptr; - } - return endpoints[id].get(); - } - USB::InterfaceDescriptor _descriptor; - WINUSB_INTERFACE_HANDLE _handle; - - std::vector> _inEndpoints; - std::vector> _outEndpoints; -}; - -} - diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostEndpoint.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostEndpoint.h deleted file mode 100644 index 754e44f..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostEndpoint.h +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once - -#include "../IUsbHostEndpoint.h" -#include -#include "UsbHException.h" -#include -#include - -namespace LFramework::USB { - -//class Future { -//public: -// virtual ~Future() = default; -// virtual size_t wait() = 0; -//}; -class WinUsbFuture : public IUsbTransfer { -public: - WinUsbFuture(HANDLE deviceHandle, std::unique_ptr &&overlapped):_deviceHandle(deviceHandle), _overlapped(std::move(overlapped)){ - - } - size_t wait() override { - ULONG bytesTransferred = 0; - auto isContinuousWaiting = TRUE; - auto overlappedResult = false; - - if(_overlapped == nullptr) { - throw UsbHException("Can not wait multiple times"); - } - - auto waitResult = WaitForSingleObjectEx(_overlapped->hEvent, INFINITE, true); - if(waitResult == WAIT_OBJECT_0){ - overlappedResult = static_cast(GetOverlappedResult(_deviceHandle, _overlapped.get(), &bytesTransferred, isContinuousWaiting)); - } - - CloseHandle(_overlapped->hEvent); - - if(!overlappedResult) { - throw UsbHWinusbErrorCodeException(); - } - - return static_cast(bytesTransferred); - } -private: - HANDLE _deviceHandle; - std::unique_ptr _overlapped; -}; - -class UsbHostEndpoint : public IUsbHostEndpoint { -public: - UsbHostEndpoint(const USB::EndpointDescriptor& descriptor, HANDLE deviceHandle, WINUSB_INTERFACE_HANDLE interfaceHandle):IUsbHostEndpoint(descriptor), _interfaceHandle(interfaceHandle),_deviceHandle(deviceHandle){ - - } - - std::shared_ptr transferAsync(void* buffer, size_t size){ - if(getDescriptor().bEndpointAddress.isIn()){ - return readAsync(buffer, size); - }else{ - return writeAsync(buffer, size); - } - } - -private: - std::shared_ptr readAsync(void* buffer, size_t size){ - //auto index = _endpointsMap.at(endpoint.getAddress()); - ULONG bytesRead; - auto overlapped = std::make_unique(); - ZeroMemory(overlapped.get(), sizeof(OVERLAPPED)); - overlapped->hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); - - if (overlapped->hEvent == nullptr) { - throw UsbHWinusbErrorCodeException(); - } - auto asyncReadResult = static_cast(WinUsb_ReadPipe(_interfaceHandle, getDescriptor().bEndpointAddress.value, reinterpret_cast(buffer), static_cast(size), &bytesRead, overlapped.get())); - if (overlapped->hEvent == nullptr) { - throw UsbHWinusbErrorCodeException(); - } - if(!asyncReadResult && (GetLastError() != ERROR_IO_PENDING)){ - throw UsbHWinusbErrorCodeException(); - } - return std::make_shared(_deviceHandle, std::move(overlapped)); - } - - std::shared_ptr writeAsync(const void* buffer, size_t size){ - - ULONG bytesWritten; - auto overlapped = std::make_unique(); - ZeroMemory(overlapped.get(), sizeof(OVERLAPPED)); - overlapped->hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); - overlapped->Internal = STATUS_PENDING; - - auto asyncWriteResult = static_cast(WinUsb_WritePipe(_interfaceHandle, getDescriptor().bEndpointAddress.value, - reinterpret_cast(const_cast(buffer)), static_cast(size), &bytesWritten, overlapped.get())); - - if(!asyncWriteResult && (GetLastError() != ERROR_IO_PENDING)) { - throw UsbHWinusbErrorCodeException(); - } - - return std::make_shared(_deviceHandle, std::move(overlapped)); - } - - WINUSB_INTERFACE_HANDLE _interfaceHandle; - HANDLE _deviceHandle; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostManager.cpp b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostManager.cpp deleted file mode 100644 index 00a0498..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostManager.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include - - - -#include "UsbHostManager.h" - -#include -#include -#include -#include -#include -#include - -namespace LFramework::USB { - -UsbHostDeviceInfo UsbHostManager::getUsbDeviceInfo(const std::string& path){ - UsbHostDeviceInfo result{}; - std::smatch match; - std::regex vidPidRegex(".*vid_([0-9A-Fa-f]{4})&pid_([0-9A-Fa-f]{4}).*"); - std::regex serialNumberRegex(".*#([^#]*)#.*"); - if (std::regex_match(path, match, serialNumberRegex)) - result.serialNumber = match[1].str(); - if (std::regex_match(path, match, vidPidRegex)) { - const uint8_t base = 16; - result.vid = static_cast(std::stoi(match[1].str(), nullptr, base)); - result.pid = static_cast(std::stoi(match[2].str(), nullptr, base)); - } - result.path = path; - return result; -} - -std::vector UsbHostManager::enumerateDevices(){ - std::vector result; - GUID usbClassGUID = GUID_DEVINTERFACE_USB_DEVICE; - - //Get device list - auto deviceList = SetupDiGetClassDevsA(&usbClassGUID, nullptr, nullptr, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); - if (deviceList == INVALID_HANDLE_VALUE) { - return result; - } - - //Iterate devices - for(DWORD i = 0; GetLastError() != ERROR_NO_MORE_ITEMS; ++i){ - //Get device interface - SP_DEVICE_INTERFACE_DATA deviceInterfaceData{}; - deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - if(SetupDiEnumDeviceInterfaces(deviceList, nullptr, &usbClassGUID, i, &deviceInterfaceData) == FALSE){ - if( GetLastError() != ERROR_NO_MORE_ITEMS){ - continue; - }else{ - break; - } - } - - //Get device interface details - DWORD deviceInterfaceDataSize = 0; - SetupDiGetDeviceInterfaceDetailA(deviceList, &deviceInterfaceData, nullptr, 0, &deviceInterfaceDataSize, nullptr); - - std::vector deviceInterfaceDetailBuffer; - deviceInterfaceDetailBuffer.resize(deviceInterfaceDataSize, 0); - - auto deviceInterfaceDetailData = reinterpret_cast(deviceInterfaceDetailBuffer.data()); - deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); - - SP_DEVINFO_DATA deviceData{}; - deviceData.cbSize = sizeof(deviceData); - - if (SetupDiGetDeviceInterfaceDetailA(deviceList, &deviceInterfaceData, deviceInterfaceDetailData, deviceInterfaceDataSize, &deviceInterfaceDataSize, &deviceData) == TRUE){ - - auto info = getUsbDeviceInfo(std::string(deviceInterfaceDetailData->DevicePath)); - result.push_back(info); - } else { - auto err = GetLastError(); - } - } - SetupDiDestroyDeviceInfoList(deviceList); - return result; -} - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostManager.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostManager.h deleted file mode 100644 index 97dc09f..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbHostManager.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace LFramework::USB { - -struct UsbHostDeviceInfo { - uint16_t vid; - uint16_t pid; - std::string serialNumber; - std::string path; -}; - -class UsbHostManager { -public: - static UsbHostDeviceInfo getUsbDeviceInfo(const std::string& path); - static std::vector enumerateDevices(); -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbNotifyWindow.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbNotifyWindow.h deleted file mode 100644 index 9b4806b..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbNotifyWindow.h +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace LFramework::USB { - -class UsbNotifyWindow { -public: - UsbNotifyWindow(std::function deviceChangeCallback) : _callback(deviceChangeCallback) { - HINSTANCE moduleHandle = GetModuleHandleA(nullptr); - registerWindowClass(moduleHandle); - _windowHandle = CreateWindowExA(0, windowClassName(), nullptr, 0, 0, 0, 0, 0, {}, {}, moduleHandle, nullptr); - if(_windowHandle == NULL){ - throw std::runtime_error("UsbNotifyWindow::ctor failed to create window"); - } - SetWindowLongPtrA(_windowHandle, GWLP_USERDATA, LONG_PTR(this)); - } - - ~UsbNotifyWindow() { - UnregisterDeviceNotification(_deviceNotification); - DestroyWindow(_windowHandle); - } - - void processMessages() { - MSG msg{}; - while (GetMessage(&msg, nullptr, 0, 0)) { - TranslateMessage(&msg); - DispatchMessageA(&msg); - } - } -private: - HWND _windowHandle = {}; - HDEVNOTIFY _deviceNotification = {}; - std::function _callback; - - static const char* windowClassName() { - return "LUsbNotifyWindow"; - } - - void onDeviceChange() { - _callback(); - } - - static LRESULT CALLBACK windowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { - auto _this = reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); - if (Msg == WM_DEVICECHANGE && (_this != nullptr)) { - _this->onDeviceChange(); - } - return DefWindowProcA(hWnd, Msg, wParam, lParam); - } - - void registerDeviceNotification() { - DEV_BROADCAST_DEVICEINTERFACE notificationFilter{}; - ZeroMemory( ¬ificationFilter, sizeof(notificationFilter) ); - notificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); - notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; - notificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE; - _deviceNotification = RegisterDeviceNotificationA(_windowHandle, ¬ificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE ); - if(_deviceNotification == nullptr){ - throw std::runtime_error("UsbNotifyWindow::registerDeviceNotification failed"); - } - } - - static ATOM registerWindowClass(HINSTANCE moduleHandle) { - WNDCLASSEXA wndClass = {}; - wndClass.cbSize = sizeof(wndClass); - wndClass.hInstance = moduleHandle; - wndClass.lpszClassName = windowClassName(); - wndClass.lpfnWndProc = &UsbNotifyWindow::windowProc; - auto result = RegisterClassExA(&wndClass); - if(result == 0){ - auto err = GetLastError(); - if(err != ERROR_CLASS_ALREADY_EXISTS){ - throw std::runtime_error("UsbNotifyWindow::registerWindowClass failed"); - } - } - return result; - } -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbService.cpp b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbService.cpp deleted file mode 100644 index 87b8c9c..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbService.cpp +++ /dev/null @@ -1,143 +0,0 @@ -#include -#include "UsbService.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "UsbNotifyWindow.h" - - -namespace LFramework::USB { - -static std::thread _eventsPollingThread; - -UsbDeviceInfo UsbService::getUsbDeviceInfo(const std::string& path){ - UsbDeviceInfo result{}; - std::smatch match; - std::regex vidPidRegex(".*vid_([0-9A-Fa-f]{4})&pid_([0-9A-Fa-f]{4}).*"); - std::regex serialNumberRegex(".*#([^#]*)#.*"); - if (std::regex_match(path, match, serialNumberRegex)) - result.serialNumber = match[1].str(); - if (std::regex_match(path, match, vidPidRegex)) { - const uint8_t base = 16; - result.vid = static_cast(std::stoi(match[1].str(), nullptr, base)); - result.pid = static_cast(std::stoi(match[2].str(), nullptr, base)); - } - result.path = path; - return result; -} - -std::vector UsbService::enumerateDevices(){ - std::vector result; - GUID usbClassGUID = GUID_DEVINTERFACE_USB_DEVICE; - - //Get device list - auto deviceList = SetupDiGetClassDevsA(&usbClassGUID, nullptr, nullptr, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); - if (deviceList == INVALID_HANDLE_VALUE) { - return result; - } - - //Iterate devices - for(DWORD i = 0; GetLastError() != ERROR_NO_MORE_ITEMS; ++i){ - //Get device interface - SP_DEVICE_INTERFACE_DATA deviceInterfaceData{}; - deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - if(SetupDiEnumDeviceInterfaces(deviceList, nullptr, &usbClassGUID, i, &deviceInterfaceData) == FALSE){ - if( GetLastError() != ERROR_NO_MORE_ITEMS){ - continue; - }else{ - break; - } - } - - //Get device interface details - DWORD deviceInterfaceDataSize = 0; - SetupDiGetDeviceInterfaceDetailA(deviceList, &deviceInterfaceData, nullptr, 0, &deviceInterfaceDataSize, nullptr); - - std::vector deviceInterfaceDetailBuffer; - deviceInterfaceDetailBuffer.resize(deviceInterfaceDataSize, 0); - - auto deviceInterfaceDetailData = reinterpret_cast(deviceInterfaceDetailBuffer.data()); - deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); - - SP_DEVINFO_DATA deviceData{}; - deviceData.cbSize = sizeof(deviceData); - - if (SetupDiGetDeviceInterfaceDetailA(deviceList, &deviceInterfaceData, deviceInterfaceDetailData, deviceInterfaceDataSize, &deviceInterfaceDataSize, &deviceData) == TRUE){ - - auto info = getUsbDeviceInfo(std::string(deviceInterfaceDetailData->DevicePath)); - result.push_back(info); - } else { - auto err = GetLastError(); - } - } - SetupDiDestroyDeviceInfoList(deviceList); - return result; -} - - -DWORD WINAPI UsbService::eventsThreadProc(LPVOID lpParam){ - UsbService* _this = reinterpret_cast(lpParam); - - std::shared_ptr window; - try{ - window = std::make_shared(_this->_deviceChangeCallback); - _this->_initPromise.set_value(true); - }catch(...){ - _this->_initPromise.set_value(false); - return 0; - } - window->processMessages(); - window = nullptr; - return 0; -} - -bool UsbService::startEventsListening(std::function deviceChangeCallback){ - if(_threadHandle != nullptr){ - return false; - } - - _initPromise = std::promise(); - auto initFuture = _initPromise.get_future(); - - _deviceChangeCallback = deviceChangeCallback; - - _threadHandle = CreateThread(nullptr, 0, &UsbService::eventsThreadProc, this, 0, &_threadId); - - if(!initFuture.get()){ - WaitForSingleObject(_threadHandle, INFINITE); - CloseHandle(_threadHandle); - _threadHandle = nullptr; - _deviceChangeCallback = nullptr; - return false; - } - return true; -} - -void UsbService::stopEventsListening(){ - if(_threadHandle == nullptr){ - return; - } - - while(PostThreadMessageA(_threadId, WM_QUIT, 0, 0) != TRUE){ - std::this_thread::yield(); - } - - WaitForSingleObject(_threadHandle, INFINITE); - CloseHandle(_threadHandle); - _threadHandle = nullptr; - _deviceChangeCallback = nullptr; -} - - -IUsbService* createUsbService(){ - return new UsbService(); -} - - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbService.h b/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbService.h deleted file mode 100644 index b0bcfe7..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/Host/Windows/UsbService.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace LFramework::USB { - -class UsbService : public IUsbService { -public: - UsbDeviceInfo getUsbDeviceInfo(const std::string& path); - std::vector enumerateDevices(); - bool startEventsListening(std::function deviceChangeCallback); - void stopEventsListening(); -private: - static DWORD WINAPI eventsThreadProc(LPVOID lpParam); - HANDLE _threadHandle = {}; - DWORD _threadId = 0; - std::promise _initPromise; - std::function _deviceChangeCallback; -}; - -} \ No newline at end of file diff --git a/Dependencies/LFramework/Src/LFramework/USB/USBDevice_Deprecated.h b/Dependencies/LFramework/Src/LFramework/USB/USBDevice_Deprecated.h deleted file mode 100644 index cf7913e..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/USBDevice_Deprecated.h +++ /dev/null @@ -1,522 +0,0 @@ -/* - * USBDevice.h - * - * Created on: 29 Aug. 2017 г. - * Author: l-pro - */ - -#ifndef LFRAMEWORK_MCU_USBDEVICE_USBDEVICE_H_ -#define LFRAMEWORK_MCU_USBDEVICE_USBDEVICE_H_ - -#include "LFrameworkConfig.h" -#include - -#include "../System.h" -#include -#include -#include -#include "../TupleUtils.h" -#include "USBTypes.h" - -namespace LFramework { -namespace USB { - -enum class UsbDeviceState { - Stopped, - ResetComplete, - Suspended, - Configured, - Addressed -}; - -enum class UsbEndpoint0Stage { - Idle, - Setup, - DataIn, - DataOut, - StatusIn, - StatusOut, - Error -}; - - -template -constexpr std::false_type HasChildDescriptorHelper(...) { - return {}; -}; - -template -constexpr std::true_type HasChildDescriptorHelper(const T& ) { - return {}; -}; - -template -constexpr bool HasChildDescriptor = std::is_same_v(std::declval()))>; - - -struct DescriptorSelector { - template - auto operator () (const T& t) { - if constexpr (HasChildDescriptor) { - return typename std::remove_reference_t>::Descriptor{}; - } - else { - return TupleSkipType{}; - } - } -}; - -struct UsbEndpointState { - uint32_t dataLength = 0; - uint32_t dataRemainingLength = 0; -}; - -template -class UsbEndpoint{ -public: - struct DescriptorEx : USB::EndpointDescriptor { - constexpr DescriptorEx() { - bEndpointAddress = Address; - wMaxPacketSize = MaxPacketSize; - bInterval = PollingInterval; - bmAttributes = EndpointAttributes(type, syncType, usageType); - } - }; - - using Descriptor = DescriptorEx; -}; - -template -class UsbInEndpoint : public UsbEndpoint{}; - -template -class UsbOutEndpoint : public UsbEndpoint{}; - -template -class UsbBulkInEndpoint : public UsbInEndpoint{}; - -template -class UsbBulkOutEndpoint : public UsbOutEndpoint{}; - -template -class UsbIsoInEndpoint : public UsbInEndpoint{}; - -template -class UsbIsoOutEndpoint : public UsbOutEndpoint{}; - -template -class UsbInterruptInEndpoint : public UsbInEndpoint{}; - -template -class UsbInterruptOutEndpoint : public UsbOutEndpoint{}; - -template -class UsbInterface { -public: - static constexpr uint32_t getEndpointsCount() { - return sizeof...(Endpoints); - } - - struct InterfaceDescriptorEx : USB::InterfaceDescriptor { - constexpr InterfaceDescriptorEx() { - bAlternateSetting = 0; //TODO: handle alternate interfaces - bNumEndpoints = getEndpointsCount(); - this->bInterfaceNumber = bInterfaceNumber; - iInterface = indexOfStringDescriptor; - classDescription = classDescriptor{}; - } - }; - - using epDesc = tupleSelectType>; - - using Descriptor = Tuple; -}; - -template -class InterfaceAssociation { -public: - -}; - -template -class UsbFunction { -public: - using Descriptor = typename Interface::Descriptor; - static constexpr size_t interfacesCount = 1; -}; - -template -class UsbFunction> { -public: - using Descriptor = float; - static constexpr size_t interfacesCount = sizeof...(Interfaces); -}; - - - -template -class UsbConfiguration { -public: - static constexpr uint32_t FunctionsCount = sizeof...(Functions); - Tuple _functions; - - void onEndpointTransferComplete(uint8_t epId, size_t size) { - - } - - using Descriptor = tupleSelectType>; - - USBDescriptor* getDescriptor(){ - return reinterpret_cast(&_descriptor); - } - /*static constexpr uint32_t getConfigurationDescriptorSize() { - return (Interfaces::getDescriptorSize() + ...); - }*/ -private: - Descriptor _descriptor; - //std::array _configurationDescriptor; -}; - - - - - -template -struct IsUsbInterface : std::false_type{}; - -template -struct IsUsbInterface> : std::true_type {}; - -template -struct IsUsbConfiguration : std::false_type{}; - -template -struct IsUsbConfiguration> : std::true_type {}; - - -/*template -class AlternateInterfaces { -public: - static constexpr uint32_t getDescriptorSize() { - return (Interfaces::getDescriptorSize() + ...); - } -}; - - -using GenericInterface = UsbInterface, UsbEndpoint<0x81>>; -using GenericInterfaceA = AlternateInterfaces, UsbEndpoint<0x81>>>; -using GenericConfig = UsbConfiguration; -using GenericConfigA = UsbConfiguration; - -static_assert(GenericConfig::getConfigurationDescriptorSize() == EndpointDescriptor::Size * 2 + InterfaceDescriptor::Size, "WTF"); -static_assert(GenericConfigA::getConfigurationDescriptorSize() == EndpointDescriptor::Size * 2 + InterfaceDescriptor::Size, "WTF"); - - -static_assert(IsUsbInterface, UsbEndpoint<0x81>>>::value, "Fail"); -*/ - - -template -class UsbDevice : public UsbPhy { -public: - DeviceDescriptor descriptor; - using Phy = UsbPhy; - - using ConfigurationsList = Tuple; - - static constexpr size_t ConfigurationsCount = sizeof...(Configurations); - - uint8_t _currentConfig = 0x0; - - - - std::tuple _configurations; - - //static_assert((IsUsbConfiguration::value && ...) , "Only UsbConfiguration types allowed"); - - template - auto& getConfiguration(){ - return std::get(_configurations); - } - - UsbDevice(){ - //usb = this; - } - -/* void connect(){ - HAL_PCD_DevConnect(_pcd); - } - - void disconnect(){ - HAL_PCD_DevDisconnect(_pcd); - }*/ - - /*void initPHY(){ - - _pcd->Instance = USB_OTG_FS; - _pcd->Init.dev_endpoints = 1; - _pcd->Init.speed = PCD_SPEED_FULL; - _pcd->Init.dma_enable = DISABLE; - _pcd->Init.Sof_enable = DISABLE; - _pcd->Init.ep0_mps = 64; - _pcd->Init.phy_itface = PCD_PHY_EMBEDDED; - _pcd->Init.low_power_enable = DISABLE; - _pcd->Init.lpm_enable = DISABLE; - _pcd->Init.vbus_sensing_enable = DISABLE; - _pcd->Init.use_dedicated_ep1 = DISABLE; - //_pcd->Init.battery_charging_enable = DISABLE; - HAL_PCD_Init(_pcd); - - //HAL_PCD_SetRxFiFo(&USBD_PCD, 0x80); - //HAL_PCD_SetTxFiFo(&USBD_PCD, 0, 0x20); - //HAL_PCD_SetTxFiFo(&USBD_PCD, 1, 0x40); - - HAL_PCD_SetRxFiFo(_pcd, 0x80); - HAL_PCD_SetTxFiFo(_pcd, 0, 0x40); - HAL_PCD_SetTxFiFo(_pcd, 1, 0x80); - }*/ - - /*void start(){ - HAL_PCD_Start(_pcd); - }*/ - - template - void executeOnCurrentConfig(Functor f){ - executeOnIndex(_configurations, _currentConfig, f); - } - - void onEndpointTransferComplete(uint8_t epId, size_t size) override { - executeOnCurrentConfig([epId, size](auto& config){config.onEndpointTransferComplete(epId, size);}); - } - - - void onReset(){ - Phy::openEndpoint(0x00, 64, EndpointType::Control); - Phy::openEndpoint(0x80, 64, EndpointType::Control); - //open ep0 - //deinit previous user config if any... - - //Control endpoint init - //TODO: move implementation in abstract PHY code - /*HAL_PCD_EP_Open(_pcd, 0x00, 64, (uint8_t)EndpointType::Control); - HAL_PCD_EP_Open(_pcd, 0x80, 64, (uint8_t)EndpointType::Control); - - setState(UsbDeviceState::ResetComplete);*/ - - //TODO: close previous config - - setState(UsbDeviceState::ResetComplete); - } - - void onSuspend(){ - /* __HAL_PCD_GATE_PHYCLOCK(_pcd); - - _stateBeforeSuspend = _state; - setState(UsbDeviceState::Suspended); - - //Suspend whole MCU device - if (_pcd->Init.low_power_enable){ - //TODO: maybe move somewhere else (to user code?) - SCB->SCR |= (uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk); - }*/ - } - - void onResume(){ - setState(_stateBeforeSuspend); - } - - const USBDescriptor* getDescriptor(USB::DescriptorType type, uint8_t id) override{ - switch(type){ - case USB::DescriptorType::DeviceDescriptor: - return &descriptor; - break; - case USB::DescriptorType::ConfigurationDescriptor: - if(id < ConfigurationsCount){ - USBDescriptor* result = nullptr; - executeOnCurrentConfig([&result](auto& config){result = config.getDescriptor();}); - return result; - } - break; - } - - return nullptr; - } - - void stdRequestGetDescriptor(const SetupPacket* setup){ - auto desc = getDescriptor(static_cast(setup->wValue >> 8), setup->wValue & 0xff); - - if(desc == nullptr){ - System::setBreakpoint(); - } - - if(setup->wLength != 0){ - auto len = desc->bLength; - len = std::min(len, (uint8_t)setup->wLength); - controlSendData((uint8_t*)desc, len); - } - } - - void stdRequestSetAddress(const SetupPacket* setup){ - if(_state == UsbDeviceState::Configured){ - controlError(); - }else { - //send status before set address TODO: maybe handle in some different manner (wait for status really sent??) - controlSendStatus(); - auto address = setup->wValue & 0x7f; - - //HAL_PCD_SetAddress(_pcd, address); - - _state = address == 0 ? UsbDeviceState::Stopped : UsbDeviceState::Addressed; - } - } - - void setConfiguration(uint8_t id){ - if(_currentConfig != id){ - if(_currentConfig != 0xff){ - executeOnCurrentConfig([](auto& config){ - //config.deinit(); - }); - } - - _currentConfig = id; - - if(_currentConfig != 0xff){ - executeOnCurrentConfig([](auto& config){ - //config.init(); - }); - } - } - } - - bool stdDeviceRequest(const SetupPacket* setup){ - switch(setup->bRequest){ - case SetupRequest::GetDescriptor: - stdRequestGetDescriptor(setup); - break; - case SetupRequest::SetAddress: - stdRequestSetAddress(setup); - break; - default: - System::setBreakpoint(); - break; - } - return true; - } - - void onSetup(const SetupPacket* header) override{ - //SetupPacket setupHeader; - //setupHeader = *((SetupPacket*)(&_pcd->Setup[0])); - _ep0Stage = UsbEndpoint0Stage::Setup; - _ep0DataSize = header->wLength; - - switch(header->bmRequestType.Recipient){ - case RequestRecipient::Device: - stdDeviceRequest(header); - break; - case RequestRecipient::Interface: - System::setBreakpoint(); - break; - case RequestRecipient::Endpoint: - System::setBreakpoint(); - break; - default: - System::setBreakpoint(); - break; - } - - if(_ep0Stage == UsbEndpoint0Stage::Setup){ - if(header->bmRequestType.Direction == RequestDirection::HostToDevice){ - controlSendStatus(); - }else { - controlReceiveStatus(); - } - } - } - - void onDataOut(uint8_t endpointNumber, uint8_t size){ - if(endpointNumber == 0){ - if(_ep0Stage == UsbEndpoint0Stage::DataOut){ - System::setBreakpoint(); - } - }else { - System::setBreakpoint(); - } - } - - void onDataIn(uint8_t endpointNumber){ - if(endpointNumber == 0){ - if(_ep0Stage == UsbEndpoint0Stage::DataIn){ - //send next packet - /*auto& ep = _inEndpoints[0]; - if(ep.dataRemainingLength > _pcd->IN_ep[0].maxpacket){ - ep.dataRemainingLength -= _pcd->IN_ep[0].maxpacket; - HAL_PCD_EP_Transmit(_pcd, 0, _pcd->IN_ep[0].xfer_buff, ep.dataRemainingLength); - - }else{ //handle last packet - if((_ep0DataSize != 0) && ((ep.dataLength % _pcd->IN_ep[0].maxpacket) == 0) && (ep.dataLength != _ep0DataSize)){ - _ep0DataSize = 0; - HAL_PCD_EP_Transmit(_pcd, 0, nullptr, 0); - }else{ - _ep0DataSize = 0; - //event: data in stage complete - controlReceiveStatus(); - } - }*/ - } - }else { - System::setBreakpoint(); - } - } - - void controlReceiveStatus(){ - _ep0Stage = UsbEndpoint0Stage::StatusOut; - Phy::beginReceive(0x00, nullptr, 0); - } - - void controlSendStatus(){ - _ep0Stage = UsbEndpoint0Stage::StatusIn; - Phy::beginTransmit(0x00, nullptr, 0); - //HAL_PCD_EP_Transmit(_pcd, 0, nullptr, 0); - } - - void controlSendData(uint8_t* data, uint32_t size){ - _ep0Stage = UsbEndpoint0Stage::DataIn; - _inEndpoints[0].dataLength = size; - _inEndpoints[0].dataRemainingLength = size; - Phy::beginTransmit(0x80, data, size); - - //HAL_PCD_EP_Transmit(_pcd, 0, data, size); - } - - void controlError(){ - _ep0Stage = UsbEndpoint0Stage::Error; - //HAL_PCD_EP_SetStall(_pcd, 0x80); - //HAL_PCD_EP_SetStall(_pcd, 0x00); - } - - - void onSOF(){System::setBreakpoint();} - void onIsochronousOutIncomplete(uint8_t endpointNumber){System::setBreakpoint();} - void onIsochronousInIncomplete(uint8_t endpointNumber){System::setBreakpoint();} - void onConnect(){System::setBreakpoint();} - void onDisconnect(){System::setBreakpoint();} - -protected: - - void setState(UsbDeviceState state){ - _state = state; - } - UsbDeviceState _stateBeforeSuspend = UsbDeviceState::Stopped; - UsbDeviceState _state = UsbDeviceState::Stopped; - //PCD_HandleTypeDef* _pcd; - - UsbEndpoint0Stage _ep0Stage = UsbEndpoint0Stage::Idle; - uint32_t _ep0DataSize = 0; - - UsbEndpointState _inEndpoints[15]; - UsbEndpointState _outEndpoints[15]; -}; - -}} - -#endif /* LFRAMEWORK_MCU_USBDEVICE_USBDEVICE_H_ */ diff --git a/Dependencies/LFramework/Src/LFramework/USB/USBTypes.h b/Dependencies/LFramework/Src/LFramework/USB/USBTypes.h deleted file mode 100644 index a786f9e..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/USBTypes.h +++ /dev/null @@ -1,656 +0,0 @@ -#pragma once - -#include -#include "../BitField.h" -#include - -namespace LFramework { - namespace USB { - -#pragma pack(push, 1) - - struct UsbAttributes { - UsbAttributes(){ - value = 0; - reservedBusPowered_1_0 = 1; //Reserved, set to 1. (USB 1.0 Bus Powered) - } - union { - uint8_t value; - struct{ - uint8_t reservedZero : 5; - uint8_t remoteWakeup : 1; - uint8_t selfPowered : 1; - uint8_t reservedBusPowered_1_0 : 1; - }; - }; - }; - - enum class LanguageID : std::uint16_t { - Invalid = 0x0000, // Invalid LANG ID - Afrikaans = 0x0436, // Afrikaans - Albanian = 0x041c, // Albanian - ArabicSaudiArabia = 0x0401, // Arabic (Saudi Arabia) - ArabicIrak = 0x0801, // Arabic (Irak) - ArabicEgypt = 0x0c01, // Arabic (Egypt) - ArabicLybya = 0x1001, // Arabic (Libya) - ArabicAlgeria = 0x1401, // Arabic (Algeria) - ArabicMorocco = 0x1801, // Arabic (Morocco) - ArabicTunisia = 0x1c01, // Arabic (Tunisia) - ArabicOman = 0x2001, // Arabic (Oman) - ArabicYemen = 0x2401, // Arabic (Yemen) - ArabicSyria = 0x2801, // Arabic (Syria) - ArabicJordan = 0x2c01, // Arabic (Jordan) - ArabicLebanon = 0x3001, // Arabic (Lebanon) - ArabicKuwait = 0x3401, // Arabic (Kuwait) - ArabicUae = 0x3801, // Arabic (U.A.E.) - ArabicBahrain = 0x3c01, // Arabic (Bahrain) - ArabicQatar = 0x4001, // Arabic (Qatar) - Armenian = 0x042b, // Armenian - Assamese = 0x044d, // Assamese - AzeriLatin = 0x042c, // Azeri (Latin) - AzeriCyrillic = 0x082c, // Azeri (Cyrillic) - Basque = 0x042d, // Basque - Belarussian = 0x0423, // Belarussian - Bengali = 0x0445, // Bengali - Bulgarian = 0x0402, // Bulgarian - Burmese = 0x0455, // Burmese - Catalan = 0x0403, // Catalan - ChineseTaiwan = 0x0404, // Chinese (Taiwan) - ChinesePrc = 0x0804, // Chinese (PRC = People Republic of Chinese) - ChineseHongKong = 0x0c04, // Chinese (Hong Kong) - ChineseSingapore = 0x1004, // Chinese (Singapore) - ChineseMacauSar = 0x1404, // Chinese (Macau SAR) - Croatian = 0x041a, // Croatian - Czech = 0x0405, // Czech - Danish = 0x0406, // Danish - DutchNetherlands = 0x0413, // Dutch (Netherlands) - DutchBelgium = 0x0813, // Dutch (Belgium) - EnglishUnitedStates = 0x0409, // English (United States) - EnglishUnitedKingdom = 0x0809, // English (United Kingdom) - EnglishAustralian = 0x0c09, // English (Australian) - EnglishCanadian = 0x1009, // English (Canadian) - EnglishNewZealand = 0x1409, // English (New Zealand) - EnglishIreland = 0x1809, // English (Ireland) - EnglishSouthAfrica = 0x1c09, // English (South Africa) - EnglishJamaica = 0x2009, // English (Jamaica) - EnglishCaribbean = 0x2409, // English (Caribbean) - EnglishBelize = 0x2809, // English (Belize) - EnglishTrinidad = 0x2c09, // English (Trinidad) - EnglishZimbabwe = 0x3009, // English (Zimbabwe) - EnglishPhlippines = 0x3409, // English (Philippines) - Estonian = 0x0425, // Estonian - Faeroese = 0x0438, // Faeroese - Farsi = 0x0429, // Farsi - Finnish = 0x040b, // Finnish - FrenchStandard = 0x040c, // French (Standard) - FrenchBelgian = 0x080c, // French (Belgian) - FrenchCanadian = 0x0c0c, // French (Canadian) - FrenchSwitzerland = 0x100c, // French (Switzerland) - FrenchLuxembourg = 0x140c, // French (Luxembourg) - FrenchMonaco = 0x180c, // French (Monaco) - Georgian = 0x0437, // Georgian - GermanStandard = 0x0407, // German (Standard) - GermanSwitzerland = 0x0807, // German (Switzerland) - GermanAustria = 0x0c07, // German (Austria) - GermanLuxembourg = 0x1007, // German (Luxembourg) - GermanLiechtenstein = 0x1407, // German (Liechtenstein) - Greek = 0x0408, // Greek - Gujarati = 0x0447, // Gujarati - Hebrew = 0x040d, // Hebrew - Hindi = 0x0439, // Hindi - Hungarian = 0x040e, // Hungarian - Icelandic = 0x040f, // Icelandic - Indonesian = 0x0421, // Indonesian - ItalianStandard = 0x0410, // Italian (Standard) - ItalianSwitzerland = 0x0810, // Italian (Switzerland) - Japanese = 0x0411, // Japanese - Kannada = 0x044b, // Kannada - KashmiriIndia = 0x0860, // Kashmiri (India) - Kazakh = 0x043f, // Kazakh - Konkani = 0x0457, // Konkani - KoreanJohab = 0x0412, // Korean (Johab) - Latvian = 0x0426, // Latvian - Lithuanian = 0x0427, // Lithuanian - LithuanianClassic = 0x0827, // Lithuanian (Classic) - Macedonian = 0x042f, // Macedonian - MalayMalaysian = 0x043e, // Malay (Malaysian) - MalayBruneiDarussalam = 0x083e, // Malay (Brunei Darussalam) - Malayalam = 0x044c, // Malayalam - Manipuri = 0x0458, // Manipuri - Marathi = 0x044e, // Marathi - NepaliIndia = 0x0861, // Nepali (India) - NorwegianBokmal = 0x0414, // Norwegian (Bokmal) - NorwegianNynorsk = 0x0814, // Norwegian (Nynorsk) - Oriya = 0x0448, // Oriya - Polish = 0x0415, // Polish - PortugueseBrazil = 0x0416, // Portuguese (Brazil) - PortugueseStandard = 0x0816, // Portuguese (Standard) - Punjabi = 0x0446, // Punjabi - Romanian = 0x0418, // Romanian - Russian = 0x0419, // Russian - Sanskrit = 0x044f, // Sanskrit - SerbianCyrillic = 0x0c1a, // Serbian (Cyrillic) - SerbianLatin = 0x081a, // Serbian (Latin) - Sindhi = 0x0459, // Sindhi - Slovak = 0x041b, // Slovak - Slovenian = 0x0424, // Slovenian - SpannishTraditionalSort = 0x040a, // Spannish (Traditional Sort) - SpannishMexican = 0x080a, // Spannish (Mexican) - SpannishModernSort = 0x0c0a, // Spannish (Modern Sort) - SpannishGuatemala = 0x100a, // Spannish (Guatemala) - SpannishCostaRica = 0x140a, // Spannish (Costa Rica) - SpannishPanama = 0x180a, // Spannish (Panama) - SpannishDominicanRepublic = 0x1c0a, // Spannish (Dominican Republic) - SpannishVenezuela = 0x200a, // Spannish (Venezuela) - SpannishColombia = 0x240a, // Spannish (Colombia) - SpannishPeru = 0x280a, // Spannish (Peru) - SpannishArgentina = 0x2c0a, // Spannish (Argentina) - SpannishEcuador = 0x300a, // Spannish (Ecuador) - SpannishChile = 0x340a, // Spannish (Chile) - SpannishUruguay = 0x380a, // Spannish (Uruguay) - SpannishParaguay = 0x3c0a, // Spannish (Paraguay) - SpannishBolivia = 0x400a, // Spannish (Bolivia) - SpannishElSalvador = 0x440a, // Spannish (El Salvador) - SpannishHonduras = 0x480a, // Spannish (Honduras) - SpannishNicaragua = 0x4c0a, // Spannish (Nicaragua) - SpannishPuertoRico = 0x500a, // Spannish (Puerto Rico) - Sutu = 0x0430, // Sutu - SwahiliKenya = 0x0441, // Swahili (Kenya) - Swedish = 0x041d, // Swedish - SwedishFinland = 0x081d, // Swedish (Finland) - Tamil = 0x0449, // Tamil - TatarTatarstan = 0x0444, // Tatar (Tatarstan) - Telugu = 0x044a, // Telugu - Thai = 0x041e, // Thai - Turkish = 0x041f, // Turkish - Ukrainian = 0x0422, // Ukrainian - UrduPakistan = 0x0420, // Urdu (Pakistan) - UrduIndia = 0x0820, // Urdu (India) - UzbekLatin = 0x0443, // Uzbek (Latin) - UzbekCyrillic = 0x0843, // Uzbek (Cyrillic) - Vietnamese = 0x042a, // Vietnamese - HidUdd = 0x04ff, // HID (Usage Data Descriptor) - Hid1 = 0xf0ff, // HID (Vendor Defined 1) - Hid2 = 0xf4ff, // HID (Vendor Defined 2) - Hid3 = 0xf8ff, // HID (Vendor Defined 3) - Hid4 = 0xfcff // HID (Vendor Defined 4) - }; - - enum class DescriptorType : uint8_t { - DeviceDescriptor = 0x01, - ConfigurationDescriptor = 0x02, - StringDescriptor = 0x03, - InterfaceDescriptor = 0x04, - EndpointDescriptor = 0x05, - DeviceQualifierDescriptor = 0x06, - InterfaceAssociationDescriptor = 0x0B, - ClassSpecificInterface = 0x24, - ClassSpecificEndpoint = 0x25 - }; - - enum class SetupRequest : uint8_t { - GetStatus = 0x00, - ClearFeature = 0x01, - SetFeature = 0x03, - SetAddress = 0x05, - GetDescriptor = 0x06, - SetDescriptor = 0x07, - GetConfiguration = 0x08, - SetConfiguration = 0x09, - GetInterface = 0x0A, - SetInterface = 0x11, - SynchFrame = 0x12 - }; - - enum class EndpointType : uint8_t { - Control = 0, - Isochronous = 1, - Bulk = 2, - Interrupt = 3 - }; - - enum class EndpointSynchronizationType : uint8_t { - NoSynchonisation = 0x00, - Asynchronous = 0x01, - Adaptive = 0x02, - Synchronous = 0x03 - }; - - enum class EndpointUsageType : uint8_t { - DataEndpoint = 0x00, - FeedbackEndpoint = 0x01, - ExplicitFeedbackDataEndpoint = 0x02 - }; - - - enum class RequestRecipient : uint8_t { - Device = 0, - Interface = 1, - Endpoint = 2, - Other = 3 - }; - - enum class RequestType : uint8_t { - Standard = 0, - Class = 1, - Vendor = 2, - Reserved = 3 - }; - - enum class RequestDirection : uint8_t { - HostToDevice = 0, - DeviceToHost = 1 - }; - - struct SetupPacket { - union { - uint8_t value; - BitFieldMember Recipient; - BitFieldMember Type; - BitFieldMember Direction; - }bmRequestType; - SetupRequest bRequest; - uint16_t wValue; - uint16_t wIndex; - uint16_t wLength; - }; - - - static_assert(sizeof(SetupPacket) == 8, "Invalid packet size"); - -#pragma pack(push, 1) - struct EndpointAddress { - uint8_t value = 0; - - constexpr EndpointAddress():value{0}{} - - constexpr EndpointAddress(uint8_t address):value{address}{} - - static EndpointAddress makeIn(uint8_t id){ - return EndpointAddress(0x80 | id); - } - - static EndpointAddress makeOut(uint8_t id){ - return EndpointAddress(id & ~0x80); - } - - constexpr operator uint8_t(){ - return value; - } - - void setIn(uint8_t id){ - value = 0x80 | id; - } - void setOut(uint8_t id){ - value = id & ~0x80; - } - - constexpr bool isIn() const{ - return value == 0 ? true : ((value & 0x80) != 0); - } - static bool isIn(uint8_t value) { - return value == 0 ? true : ((value & 0x80) != 0); - } - - constexpr bool isOut() const { - return value == 0 ? true : ((value & 0x80) == 0); - } - static bool isOut(uint8_t value) { - return value == 0 ? true : ((value & 0x80) == 0); - } - - constexpr bool isValid() const { - return ((value & 0x70) == 0) && - ((value & 0x7f) == 0 ? ((value & 0x80) == 0) : true); - } - - static constexpr uint8_t inAddress(uint8_t index){ - return index | 0x80; - } - - static constexpr uint8_t outAddress(uint8_t index){ - return index & 0x7f; - } - - constexpr uint8_t index() const { - return static_cast(value & 0x7f); - } - }; -#pragma pack(pop) - - static_assert(EndpointAddress(0x00).isIn() == true, "Fail"); - static_assert(EndpointAddress(0x00).isOut() == true, "Fail"); - static_assert(EndpointAddress(0x00).isValid() == true, "Fail"); - - static_assert(EndpointAddress(0x81).isIn() == true, "Fail"); - static_assert(EndpointAddress(0x81).isOut() == false, "Fail"); - static_assert(EndpointAddress(0x81).isValid() == true, "Fail"); - static_assert(EndpointAddress(0x01).isIn() == false, "Fail"); - static_assert(EndpointAddress(0x01).isOut() == true, "Fail"); - static_assert(EndpointAddress(0x01).isValid() == true, "Fail"); - - static_assert(EndpointAddress(0x70).isValid() == false, "Fail"); - static_assert(EndpointAddress(0xf0).isValid() == false, "Fail"); - - //Descriptors - struct USBDescriptor { - constexpr USBDescriptor(uint8_t length, DescriptorType type) : bLength(length), bDescriptorType(type) {} - uint8_t bLength; - DescriptorType bDescriptorType; - }; - - template - struct USBDescriptorInit : USBDescriptor { - constexpr USBDescriptorInit() : USBDescriptor(sizeof(Derived), Derived::Type) {} - }; - - struct UsbClassDescriptor { - constexpr UsbClassDescriptor():classId(0), subClassId(0), protocol(0){} - constexpr UsbClassDescriptor(uint8_t classId, uint8_t subClassId, uint8_t protocol) - :classId(classId), subClassId(subClassId), protocol(protocol){} - uint8_t classId = 0; - uint8_t subClassId = 0; - uint8_t protocol = 0; - }; - - template - struct UsbClassDescriptorInit : UsbClassDescriptor{ - constexpr UsbClassDescriptorInit() : UsbClassDescriptor(ClassId, SubClassId, Protocol) {} - }; - - namespace UsbClass { - namespace Device { - using UseInterfaceClass = UsbClassDescriptorInit<0, 0, 0>; - - template - using CDC = UsbClassDescriptorInit<0x02, SubClassId, Protocol>; - - using HubFullSpeed = UsbClassDescriptorInit<0x09, 0x00, 0x00>; - using HubHiSpeedSingleTT = UsbClassDescriptorInit<0x09, 0x00, 0x01>; - using HubHiSpeedMultipleTT = UsbClassDescriptorInit<0x09, 0x00, 0x02>; - - using Billboard = UsbClassDescriptorInit<0x11, 0x00, 0x00>; - - template - using Diagnostic = UsbClassDescriptorInit<0xDC, SubClassId, Protocol>; - - - - namespace Miscellaneous { - using ActiveSync = UsbClassDescriptorInit<0xEF, 0x01, 0x01>; - using PalmSync = UsbClassDescriptorInit<0xEF, 0x01, 0x02>; - - - using InterfaceAssociation = UsbClassDescriptorInit<0xEF, 0x02, 0x01>; - using WireAdapterMFProgramming = UsbClassDescriptorInit<0xEF, 0x02, 0x02>; - - using CableBasedAssociationFramework = UsbClassDescriptorInit<0xEF, 0x03, 0x01>; - - using RNDISoverEthernet = UsbClassDescriptorInit<0xEF, 0x04, 0x01>; - using RNDISoverWiFi = UsbClassDescriptorInit<0xEF, 0x04, 0x02>; - using RNDISoverWiMAX = UsbClassDescriptorInit<0xEF, 0x04, 0x03>; - using RNDISoverWWAN = UsbClassDescriptorInit<0xEF, 0x04, 0x04>; - using RNDISforRawIP4 = UsbClassDescriptorInit<0xEF, 0x04, 0x05>; - using RNDISforRawIP6 = UsbClassDescriptorInit<0xEF, 0x04, 0x06>; - using RNDISforGPRS = UsbClassDescriptorInit<0xEF, 0x04, 0x07>; - - using USB3VisionControl = UsbClassDescriptorInit<0xEF, 0x05, 0x00>; - using USB3VisionEvent = UsbClassDescriptorInit<0xEF, 0x05, 0x01>; - using USB3VisionStreaming = UsbClassDescriptorInit<0xEF, 0x05, 0x02>; - - using STEP = UsbClassDescriptorInit<0xEF, 0x06, 0x01>; - using STEP_RAW = UsbClassDescriptorInit<0xEF, 0x06, 0x02>; - - using CmdInterfaceInIAD = UsbClassDescriptorInit<0xEF, 0x07, 0x01>; - using CmdInterfaceInInterface = UsbClassDescriptorInit<0xEF, 0x07, 0x01>; - using MediaInterfaceInInterface = UsbClassDescriptorInit<0xEF, 0x07, 0x02>; - } - - template - using VendorSpecific = UsbClassDescriptorInit<0xFF, SubClassId, Protocol>; - - } - namespace Interface { - template - using Audio = UsbClassDescriptorInit<0x01, SubClassId, Protocol>; - - template - using CDC = Device::CDC; - - template - using HID = UsbClassDescriptorInit<0x03, SubClassId, Protocol>; - - template - using Physical = UsbClassDescriptorInit<0x05, SubClassId, Protocol>; - - using StillImaging = UsbClassDescriptorInit<0x06, 0x01, 0x01>; - - template - using Printer = UsbClassDescriptorInit<0x07, SubClassId, Protocol>; - - template - using MassStorage = UsbClassDescriptorInit<0x08, SubClassId, Protocol>; - - template - using CDCData = UsbClassDescriptorInit<0x0A, SubClassId, Protocol>; - - template - using SmartCard = UsbClassDescriptorInit<0x0B, SubClassId, Protocol>; - using ContentSecurity = UsbClassDescriptorInit<0x0D, 0x00, 0x00>; - template - using Video = UsbClassDescriptorInit<0x0E, SubClassId, Protocol>; - template - using PersonalHealthcare = UsbClassDescriptorInit<0x0F, SubClassId, Protocol>; - - using AVControl = UsbClassDescriptorInit<0x10, 0x01, 0x00>; - using AVData0 = UsbClassDescriptorInit<0x10, 0x02, 0x00>; - using AVData1 = UsbClassDescriptorInit<0x10, 0x03, 0x00>; - - using TypeCBridge = UsbClassDescriptorInit<0x12, 0x00, 0x00>; - - template - using Diagnostic = UsbClassDescriptorInit<0xDC, SubClassId, Protocol>; - - namespace WirelessController { - using BluetoothProgramming = UsbClassDescriptorInit<0xE0, 0x01, 0x01>; - using UWBRadioControl = UsbClassDescriptorInit<0xE0, 0x01, 0x02>; - using RemoteNDIS = UsbClassDescriptorInit<0xE0, 0x01, 0x03>; - using BluetoothAMPController = UsbClassDescriptorInit<0xE0, 0x01, 0x04>; - - using HostWireAdapterControlData = UsbClassDescriptorInit<0xE0, 0x02, 0x01>; - using DeviceWireAdapterControlData = UsbClassDescriptorInit<0xE0, 0x02, 0x02>; - using DeviceWireAdapterIsochronous = UsbClassDescriptorInit<0xE0, 0x02, 0x03>; - } - - namespace ApplicationSpecific { - using DFU = UsbClassDescriptorInit<0xFE, 0x01, 0x01>; - using IRDABridge = UsbClassDescriptorInit<0xFE, 0x02, 0x00>; - - using TestAndMeasurement = UsbClassDescriptorInit<0xFE, 0x03, 0x00>; - using TestAndMeasurement_USBTMC_USB488 = UsbClassDescriptorInit<0xFE, 0x03, 0x01>; - } - - namespace Miscellaneous = UsbClass::Device::Miscellaneous; - - template - using VendorSpecific = UsbClassDescriptorInit<0xFF, SubClassId, Protocol>; - } - } - - struct UsbVersion { - using SubMinor = BitFieldMember; - using Minor = BitFieldMember; - using Major = BitFieldMember; - - constexpr UsbVersion(const uint8_t major, const uint8_t minor = 0, const uint8_t subMinor = 0) - :value(SubMinor::assign(Minor::assign(Major::assign(0, major), minor), subMinor)){ - } - constexpr UsbVersion() : value(0) {} - constexpr UsbVersion& operator=(const uint16_t value) { - this->value = value; - return *this; - } - union { - uint16_t value; - Major major; - Minor minor; - SubMinor subMinor; - }; - }; - - - - template - struct UsbVersionInit : public UsbVersion - { - static constexpr uint8_t MajorVersion = _MajorVersion; - static constexpr uint8_t MinorVersion = _MinorVersion; - static constexpr uint8_t SubMinorVersion = _SubMinorVersion; - constexpr UsbVersionInit() :UsbVersion{ MajorVersion, MinorVersion, SubMinorVersion } {} - }; - - template - struct LanguageIDStringDescriptor : public USBDescriptorInit> { - static constexpr DescriptorType Type = DescriptorType::StringDescriptor; - std::array languages; - }; - - inline uint8_t* MakeStringDescriptor(const char* ansiString, void* buffer, std::size_t bufferLength, std::uint16_t* outSize){ - auto outPtr = reinterpret_cast(buffer); - uint16_t result = 0U; - //TODO: check bufferLength overflow - if (ansiString != NULL){ - outPtr[result++] = 0; - outPtr[result++] = static_cast(DescriptorType::StringDescriptor); - - while (*ansiString != '\0'){ - outPtr[result++] = *ansiString++; - outPtr[result++] = 0U; - } - outPtr[0] = result; - } - *outSize = result; - return outPtr; - } - - struct DeviceDescriptor : public USBDescriptorInit { - static constexpr DescriptorType Type = DescriptorType::DeviceDescriptor; - UsbVersion bcdUSB; - UsbClassDescriptor classDescription; - uint8_t bMaxPacketSize0 = 64; //8, 16, 32, 64 - uint16_t idVendor = 0; - uint16_t idProduct = 0; - UsbVersion bcdDevice; - uint8_t iManufacturer = 0; - uint8_t iProduct = 0; - uint8_t iSerialNumber = 0; - uint8_t bNumConfigurations = 0; - }; - static_assert(sizeof(DeviceDescriptor) == 18, "Invalid packet size"); - - - class UsbCurrent { - public: - UsbCurrent(){ - set(500); - } - void set(uint16_t currentMa){ - _value = currentMa >> 1; - } - UsbCurrent& operator = (uint16_t value) { - set(value); - return *this; - } - private: - std::uint8_t _value; - }; - - struct ConfigurationDescriptor : public USBDescriptorInit { - static constexpr DescriptorType Type = DescriptorType::ConfigurationDescriptor; - uint16_t wTotalLength; - uint8_t bNumInterfaces; - uint8_t bConfigurationValue; - uint8_t iConfiguration; - uint8_t bmAttributes; - UsbCurrent bMaxPower; - }; - static_assert(sizeof(ConfigurationDescriptor) == 9, "Invalid packet size"); - - struct InterfaceDescriptor : public USBDescriptorInit { - static constexpr DescriptorType Type = DescriptorType::InterfaceDescriptor; - uint8_t bInterfaceNumber; - uint8_t bAlternateSetting; - uint8_t bNumEndpoints; - UsbClassDescriptor classDescription; - uint8_t iInterface; - }; - static_assert(sizeof(InterfaceDescriptor) == 9, "Invalid packet size"); - - struct EndpointAttributes{ - uint8_t value; - - constexpr EndpointAttributes():value(0){} - - constexpr EndpointAttributes(EndpointType type, EndpointSynchronizationType syncType = EndpointSynchronizationType::NoSynchonisation, EndpointUsageType usageType = EndpointUsageType::DataEndpoint) - : value(static_cast(static_cast(type) | (static_cast(syncType) << 2) | (static_cast(usageType) << 4))){ - - } - - constexpr EndpointType getType() const { - return static_cast(value & 0x03); - } - - constexpr void setType(EndpointType type) { - value = (value & ~0x03) | static_cast(type); - } - - constexpr EndpointSynchronizationType getSynchronizationType() const { - return static_cast((value >> 2) & 0x03); - } - - constexpr EndpointUsageType getUsageType() const { - return static_cast((value >> 4) & 0x03); - } - }; - - struct EndpointDescriptor : public USBDescriptorInit { - static constexpr DescriptorType Type = DescriptorType::EndpointDescriptor; - EndpointAddress bEndpointAddress; - EndpointAttributes bmAttributes; - uint16_t wMaxPacketSize = 0; - uint8_t bInterval = 0; - }; - static_assert(sizeof(EndpointDescriptor) == 7, "Invalid packet size"); - - struct DeviceQualifierDescriptor : public USBDescriptorInit { - static constexpr DescriptorType Type = DescriptorType::DeviceQualifierDescriptor; - UsbVersion bcdUSB; - UsbClassDescriptor classDescription; - uint8_t bMaxPacketSize0; - uint8_t bNumConfigurations; - uint8_t bReserved; - - DeviceQualifierDescriptor(UsbVersion bcdUSB, UsbClassDescriptor classDescription, uint8_t bMaxPacketSize0, uint8_t bNumConfigurations, uint8_t bReserved) - :bcdUSB(bcdUSB), classDescription(classDescription), bMaxPacketSize0(bMaxPacketSize0), bNumConfigurations(bNumConfigurations), bReserved(bReserved) - { - - } - }; - //TODO: validate - static_assert(sizeof(DeviceQualifierDescriptor) == 10, "Invalid packet size"); - - struct InterfaceAssociationDescriptor : public USBDescriptorInit { - static constexpr DescriptorType Type = DescriptorType::InterfaceAssociationDescriptor; - uint8_t bFirstInterface; - uint8_t bInterfaceCount; - UsbClassDescriptor classDescription; - uint8_t iFunction; - }; - //TODO: validate - static_assert(sizeof(InterfaceAssociationDescriptor) == 8, "Invalid packet size"); - - - -#pragma pack(pop) - } -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/USBTypesTest.cpp b/Dependencies/LFramework/Src/LFramework/USB/USBTypesTest.cpp deleted file mode 100644 index 4d51871..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/USBTypesTest.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef _WIN32 - -#include "USBTypes.h" -#include "../UnitTest/UnitTest.h" - -using namespace LFramework; -using namespace LFramework::USB; - -TEST(USB_Setup_bmRequestType) { - SetupPacket setup; - - setup.bmRequestType.Direction = RequestDirection::HostToDevice; - TEST_TRUE(setup.bmRequestType.Direction == RequestDirection::HostToDevice); - setup.bmRequestType.Direction = RequestDirection::DeviceToHost; - TEST_TRUE(setup.bmRequestType.Direction == RequestDirection::DeviceToHost); - - setup.bmRequestType.Type = RequestType::Standard; - TEST_TRUE(setup.bmRequestType.Type == RequestType::Standard); - setup.bmRequestType.Type = RequestType::Class; - TEST_TRUE(setup.bmRequestType.Type == RequestType::Class); - setup.bmRequestType.Type = RequestType::Vendor; - TEST_TRUE(setup.bmRequestType.Type == RequestType::Vendor); - setup.bmRequestType.Type = RequestType::Reserved; - TEST_TRUE(setup.bmRequestType.Type == RequestType::Reserved); - - setup.bmRequestType.Recipient = RequestRecipient::Device; - TEST_TRUE(setup.bmRequestType.Recipient == RequestRecipient::Device); - setup.bmRequestType.Recipient = RequestRecipient::Interface; - TEST_TRUE(setup.bmRequestType.Recipient == RequestRecipient::Interface); - setup.bmRequestType.Recipient = RequestRecipient::Endpoint; - TEST_TRUE(setup.bmRequestType.Recipient == RequestRecipient::Endpoint); - setup.bmRequestType.Recipient = RequestRecipient::Other; - TEST_TRUE(setup.bmRequestType.Recipient == RequestRecipient::Other); -} -#endif diff --git a/Dependencies/LFramework/Src/LFramework/USB/UsbEndpoint.h b/Dependencies/LFramework/Src/LFramework/USB/UsbEndpoint.h deleted file mode 100644 index 16dbb7b..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/UsbEndpoint.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -namespace LFramework::USB { - -class UsbEndpoint { -public: - UsbEndpoint(const EndpointDescriptor descriptor):_descriptor(descriptor){ - - } - - const EndpointDescriptor& getDescriptor() const { - return _descriptor; - } - -private: - EndpointDescriptor _descriptor; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/UsbException.h b/Dependencies/LFramework/Src/LFramework/USB/UsbException.h deleted file mode 100644 index fc258cf..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/UsbException.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include -#include - -namespace LFramework::USB { - -class UsbException : public std::exception { -public: - UsbException(const std::string& message):_message(message){ } - char const* what() const override { - return _message.c_str(); - } -private: - std::string _message; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/UsbInterface.h b/Dependencies/LFramework/Src/LFramework/USB/UsbInterface.h deleted file mode 100644 index fa4db1a..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/UsbInterface.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "USBTypes.h" -#include "UsbEndpoint.h" - -#define USB_VENDOR_CODE_WINUSB 'P' - -namespace LFramework::USB { - -class UsbInterface { -public: - virtual ~UsbInterface() = default; - virtual UsbEndpoint* getEndpoint(uint8_t address) { - bool isIn = USB::EndpointAddress::isIn(address); - uint8_t id = 0; - while(true){ - auto ep = getEndpoint(isIn, id++); - if(ep == nullptr){ - return nullptr; - } - if(ep->getDescriptor().bEndpointAddress.value == address){ - return ep; - } - } - } - virtual UsbEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) = 0; - virtual const UsbEndpoint* getEndpoint(bool isInEndpoint, uint8_t id) const = 0; - virtual const USB::InterfaceDescriptor& getInterfaceDescriptor() const = 0; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/UsbMicrosoftTypes.h b/Dependencies/LFramework/Src/LFramework/USB/UsbMicrosoftTypes.h deleted file mode 100644 index 307bd10..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/UsbMicrosoftTypes.h +++ /dev/null @@ -1,146 +0,0 @@ -#pragma once - -#include -#include "USBTypes.h" - -namespace LFramework::USB::Microsoft { - - namespace Os20{ - enum class DescriptorType : std::uint16_t { - HeaderDescriptor = 0x00, - HeaderConfiguration = 0x01, - HeaderFunction = 0x02, - FeatureCompatibleId = 0x03, - FeatureRegProperty = 0x04, - FeatureMinResumeTime = 0x05, - FeatureModelId = 0x06, - FeatureCcgpDevice = 0x07, - FeatureVendorRevision = 0x08 - }; - - enum class PropertyDataType : uint32_t{ - String = 1, //A NULL-terminated Unicode String (REG_SZ) - EnvironmentVariablesString = 2, //A NULL-terminated Unicode String that includes environment variables - Binary = 3, //Free-form binary (REG_BINARY) - Int32LittleEndian = 4, //A little-endian 32-bit integer - Int32BigEndian = 5, //A big-endian 32-bit integer - SymLinkString = 6, //A NULL-terminated Unicode string that contains a symbolic link - StringArray = 7 //Multiple NULL-terminated Unicode strings - }; - } - - - -#pragma pack(push, 1) - - //"Entry point" descriptor for microsoft-compatible devices, should be accessible at index 0xEE - struct MicrosoftStringDescriptor : public USBDescriptor { - MicrosoftStringDescriptor(uint8_t bMS_VendorCode): - USBDescriptor(sizeof(MicrosoftStringDescriptor), DescriptorType::StringDescriptor), - qwSignature{ - 'M', 0x00, - 'S', 0x00, - 'F', 0x00, - 'T', 0x00, - '1', 0x00, - '0', 0x00, - '0', 0x00 - }, - bMS_VendorCode(bMS_VendorCode){ - } - uint8_t qwSignature[14]; - uint8_t bMS_VendorCode; - uint8_t bPad = 0; - }; - static_assert(sizeof(MicrosoftStringDescriptor) == 18, "Invalid packet size"); - - - namespace CompatId { - struct Header { //Header for MSOS feature descriptors - - uint32_t dwLength; - uint16_t bcdVersion = 0x0100; - uint16_t wIndex = 0x0004; //Extended compat ID descriptor identifier (0x0004) - uint8_t bCount; //number of function sections that follow - std::array RESERVED = {}; - }; - //TODO: validate - static_assert(sizeof(Header) == 16, "Invalid packet size"); - - struct Function { //Function descriptor section - uint8_t bFirstInterfaceNumber = {}; - uint8_t RESERVED0 = {}; - std::array compatibleID = {}; - std::array subCompatibleID = {}; - std::array RESERVED1 = {}; - }; - //TODO: validate - static_assert(sizeof(Function) == 24, "Invalid packet size"); - - struct WinUSBFunction { - Header header; - Function function; - - WinUSBFunction(uint8_t firstInterfaceNumber){ - header.dwLength = sizeof(WinUSBFunction); - header.bCount = 1; - function.bFirstInterfaceNumber = firstInterfaceNumber; - function.compatibleID = {0x57, 0x49, 0x4E, 0x55, 0x53, 0x42, 0x00, 0x00}; //WINUSB - } - }; - } - - namespace Property{ - struct Header { - uint32_t dwLength; - uint16_t bcdVersion = 0x0100; - uint16_t wIndex = 0x0005; //extended properties OS feature descriptor - uint16_t wCount; - }; - //TODO: validate - static_assert(sizeof(Header) == 10, "Invalid packet size"); - - template - struct Section{ - uint32_t dwSize = sizeof(Section); - Os20::PropertyDataType dwPropertyDataType; - uint16_t wPropertyNameLength = sizeof(Name); - Name bPropertyName; - uint32_t dwPropertyDataLength = sizeof(Data); - Data bPropertyData; - }; - - - static uint32_t ansiToWide(const char* src, char* dst, uint32_t dst_size){ - uint32_t dst_ready = 0; - while((*src) != '\0' && ((dst_size - dst_ready) >= 2)){ - dst[dst_ready++] = *src; - dst[dst_ready++] = '\0'; - src++; - } - if((dst_size - dst_ready) >= 2){ - dst[dst_ready++] = '\0'; - dst[dst_ready++] = '\0'; - } - return dst_ready; - } - - struct InterfaceGuid { - Header header; - Section, std::array> guidSection; - - InterfaceGuid(){ - header.dwLength = sizeof(InterfaceGuid); - header.wCount = 1; - - guidSection.dwPropertyDataType = Os20::PropertyDataType::String; - ansiToWide("DeviceInterfaceGUID", (char*)guidSection.bPropertyName.data(), sizeof(guidSection.bPropertyName)); - ansiToWide("{EEEEEEE3-50F3-4888-84B4-74E50E1649DC}", (char*)guidSection.bPropertyData.data(), sizeof(guidSection.bPropertyData)); - } - }; - } - -#pragma pack(pop) - -} - diff --git a/Dependencies/LFramework/Src/LFramework/USB/UsbPollingTransfer.h b/Dependencies/LFramework/Src/LFramework/USB/UsbPollingTransfer.h deleted file mode 100644 index 12fa70b..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/UsbPollingTransfer.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include "UsbTransfer.h" - -namespace LFramework::USB { - -class UsbPollingTransfer : public LFramework::USB::UsbTransfer { -public: - enum class State { - Pending, - Success, - Fail - }; - - UsbPollingTransfer(){ - callback = &UsbPollingTransfer::transferComleteCallbackStatic; - } - void reset(){ - _state = State::Pending; - size = 0; - actualSize = 0; - } - State getState() const { - return _state; - } -private: - State _state = State::Pending; - void transferComleteCallback(bool success){ - _state = success ? State::Success : State::Fail; - } - - static void transferComleteCallbackStatic(LFramework::USB::UsbTransfer* _this, bool success){ - static_cast(_this)->transferComleteCallback(success); - } -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/UsbTransfer.h b/Dependencies/LFramework/Src/LFramework/USB/UsbTransfer.h deleted file mode 100644 index e9b52de..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/UsbTransfer.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -namespace LFramework::USB { - -class UsbTransfer { -public: - typedef void(*TransferCompleteCallback)(UsbTransfer*, bool); - void* buffer = nullptr; - std::uint32_t size = 0; - std::uint32_t actualSize = 0; - void* context = nullptr; - TransferCompleteCallback callback = nullptr; -}; - -} diff --git a/Dependencies/LFramework/Src/LFramework/USB/usbd_conf.h b/Dependencies/LFramework/Src/LFramework/USB/usbd_conf.h deleted file mode 100644 index d0d9352..0000000 --- a/Dependencies/LFramework/Src/LFramework/USB/usbd_conf.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef USB_CONF_H_ -#define USB_CONF_H_ -#include -#include - -#define USBD_MAX_NUM_INTERFACES 1 -#define USBD_MAX_NUM_CONFIGURATION 1 -#define USBD_MAX_STR_DESC_SIZ 512 -#define USBD_SUPPORT_USER_STRING 1 -#define USBD_DEBUG_LEVEL 0 -#define USBD_SELF_POWERED 1 - -#endif - diff --git a/Dependencies/LFramework/Src/LFramework/UnitTest/CMakeLists.txt b/Dependencies/LFramework/Src/LFramework/UnitTest/CMakeLists.txt deleted file mode 100644 index 2bc07f6..0000000 --- a/Dependencies/LFramework/Src/LFramework/UnitTest/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -add_library(LFrameworkUnitTest INTERFACE ) -add_library(LFramework::UnitTest ALIAS LFrameworkUnitTest ) - -target_sources(LFrameworkUnitTest -INTERFACE - UnitTest.h - UnitTest.cpp -) diff --git a/Dependencies/LFramework/Src/LFramework/UnitTest/UnitTest.cpp b/Dependencies/LFramework/Src/LFramework/UnitTest/UnitTest.cpp deleted file mode 100644 index 0674308..0000000 --- a/Dependencies/LFramework/Src/LFramework/UnitTest/UnitTest.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* - * UnitTest.cpp - * - * Created on: 27 Aug. 2017 г. - * Author: l-pro - */ - -#include "UnitTest.h" -#include "../Debug.h" - -namespace LFramework { namespace Testing { - - LinkedList& getTestsList() { - static LinkedList list; - return list; - } - - void runAllTests() { - getTestsList().foreach([](auto node) { runTest((Test*)node);}); - } - - TestResult runTest(Test* test){ - lfDebug() << "[ RUN ]" << test->name; - auto result = test->run(); - lfDebug() << (result.success ? "[ PASSED ]" : "[ FAILED ]") << test->name; - if (result.message != nullptr) { - lfDebug() << result.message; - } - return result; - } - -}} - - - - diff --git a/Dependencies/LFramework/Src/LFramework/UnitTest/UnitTest.h b/Dependencies/LFramework/Src/LFramework/UnitTest/UnitTest.h deleted file mode 100644 index e1202f9..0000000 --- a/Dependencies/LFramework/Src/LFramework/UnitTest/UnitTest.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * UnitTest.h - * - * Created on: 26 aug. 2017 ã. - * Author: l-pro - */ - -#ifndef MCUFRAMEWORK_UNITTEST_UNITTEST_H_ -#define MCUFRAMEWORK_UNITTEST_UNITTEST_H_ - -#include "../Containers/LinkedList.h" - -namespace LFramework { namespace Testing { - - LinkedList& getTestsList(); - void runAllTests(); - - struct TestResult { - bool success = false; - const char* message = nullptr; - - operator bool() const { - return success; - } - }; - - typedef void(*TestFunction)(TestResult& result); - - struct Test : public LinkedListItem { - const char* name = nullptr; - - Test(const char* name, TestFunction testFunc): name(name), _test(testFunc){ - getTestsList().pushBack(this); - } - - TestResult run(){ - TestResult result{}; - result.success = true; - _test(result); - return result; - } - private: - TestFunction _test; - }; - - -#define TEST_FUNC_NAME(name) test_##name - -#define TEST_FUNC(name) static void TEST_FUNC_NAME(name) (LFramework::Testing::TestResult& result) - -#define TEST_OBJECT_NAME(name) test_##name##Object - -#define TEST_REGISTER(name) \ - LFramework::Testing::Test TEST_OBJECT_NAME(name) (#name, TEST_FUNC_NAME(name) ); \ - -#define TEST_IMPORT(name) extern LFramework::Testing::Test TEST_OBJECT_NAME(name); - -#define TEST(name) \ - TEST_FUNC(name); \ - TEST_REGISTER(name); \ - TEST_FUNC(name) - -#define TEST_ASSERT(__expression, __message)\ - if(!(__expression)) { \ - result.message = __message; \ - result.success = false; \ - return; \ - } - -#define TEST_TRUE(__expression) \ - TEST_ASSERT(__expression, "Expression is not true: " #__expression) - - -#define TEST_RUN(name) runTest(&TEST_OBJECT_NAME(name)) - - - TestResult runTest(Test* test); - -}} - - -#endif /* MCUFRAMEWORK_UNITTEST_UNITTEST_H_ */ diff --git a/Dependencies/LMath/.gitattributes b/Dependencies/LMath/.gitattributes deleted file mode 100644 index 1ff0c42..0000000 --- a/Dependencies/LMath/.gitattributes +++ /dev/null @@ -1,63 +0,0 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### -* text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain diff --git a/Dependencies/LMath/.gitignore b/Dependencies/LMath/.gitignore deleted file mode 100644 index a535109..0000000 --- a/Dependencies/LMath/.gitignore +++ /dev/null @@ -1,246 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -[Xx]64/ -[Xx]86/ -[Bb]uild/ -bld/ -[Bb]in/ -[Oo]bj/ - -# Visual Studio 2015 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# DNX -project.lock.json -artifacts/ - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml - -# TODO: Un-comment the next line if you do not want to checkin -# your web deploy settings because they may include unencrypted -# passwords -#*.pubxml -*.publishproj - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config -# NuGet v3's project.json files produces more ignoreable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Microsoft Azure ApplicationInsights config file -ApplicationInsights.config - -# Windows Store app package directory -AppPackages/ -BundleArtifacts/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -[Ss]tyle[Cc]op.* -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.pfx -*.publishsettings -node_modules/ -orleans.codegen.cs - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# LightSwitch generated files -GeneratedArtifacts/ -ModelManifest.xml - -# Paket dependency manager -.paket/paket.exe - -# FAKE - F# Make -.fake/ -*.db -*.filters diff --git a/Dependencies/LMath/CMakeLists.txt b/Dependencies/LMath/CMakeLists.txt deleted file mode 100644 index 1a3087b..0000000 --- a/Dependencies/LMath/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -cmake_minimum_required(VERSION 3.21) -add_library(LMath INTERFACE) -add_subdirectory(Src/LMath) -target_include_directories(LMath INTERFACE Src) \ No newline at end of file diff --git a/Dependencies/LMath/README.md b/Dependencies/LMath/README.md deleted file mode 100644 index 1200d73..0000000 --- a/Dependencies/LMath/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# lmath -C++ template vector math library with AMP, (SSE2, NEON and so on.. in future...) support diff --git a/Dependencies/LMath/Src/LMath/CMakeLists.txt b/Dependencies/LMath/Src/LMath/CMakeLists.txt deleted file mode 100644 index b56df7a..0000000 --- a/Dependencies/LMath/Src/LMath/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -target_sources(LMath -INTERFACE - lmath.h - lm_common.h - lm_common_intrin.h - lm_constants.h - lm_half.h - lm_macro.h - lm_matrix.h - lm_matrix_traits.h - lm_plane.h - lm_plane_intrin.h - lm_quaternion.h - lm_quaternion_intrin.h - lm_stdio.h - lm_traits.h - lm_types.h - lm_vector.h - lm_vector_avx.h - lm_vector_sse.h - lm_vector_traits.h -) diff --git a/Dependencies/LMath/Src/LMath/lm_common.h b/Dependencies/LMath/Src/LMath/lm_common.h deleted file mode 100644 index 17544bb..0000000 --- a/Dependencies/LMath/Src/LMath/lm_common.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef lm_common_h__ -#define lm_common_h__ - -#include "lm_vector_traits.h" -#include "lm_matrix_traits.h" - -namespace lm{ - /*namespace common_traits { - template::value> - struct field_type { - typedef typename T::element_type type; - }; - - template - struct field_type { - typedef T type; - }; - }*/ - - /*template::value> - struct transform_copy_helper { - template - static auto execute(const T& v, OpUnary op)RESTRICT(cpu) { - typename std::remove_cv::type result; - for (LmSize i = 0; i < T::size; ++i) { - result.data[i] = op(v.data[i]); - } - return result; - } -#if defined(LM_AMP_SUPPORTED) - template - static auto execute(const T& v, OpUnary op)RESTRICT(amp) { - std::remove_cv::type result; - for (LmSize i = 0; i < T::size; ++i) { - result.data[i] = op(v.data[i]); - } - return result; - } -#endif - };*/ - - - /*template - struct transform_copy_helper { - template - static auto execute(const T& v, OpUnary op) RESTRICT(cpu) { - return op(v); - } -#if defined(LM_AMP_SUPPORTED) - template - static auto execute(const T& v, OpUnary op) RESTRICT(amp) { - return op(v); - } -#endif - };*/ -} - -#endif // lm_common_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_common_intrin.h b/Dependencies/LMath/Src/LMath/lm_common_intrin.h deleted file mode 100644 index 136f551..0000000 --- a/Dependencies/LMath/Src/LMath/lm_common_intrin.h +++ /dev/null @@ -1,128 +0,0 @@ -#ifndef lm_common_intrin_h__ -#define lm_common_intrin_h__ - -#include "lm_vector.h" -#include "lm_matrix.h" -#include "lm_common.h" -#include "lm_quaternion.h" -#include "lm_types.h" - -#include -#include -#include - -namespace lm { - -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - - template - static inline Matrix matrix4x4LookatLh(const Vector& position, const Vector& target, const Vector& up_direction) { - auto forward = lm::normalize(target - position); - auto right = lm::normalize(lm::cross(up_direction, forward)); - auto up = lm::normalize(lm::cross(forward, right)); - - auto zero = DefaultValues::zero(); - auto one = DefaultValues::one(); - - return Matrix{ - Vector(right, -lm::dot(right, position)), - Vector(up, -lm::dot(up, position)), - Vector(forward, -lm::dot(forward, position)), - Vector(zero, zero, zero, one) - }; - } - - template - static inline Matrix matrix4x4Perspective(T fov, T aspect, T near_clip, T far_clip) { - auto zero = DefaultValues::zero(); - auto one = DefaultValues::one(); - auto two = DefaultValues::two(); - auto yScale = one / (lm::tan(fov / two)); - return Matrix( - Vector(yScale / aspect, zero, zero, zero), - Vector(zero, -yScale, zero, zero), - Vector(zero, zero, far_clip / (far_clip - near_clip), (-near_clip * far_clip) / (far_clip - near_clip)), - Vector(zero, zero, one, zero)); - } - - template - static inline Matrix matrix4x4RotationY(float angleInRadians) { - auto cosAngle = lm::cos(angleInRadians); - auto sinAngle = lm::sin(angleInRadians); - - auto zero = DefaultValues::zero(); - auto one = DefaultValues::one(); - - return Matrix( - Vector(cosAngle, zero, sinAngle, zero), - Vector(zero, one, zero, zero), - Vector(-sinAngle, zero, cosAngle, zero), - Vector(zero, zero, zero, one));; - } - - - template - static inline Matrix matrix4x4RotationQuaternion(const lm::Quaternion& q) { - auto num1 = q[0] * q[0]; - auto num2 = q[1] * q[1]; - auto num3 = q[2] * q[2]; - auto num4 = q[0] * q[1]; - auto num5 = q[2] * q[3]; - auto num6 = q[2] * q[0]; - auto num7 = q[1] * q[3]; - auto num8 = q[1] * q[2]; - auto num9 = q[0] * q[3]; - - auto zero = DefaultValues::zero(); - auto one = DefaultValues::one(); - auto two = DefaultValues::two(); - - return Matrix( - Vector(one - two * (num2 + num3), two * (num4 - num5), two * (num6 + num7), zero), - Vector(two * (num4 + num5), one - two * (num3 + num1), two * (num8 - num9), zero), - Vector(two * (num6 - num7), two * (num8 + num9), one - two * (num2 + num1), zero), - Vector(zero, zero, zero, one)); - } - - template - static inline Matrix matrix4x4Scale(T sx, T sy, T sz) { - - auto zero = DefaultValues::zero(); - auto one = DefaultValues::one(); - - return Matrix( - Vector(sx, zero, zero, zero), - Vector(zero, sy, zero, zero), - Vector(zero, zero, sz, zero), - Vector(zero, zero, zero, one)); - } - - template - static inline Matrix matrix4x4Scale(const Vector& scale) { - return matrix4x4Scale(scale.x(), scale.y(), scale.z()); - } - - template - static inline Matrix matrix4x4Translation(T x, T y, T z) { - auto zero = DefaultValues::zero(); - auto one = DefaultValues::one(); - - return Matrix( - Vector(one, zero, zero, x), - Vector(zero, one, zero, y), - Vector(zero, zero, one, z), - Vector(zero, zero, zero, one)); - } - - template - static inline Matrix matrix4x4Translation(const Vector& position) { - return matrix4x4Translation(position.x(), position.y(), position.z()); - } -} -#endif // lm_common_intrin_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_constants.h b/Dependencies/LMath/Src/LMath/lm_constants.h deleted file mode 100644 index c485c2c..0000000 --- a/Dependencies/LMath/Src/LMath/lm_constants.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef lm_constants_h__ -#define lm_constants_h__ - -namespace lm { - static constexpr double pi_d = 3.14159265358979; - static constexpr float pi_f = 3.14159265358979f; -} -#endif // lm_constants_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_half.h b/Dependencies/LMath/Src/LMath/lm_half.h deleted file mode 100644 index cc64c93..0000000 --- a/Dependencies/LMath/Src/LMath/lm_half.h +++ /dev/null @@ -1,217 +0,0 @@ -#ifndef LM_HALF_h__ -#define LM_HALF_h__ - -#include -#include "lm_types.h" - -namespace lm{ - - class Half{ - private: - struct FI32{ - static_assert(sizeof(float) == 4, "Not supported float size"); - float& f() { - return *(reinterpret_cast(&i)); - } - uint32_t i; - }; - std::uint16_t data; - public: - bool isNan() { - return ((data & 0x7c00) == 0x7c00) && ((data & 0x3ff) != 0); - } - bool isInf() { - return ((data & 0x7c00) == 0x7c00) && ((data & 0x3ff) == 0); - } - bool isSubnormal() { - return ((data & 0x7c00) == 0) && ((data & 0x3ff) != 0); - } - bool isPositive() { - return (data & 0x8000) == 0; - } - bool isZero() { - return (data & 0x7fff) == 0; - } - const float toFloat() const { - return toFloat(*this); - } - static Half toHalf(float src) { - Half dst; - FI32 fi; - fi.f() = src; - int32_t s,m,e; - - //fp32 exponent zero offset = 127 - //fp16 exponent zero offset = 15 - - s = (fi.i >> 16) & 0x8000; //-V519 - m = fi.i & 0x7fffff; //-V519 - //decode exponent from fp32 and encode to fp16 - e = ((fi.i >> 23) & 0xff) - 127 + 15; //-V519 - - if ((e > 0) && (e < 30)){ - //simple case, no exp overflow, just loose precision - dst.data = static_cast((s) | (e << 10) | ((m + 0x1000) >> 13)); - }else if(src == 0.0f){ - //handle zero - dst.data = 0; - }else{ - //subnormal values - if(e <= 0){ - if(e < -10){ //-10-15 = -25(exp) - too small value to represent in half float - dst.data = 0; - }else{//just subnormal value, representable in half - //add explicitly 1 leading bit - m = (m | 0x800000) >> (-e + 1); - - //round to bigger value - if(m & 0x1000) - m |= 0x2000; - dst.data = static_cast((s) | (m >> 13)); - } - }else if(e == 0xff - 127 + 15){//exp exactly on NAN or INF - //mantissa == 0 and exp == 11111 then inf - //else, if mantissa != 0 -> NAN - if(m == 0){//INF - dst.data = static_cast(s | 0x7c00); - }else{//NAN - dst.data = static_cast(s | 0x7c00 | (m >> 13)); - } - }else{//Exp should be > 0 (> 30 or 0 + 1 (rounded)) - //round - if(m & 0x1000){ - m += 0x2000; - if(m & 0x800000){ - m = 0; - e++; - } - } - if(e > 30){//exp overflow - dst.data = static_cast(s | 0x7c00);//too big val, inf - }else{// - dst.data = static_cast((s) | (e << 10) | (m >> 13)); - } - } - } - return dst; - } - static float toFloat(const Half& src) { - int s, e, m; - FI32 fi; - s = src.data >> 15; - e = (src.data & 0x7c00) >> 10; - m = (src.data & 0x3ff); - - if(e > 0 && e < 31){//normalized val - fi.i = (s << 31) | ((e - 15 + 127) << 23) | (m << 13); - }else if((e == 0) && (m == 0)){//signed zero - fi.i = s << 31; - }else if((e == 0) && (m != 0)){//denormalized value - //normalize value - while(!(m & 0x400)){ - m <<= 1; - e--; - } - e++; - m = m & 0x3ff; - fi.i = (s << 31) | ((e - 15 + 127) << 23) | (m << 13); - }else if((e == 31) && (m == 0)){//INF - fi.i = (s << 31) | 0x7f800000; - }else{ - fi.i = (s << 31) | 0x7f800000 | (m << 13); - } - return fi.f(); - } - - Half() { - - } - Half(const Half& val) { - data = val.data; - } - Half(const float& val) { - *this = toHalf(val); - } - Half& operator =(const float& other) { - *this = toHalf(other); - return *this; - } - - //operators - Half operator +() { - return *this; - } - Half operator -() { - return toHalf(-toFloat()); - } - Half operator +(const Half& rval) { - return toHalf(this->toFloat() + rval.toFloat()); - } - Half operator -(const Half& rval) { - return toHalf(this->toFloat() - rval.toFloat()); - } - Half operator *(const Half& rval) { - return toHalf(this->toFloat() * rval.toFloat()); - } - Half operator /(const Half& rval) { - return toHalf(this->toFloat() / rval.toFloat()); - } - - bool operator ==(const Half& rval) { - return data == rval.data; - } - bool operator !=(const Half& rval) { - return data != rval.data; - } - bool operator <(const Half& rval) { - return this->toFloat() < rval.toFloat(); - } - bool operator >(const Half& rval) { - return this->toFloat() > rval.toFloat(); - } - bool operator <=(const Half& rval) { - return this->toFloat() <= rval.toFloat(); - } - bool operator >=(const Half& rval) { - return this->toFloat() >= rval.toFloat(); - } - Half& operator +=(const Half& rval) { - *this = toHalf(this->toFloat() + rval.toFloat()); - return *this; - } - Half& operator -=(const Half& rval) { - *this = toHalf(this->toFloat() - rval.toFloat()); - return *this; - } - Half& operator *=(const Half& rval) { - *this = toHalf(this->toFloat() * rval.toFloat()); - return *this; - } - Half& operator /=(const Half& rval) { - *this = toHalf(this->toFloat() / rval.toFloat()); - return *this; - } - - const Half& operator++() { - *this = toHalf(this->toFloat() + 1.0f); - return *this; - } - const Half operator++(int) { - Half old(*this); - *this = toHalf(this->toFloat() + 1.0f); - return old; - } - const Half& operator--() { - *this = toHalf(this->toFloat() - 1.0f); - return *this; - } - const Half operator--(int) { - Half old(*this); - *this = toHalf(this->toFloat() - 1.0f); - return old; - } - }; - - typedef Half half; -} -#endif // LM_HALF_h__ \ No newline at end of file diff --git a/Dependencies/LMath/Src/LMath/lm_macro.h b/Dependencies/LMath/Src/LMath/lm_macro.h deleted file mode 100644 index 5a9294e..0000000 --- a/Dependencies/LMath/Src/LMath/lm_macro.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef lm_macro_h__ -#define lm_macro_h__ - -#define EMPTY_SUFFIX -#define UNPACK(...) __VA_ARGS__ -#define GEN_METHOD(_Method) _Method(EMPTY_SUFFIX) ENABLE_IF_AMP( _Method(restrict(amp)) ) - -#define GEN_METHOD_CONST(_Method) _Method(const) ENABLE_IF_AMP( _Method(const restrict(amp)) ) - -#define GEN_METHOD2(_Method) _Method(EMPTY_SUFFIX, EMPTY_SUFFIX) _Method(const, const) ENABLE_IF_AMP( _Method(EMPTY_SUFFIX, restrict(amp)) _Method(const, const restrict(amp)) ) - -#define GEN_METHOD_PARAMS(_Method, ...) UNPACK(_Method(__VA_ARGS__, EMPTY_SUFFIX)) UNPACK( ENABLE_IF_AMP( _Method(__VA_ARGS__, restrict(amp)) )) - -#endif // lm_macro_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_matrix.h b/Dependencies/LMath/Src/LMath/lm_matrix.h deleted file mode 100644 index c4eb8d6..0000000 --- a/Dependencies/LMath/Src/LMath/lm_matrix.h +++ /dev/null @@ -1,218 +0,0 @@ -#ifndef lm_matrix_h__ -#define lm_matrix_h__ - -#include "lm_vector.h" -#include "lm_types.h" -#include -#include "lm_matrix_traits.h" -#include - -namespace lm { - template - struct Matrix : public Vector, M> { - typedef Vector Row; - typedef Vector, M> Base; - - template> - Matrix(const Args& ... rest) RESTRICT(cpu) : Base{ rest... } {} - - constexpr Matrix() RESTRICT(cpu, amp) {} - - Matrix(const Matrix& m) RESTRICT(cpu, amp) : Base{ (const Base&)m } {} - - Matrix(const Vector, M>& m) RESTRICT(cpu, amp) : Base{ m } {} - - auto getColumn(LmSize id) const RESTRICT(cpu, amp) { - Vector result; - for (LmSize i = 0; i < M; ++i) { - result[i] = this->get(i)[id]; - } - return result; - } - - - static Matrix identity() RESTRICT(cpu, amp) { - auto zero = DefaultValues::zero(); - Matrix result(zero); - for (LmSize y = 0; y < M; ++y) { - result[y][y] = static_cast(1); - } - return result; - } - - template> - operator Matrix() const RESTRICT(cpu, amp) { - Matrix result; - for (LmSize y = 0; y < M2; ++y){ - for (LmSize x = 0; x < N2; ++x) { - result[y][x] = this->data[y][x]; - } - } - return result; - } - }; - - template - auto mul(const Matrix& left, const Matrix& right) RESTRICT(cpu, amp) { - auto result = Matrix, M, N2>{}; - for (LmSize y = 0; y < M; ++y) { - for (LmSize x = 0; x < N2; ++x) { - - result[y][x] = DefaultValues>::zero(); - - for (LmSize i = 0; i < N; ++i) { - result[y][x] += left[y][i] * right[i][x]; - } - } - } - return result; - } - - template - auto mul(const Matrix& left, const Vector& right) RESTRICT(cpu, amp) { - auto result = Vector, N>{}; - for (LmSize y = 0; y < M; ++y) { - result[y] = dot(left[y], right); - } - return result; - } - - template> - auto determinant(const Matrix& m) RESTRICT(cpu, amp) { - return m[0][0] * m[1][1] - m[0][1] * m[1][0]; - } - - - template> - auto determinantAffine(const Matrix& m) RESTRICT(cpu, amp) { - return - (m[0][0] * m[1][1] * m[2][2] + m[1][0] * m[2][1] * m[0][2] + m[0][1] * m[1][2] * m[2][0]) - - (m[0][2] * m[1][1] * m[2][0] + m[0][1] * m[1][0] * m[2][2] + m[1][2] * m[2][1] * m[0][0]); - } - - template - Matrix transpose(const Matrix& v) RESTRICT(cpu, amp) { - Matrix result; - - for (LmSize y = 0; y < M; ++y) { - for (LmSize x = 0; x < N; ++x) { - result[x][y] = v[y][x]; - } - } - - return result; - } - - - template - Matrix inverse(const Matrix& u, bool affine) RESTRICT(cpu, amp) { - Matrix result; - if (affine) { - T s = static_cast(1) / determinantAffine(u); - result[0][0] = (u[1][1] * u[2][2] - u[1][2] * u[2][1]) * s; - result[0][1] = (u[2][1] * u[0][2] - u[2][2] * u[0][1]) * s; - result[0][2] = (u[0][1] * u[1][2] - u[0][2] * u[1][1]) * s; - result[0][3] = u[0][3]; - result[1][0] = (u[1][2] * u[2][0] - u[1][0] * u[2][2]) * s; - result[1][1] = (u[2][2] * u[0][0] - u[2][0] * u[0][2]) * s; - result[1][2] = (u[0][2] * u[1][0] - u[0][0] * u[1][2]) * s; - result[1][3] = u[1][3]; - result[2][0] = (u[1][0] * u[2][1] - u[1][1] * u[2][0]) * s; - result[2][1] = (u[2][0] * u[0][1] - u[2][1] * u[0][0]) * s; - result[2][2] = (u[0][0] * u[1][1] - u[0][1] * u[1][0]) * s; - result[2][3] = u[2][3]; - result[3][0] = -(result[0][0] * u[3][0] + result[1][0] * u[3][1] + result[2][0] * u[3][2]); - result[3][1] = -(result[0][1] * u[3][0] + result[1][1] * u[3][1] + result[2][1] * u[3][2]); - result[3][2] = -(result[0][2] * u[3][0] + result[1][2] * u[3][1] + result[2][2] * u[3][2]); - result[3][3] = u[3][3]; - } - else { - - // transpose matrix - T src[16]; - for (size_t i = 0; i < 4; ++i) { - src[i] = u[i][0]; - src[i + 4] = u[i][1]; - src[i + 8] = u[i][2]; - src[i + 12] = u[i][3]; - } - - // calculate pairs for first 8 elements (cofactors) - T tmp[12]; // temp array for pairs - tmp[0] = src[10] * src[15]; - tmp[1] = src[11] * src[14]; - tmp[2] = src[9] * src[15]; - tmp[3] = src[11] * src[13]; - tmp[4] = src[9] * src[14]; - tmp[5] = src[10] * src[13]; - tmp[6] = src[8] * src[15]; - tmp[7] = src[11] * src[12]; - tmp[8] = src[8] * src[14]; - tmp[9] = src[10] * src[12]; - tmp[10] = src[8] * src[13]; - tmp[11] = src[9] * src[12]; - - // calculate first 8 elements (cofactors) - result[0][0] = (tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7]) - (tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7]); - result[0][1] = (tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7]) - (tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7]); - result[0][2] = (tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7]) - (tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7]); - result[0][3] = (tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6]) - (tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6]); - result[1][0] = (tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3]) - (tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3]); - result[1][1] = (tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3]) - (tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3]); - result[1][2] = (tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3]) - (tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3]); - result[1][3] = (tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2]) - (tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2]); - - // calculate pairs for second 8 elements (cofactors) - tmp[0] = src[2] * src[7]; - tmp[1] = src[3] * src[6]; - tmp[2] = src[1] * src[7]; - tmp[3] = src[3] * src[5]; - tmp[4] = src[1] * src[6]; - tmp[5] = src[2] * src[5]; - tmp[6] = src[0] * src[7]; - tmp[7] = src[3] * src[4]; - tmp[8] = src[0] * src[6]; - tmp[9] = src[2] * src[4]; - tmp[10] = src[0] * src[5]; - tmp[11] = src[1] * src[4]; - - // calculate second 8 elements (cofactors) - result[2][0] = (tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15]) - (tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15]); - result[2][1] = (tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15]) - (tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15]); - result[2][2] = (tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15]) - (tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15]); - result[2][3] = (tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14]) - (tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14]); - result[3][0] = (tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9]) - (tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10]); - result[3][1] = (tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10]) - (tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8]); - result[3][2] = (tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8]) - (tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9]); - result[3][3] = (tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9]) - (tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8]); - - // calculate determinant - T det = src[0] * result[0][0] + src[1] * result[0][1] + src[2] * result[0][2] + src[3] * result[0][3]; - - // calculate matrix inverse - det = static_cast(1) / det; - - for (LmSize i = 0; i < 4; ++i) { - for (LmSize j = 0; j < 4; ++j) { - result[i][j] *= det; - } - } - } - - return result; - } - - typedef Matrix float2x2; - typedef Matrix float2x3; - typedef Matrix float3x3; - typedef Matrix float3x4; - typedef Matrix float4x3; - typedef Matrix float4x4; - typedef Matrix double2x2; - typedef Matrix double2x3; - typedef Matrix double3x3; - typedef Matrix double3x4; - typedef Matrix double4x3; - typedef Matrix double4x4; -} -#endif // lm_matrix_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_matrix_traits.h b/Dependencies/LMath/Src/LMath/lm_matrix_traits.h deleted file mode 100644 index ec96967..0000000 --- a/Dependencies/LMath/Src/LMath/lm_matrix_traits.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef lm_matrix_traits_h__ -#define lm_matrix_traits_h__ - -#include "lm_vector_traits.h" -#include "lm_types.h" - -namespace lm{ - - - template - struct MatrixSize { - static constexpr size_t rows = VectorSize::value; - static constexpr size_t columns = VectorSize::value; - static constexpr auto value = lm::Vector(rows, columns); - }; - - template - struct MatrixRowType { - typedef typename T::ElementType type; - }; - - template - struct MatrixColumnType_ { - typedef Vector type; - }; - - template - struct MatrixColumnType_ { - typedef Vector type; - }; - - template - struct MatrixColumnType : MatrixColumnType_::value> { - }; - - - template - struct IsSquare { - static constexpr bool Value = MatrixSize::rows == MatrixSize::columns; - }; - - template - struct CanMultiplyMatrix { - static constexpr bool Value = MatrixSize::columns == MatrixSize::rows; - }; - - - - template - using DotResultType = MultiplyType()[0]), decltype(std::declval()[0])>; - -} - -#endif // lm_matrix_traits_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_plane.h b/Dependencies/LMath/Src/LMath/lm_plane.h deleted file mode 100644 index 65da73a..0000000 --- a/Dependencies/LMath/Src/LMath/lm_plane.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef lm_plane_h__ -#define lm_plane_h__ - -#include "lm_vector.h" - -namespace lm -{ - template - struct Plane { - union{ - T data[4]; - struct - { - lm::Vector normal; - T d; - }; - }; - - Plane() : normal(0,1,0), d(0) {} - - Plane(T _a, T _b, T _c, T _d) : normal(_a,_b,_c), d(_d) {} - - Plane(Vector& _normal, float _d) : normal(_normal), d(_d) {} - - Plane& operator=(const Plane& v) { - normal = v.normal; - d = v.d; - return *this; - } - }; -} -#endif // lm_plane_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_plane_intrin.h b/Dependencies/LMath/Src/LMath/lm_plane_intrin.h deleted file mode 100644 index 9ee6821..0000000 --- a/Dependencies/LMath/Src/LMath/lm_plane_intrin.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef lm_plane_intrin_h__ -#define lm_plane_intrin_h__ - -#include "lm_plane.h" - -namespace lm -{ - template - static inline auto dot(const Plane& plane, const Vector& value) { - return ((((plane.normal.x() * value.x()) + (plane.normal.y() * value.y())) + (plane.normal.z() * value.z())) + (plane.d * value.w())); - } - - /*static inline float PlaneDot(const Plane& plane, const Vector4D& value) { - return ((((plane.Normal.X * value.X) + (plane.Normal.Y * value.Y)) + (plane.Normal.Z * value.Z)) + (plane.D * value.W)); - } - static inline float PlaneDotCoordinate(const Plane& plane, const Vector3D& value) { - return ((((plane.Normal.X * value.X) + (plane.Normal.Y * value.Y)) + (plane.Normal.Z * value.Z)) + plane.D); - } - - static inline float PlaneDotNormal(const Plane& plane, const Vector3D& value) { - return (((plane.Normal.X * value.X) + (plane.Normal.Y * value.Y)) + (plane.Normal.Z * value.Z)); - } - static inline float PlaneDot(const Plane& plane, const Vector3D& point) { - return ((((plane.Normal.Y * point.Y) + (plane.Normal.X * point.X)) + (plane.Normal.Z * point.Z)) + plane.D); - }*/ - - - /*static inline float PlaneDotCoordinate(const Plane& plane, const Vector3D& value) { - return ((((plane.Normal.X * value.X) + (plane.Normal.Y * value.Y)) + (plane.Normal.Z * value.Z)) + plane.D); - } - static inline float PlaneDotNormal(const Plane& plane, const Vector3D& value) { - return (((plane.Normal.X * value.X) + (plane.Normal.Y * value.Y)) + (plane.Normal.Z * value.Z)); - }*/ - template - static inline auto dot(const Plane& plane, const Vector& point) { - return ((((plane.normal.y * point.y) + (plane.normal.x * point.x)) + (plane.normal.z * point.z)) + plane.D); - } -} -#endif // lm_plane_intrin_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_quaternion.h b/Dependencies/LMath/Src/LMath/lm_quaternion.h deleted file mode 100644 index bde922a..0000000 --- a/Dependencies/LMath/Src/LMath/lm_quaternion.h +++ /dev/null @@ -1,158 +0,0 @@ -#ifndef lm_quaternion_h__ -#define lm_quaternion_h__ - -#include "lm_vector.h" - -namespace lm { - template - struct Quaternion { - T data[4]; - - constexpr Quaternion() {} - - constexpr Quaternion(T x, T y, T z, T w) : data{ x,y,z,w } {} - - static Quaternion angleAxis(T angleRadians, const Vector& axis) { - auto theta = angleRadians / DefaultValues::two(); - auto s = lm::sin(theta); - auto c = lm::cos(theta); - - return Quaternion( - axis[0] * s, - axis[1] * s, - axis[2] * s, c); - } - - T& x() { return data[0]; } - const T& x() const { return data[0]; } - - T& y() { return data[1]; } - const T& y() const { return data[1]; } - - T& z() { return data[2]; } - const T& z() const { return data[2]; } - - T& w() { return data[3]; } - const T& w() const { return data[3]; } - - static Quaternion identity() { - auto zero = DefaultValues::zero(); - auto one = DefaultValues::one(); - return Quaternion(zero, zero, zero, one); - } - - T normSquare() const{ - return data[0] * data[0] + data[1] * data[1] + data[2] * data[2] + data[3] * data[3]; - } - - T norm() const { - return lm::sqrt(normSquare()); - } - - - void conjugate() const { - for (LmSize i = 0; i < 3; ++i) { - data[i] = -data[i]; - } - } - void inverse() { - auto n = static_cast(-1) / normSquare(); - data[0] = data[0] * n; - data[1] = data[1] * n; - data[2] = data[2] * n; - data[3] = data[3] * -n; - } - - - Quaternion operator -() const { - return Quaternion(-data[0], -data[1], -data[2], data[3]); - } - - bool operator==(const Quaternion& a) const{ - return - data[0] == a.data[0] && - data[1] == a.data[1] && - data[2] == a.data[2] && - data[3] == a.data[3]; - } - - bool operator!=(const Quaternion& a) const { - return - data[0] != a.data[0] || - data[1] != a.data[1] || - data[2] != a.data[2] || - data[3] != a.data[3]; - } - - - Quaternion operator *(const Quaternion& r) const { - Quaternion result; - result[3] = r[3] * data[3] - r[0] * data[0] - r[1] * data[1] - r[2] * data[2]; - result[0] = r[3] * data[0] + r[0] * data[3] - r[1] * data[2] + r[2] * data[1]; - result[1] = r[3] * data[1] + r[0] * data[2] + r[1] * data[3] - r[2] * data[0]; - result[2] = r[3] * data[2] - r[0] * data[1] + r[1] * data[0] + r[2] * data[3]; - return result; - } - - T& operator[](LmSize id) { - return data[id]; - } - const T& operator[](LmSize id) const { - return data[id]; - } - }; - - template - inline auto dot(const Quaternion& a, const Quaternion& b) { - return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3]; - } - - - template - inline Quaternion lerp(const Quaternion& a, const Quaternion& b, const T& x) { - return Quaternion( - a[0] + (b[0] - a[0]) * x, - a[1] + (b[1] - a[1]) * x, - a[2] + (b[2] - a[2]) * x, - a[3] + (b[3] - a[3]) * x); - } - - template - inline Quaternion slerp(const Quaternion& a, const Quaternion& b, const T& x) { - auto cosom = dot(a, b); - - if ((DefaultValues::one() + cosom) > std::numeric_limits::epsilon()) { - T sp; - T sq; - if ((DefaultValues::one() - cosom) > std::numeric_limits::epsilon()) { - double omega = lm::acos(cosom); - double sinom = DefaultValues::one() / lm::sin(omega); - - sp = static_cast(sin((DefaultValues::one() - x) * omega) * sinom); - sq = static_cast(sin(x * omega) * sinom); - } - else { - sp = DefaultValues::one() - x; - sq = x; - } - return Quaternion( - a[0] * sp + b[0] * sq, - a[1] * sp + b[1] * sq, - a[2] * sp + b[2] * sq, - a[3] * sp + b[3] * sq); - } - else { - auto halfpi = static_cast(lm::pi_d / DefaultValues::two()); //TODO: cleanup types mess - auto sp = static_cast(lm::sin((DefaultValues::one() - x) * halfpi)); - auto sq = static_cast(lm::sin(x * halfpi)); - return Quaternion( - a[0] * sp - a[1] * sq, - a[1] * sp + a[0] * sq, - a[2] * sp - a[3] * sq, - a[2]); - } - } - - typedef Quaternion Quaternion_f; -} -#endif // lm_quaternion_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_quaternion_intrin.h b/Dependencies/LMath/Src/LMath/lm_quaternion_intrin.h deleted file mode 100644 index 861d1e3..0000000 --- a/Dependencies/LMath/Src/LMath/lm_quaternion_intrin.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef lm_quaternion_intrin_h__ -#define lm_quaternion_intrin_h__ - -#include "lm_quaternion.h" - -namespace lm -{ - template - auto mul(const lm::Quaternion& q1, const lm::Quaternion& q2) { - return lm::Quaternion( - (q1.w() * q2.x() + q1.x() * q2.w() + q1.y() * q2.z() - q1.z() * q2.y()), - (q1.w() * q2.y() + q1.y() * q2.w() + q1.z() * q2.x() - q1.x() * q2.z()), - (q1.w() * q2.z() + q1.z() * q2.w() + q1.x() * q2.y() - q1.y() * q2.x()), - (q1.w() * q2.w() - q1.x() * q2.x() - q1.y() * q2.y() - q1.z() * q2.z()) - ); - } -} -#endif // lm_quaternion_intrin_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_stdio.h b/Dependencies/LMath/Src/LMath/lm_stdio.h deleted file mode 100644 index 30b5a6b..0000000 --- a/Dependencies/LMath/Src/LMath/lm_stdio.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef lm_stdio_h__ -#define lm_stdio_h__ - -#include -#include "lm_vector.h" - -namespace lm -{ - template - std::ostream& operator<<(std::ostream& os, const Vector& obj) { - os << "["; - for (size_t i = 0; i < N; ++i) { - os << obj.data[i]; - if(i != (N - 1)) - { - os << ", "; - } - } - os << "]"; - return os; - } -} - - -#endif // lm_stdio_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_traits.h b/Dependencies/LMath/Src/LMath/lm_traits.h deleted file mode 100644 index 038411d..0000000 --- a/Dependencies/LMath/Src/LMath/lm_traits.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef lm_traits_h__ -#define lm_traits_h__ - -#include - -namespace lm { - template - using MultiplyType = decltype(A() * B()); - - template - using DivideType = decltype(A() / B()); -} - -#endif // lm_traits_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_types.h b/Dependencies/LMath/Src/LMath/lm_types.h deleted file mode 100644 index 73c3763..0000000 --- a/Dependencies/LMath/Src/LMath/lm_types.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef lm_types_h__ -#define lm_types_h__ - -#if defined(_MSC_VER) -//#define LM_AMP_SUPPORTED -#endif - - -#if defined(LM_AMP_SUPPORTED) -#include -#include -#endif - -#include - -namespace lm { -#if defined(LM_AMP_SUPPORTED) -#define RESTRICT(...) restrict(__VA_ARGS__) -#define ENABLE_IF_AMP(...) __VA_ARGS__ -#else -#define RESTRICT(...) -#define ENABLE_IF_AMP(...) -#endif - - template - struct DefaultValues { - static T zero() RESTRICT(cpu, amp) { - return static_cast(0); - } - static T one() RESTRICT(cpu, amp) { - return static_cast(1); - } - static T two() RESTRICT(cpu, amp) { - return static_cast(2); - } - }; - - - template - T zero = static_cast(0); - template - T one = static_cast(1); - template - T two = static_cast(2); - - typedef size_t LmSize; -} - -#endif // lm_types_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_vector.h b/Dependencies/LMath/Src/LMath/lm_vector.h deleted file mode 100644 index 6a3cff0..0000000 --- a/Dependencies/LMath/Src/LMath/lm_vector.h +++ /dev/null @@ -1,711 +0,0 @@ -#ifndef lm_vector_h__ -#define lm_vector_h__ - -#include - -#include "lm_types.h" -#include "lm_constants.h" -#include "lm_macro.h" -#include "lm_traits.h" -#include - -namespace lm { - -#define LM_VECTOR_ARITHMETIC_OP_SCALAR(_Op, _Suffix) \ - template \ - auto operator _Op (const Vector& l, const U& divider) _Suffix { \ - Vector, N, Instructions> result; \ - for (LmSize i = 0; i < N; ++i) { \ - result.set(i, l.get(i) _Op divider); \ - } \ - return result; \ - } - -#define LM_VECTOR_ARITHMETIC_OP_VECTOR(_Op, _Suffix) \ - template \ - auto operator _Op (const Vector& l, Vector divider) _Suffix {\ - Vector, N, Instructions> result; \ - for (LmSize i = 0; i < N; ++i) {\ - result.set(i, l.get(i) _Op divider.get(i)); \ - } \ - return result; \ - } \ - -#define LM_VECTOR_ARITHMETIC_OP_SELF_SCALAR(_Op, _Suffix) \ - template\ - auto operator _Op## = (Vector& l, const U& divider) _Suffix { \ - for (LmSize i = 0; i < N; ++i) { \ - l.set(i, l.get(i) _Op divider); \ - } \ - return l; \ - } - -#define LM_VECTOR_ARITHMETIC_OP_SELF_VECTOR(_Op, _Suffix) \ - template \ - auto operator _Op##= (Vector& l, Vector divider) _Suffix{ \ - for (LmSize i = 0; i < N; ++i) { \ - l.set(i, l.get(i) _Op divider.get(i)); \ - } \ - return l; \ - } - -#define LM_VECTOR_ARITHMETIC_OP(_Op) \ - GEN_METHOD_PARAMS(LM_VECTOR_ARITHMETIC_OP_SCALAR, _Op) \ - GEN_METHOD_PARAMS(LM_VECTOR_ARITHMETIC_OP_VECTOR, _Op) \ - GEN_METHOD_PARAMS(LM_VECTOR_ARITHMETIC_OP_SELF_SCALAR, _Op) \ - GEN_METHOD_PARAMS(LM_VECTOR_ARITHMETIC_OP_SELF_VECTOR, _Op) - - -#define MATH_VECTOR_FUNC(_Name, _TemplateParams, _TemplateParamsNames, _ExecParams, _Params) \ - namespace impl { \ - template \ - struct _Name { \ - template \ - static auto exec(const T& v UNPACK _ExecParams) RESTRICT(cpu) { return std:: _Name (v UNPACK _Params); } \ - ENABLE_IF_AMP(template static auto exec(const T& v UNPACK _ExecParams) RESTRICT(amp) { return concurrency::precise_math:: _Name (v UNPACK _Params); }) \ - }; \ - template \ - struct _Name UNPACK _TemplateParamsNames> { \ - template \ - static auto exec(const Vector& v UNPACK _ExecParams) RESTRICT(cpu, amp) { \ - Vector::exec(*static_cast(nullptr) UNPACK _Params)), N> result; \ - for (LmSize i = 0; i < N; ++i) { result[i] = impl:: _Name ::exec(v[i] UNPACK _Params); } \ - return result; \ - } \ - }; \ - } \ - template \ - auto _Name(const T& v UNPACK _ExecParams) RESTRICT(cpu, amp) { \ - return impl:: _Name ::exec(v UNPACK _Params); \ - } - -#define MATH_VECTOR_FUNC_ONE_PARAM(_Name) MATH_VECTOR_FUNC(_Name, (, typename TParam), (, TParam), (, TParam x), (, x)) -#define MATH_VECTOR_FUNC_NO_PARAM(_Name) MATH_VECTOR_FUNC(_Name, (), (), (), ()) - - - enum class InstructionSet { - Generic, - SSE, - AVX - }; - - template - struct VectorData { - T data[N]; - -#define VECTOR_DATA_GET(_Suffix) \ - template \ - T& get(LmSize id) _Suffix{ \ - return data[id]; \ - } \ - template \ - const T& get(LmSize id) const _Suffix{ \ - return data[id]; \ - } - GEN_METHOD(VECTOR_DATA_GET) - -#define VECTOR_DATA_SET(_Suffix) \ - template \ - void set(LmSize id, T value) _Suffix { \ - data[id] = value; \ - } - GEN_METHOD(VECTOR_DATA_SET) - - constexpr VectorData() {} - -#ifdef LM_AMP_SUPPORTED - template - constexpr VectorData() restrict(amp) {} -#endif - -#define CTOR_VA(_Suffix) \ - template 4)>> \ - constexpr VectorData(const Args& ... rest) _Suffix : data{ rest... } {} - GEN_METHOD(CTOR_VA) - - //Vector2 constructors -#define CTOR_V2(_Suffix) \ - template> \ - constexpr VectorData(const TA& a, const TA& b) _Suffix : data{ a, b } {} - GEN_METHOD(CTOR_V2) - - //Vector3 constructors -#define CTOR_V3_0(_Suffix) \ - template::type>\ - constexpr VectorData(const TA& a, const TA& b, const TA& c) _Suffix : data{ static_cast(a), static_cast(b), static_cast(c) } {} - GEN_METHOD(CTOR_V3_0) - -#define CTOR_V3_1_BASE(_Suffix) \ - template> \ - constexpr VectorData(const VectorData& a, const TA& b) _Suffix : data{ a.data[0], a.data[1], b } {} - GEN_METHOD(CTOR_V3_1_BASE) - -#define CTOR_V3_2_BASE(_Suffix) \ - template> \ - constexpr VectorData(const TA& a, const VectorData& b) _Suffix : data{ a, b.data[0], b.data[1] } {} - GEN_METHOD(CTOR_V3_2_BASE) - - //Vector4 constructors -#define CTOR_V4_0_BASE(_Suffix) \ - template> \ - constexpr VectorData(const TA& a, const TA& b, const TA& c, const TA& d) _Suffix : data{ static_cast(a), static_cast(b), static_cast(c), static_cast(d) } {} - GEN_METHOD(CTOR_V4_0_BASE) - -#define CTOR_V4_1_BASE(_Suffix) \ - template> \ - constexpr VectorData(const TA& a, const TA& b, const VectorData& c) _Suffix : data{ a, b, c.data[0], c.data[1] } {} - GEN_METHOD(CTOR_V4_1_BASE) - -#define CTOR_V4_2_BASE(_Suffix) \ - template> \ - constexpr VectorData(const VectorData& a, const TA& b, const TA& c) _Suffix : data{ a.data[0], a.data[1], b, c } {} - GEN_METHOD(CTOR_V4_2_BASE) - -#define CTOR_V4_3_BASE(_Suffix) \ - template> \ - constexpr VectorData(const VectorData& a, const VectorData& b) _Suffix : data{ a.data[0], a.data[1], b.data[0], b.data[1] } {} - GEN_METHOD(CTOR_V4_3_BASE) - -#define CTOR_V4_4_BASE(_Suffix) \ - template> \ - constexpr VectorData(const TA& a, const VectorData& b) _Suffix : data{ a, b.data[0], b.data[1], b.data[2] } {} - GEN_METHOD(CTOR_V4_4_BASE) - -#define CTOR_V4_5_BASE(_Suffix) \ - template> \ - constexpr VectorData(const VectorData& a, const TA& b) _Suffix : data{ a.data[0], a.data[1], a.data[2], b } {} - GEN_METHOD(CTOR_V4_5_BASE) - -#define CTOR_S(_Suffix) \ - template \ - VectorData(Arg arg) _Suffix { \ - for (LmSize i = 0; i < N; ++i) { \ - data[i] = arg; \ - } \ - } - GEN_METHOD(CTOR_S) - }; - - template - struct Vector : public VectorData { - public: - static constexpr LmSize Size = N; - typedef T ElementType; - - constexpr Vector() {} - -#ifdef LM_AMP_SUPPORTED - template - constexpr Vector() restrict(amp) {} -#endif - - typedef VectorData Base; - - using Base::Base; - -#define CTOR_V3_1(_Suffix) \ - template> \ - constexpr Vector(const Vector& a, const TA& b) _Suffix : Base{ (const VectorData&)a, b } {} - GEN_METHOD(CTOR_V3_1) - -#define CTOR_V3_2(_Suffix) \ - template> \ - constexpr Vector(const TA& a, const Vector& b) _Suffix : Base{ a, (const VectorData&)b} {} - GEN_METHOD(CTOR_V3_2) - - //Vector4 constructors -#define CTOR_V4_1(_Suffix) \ - template> \ - constexpr Vector(const TA& a, const TA& b, const Vector& c) _Suffix : Base {a, b, (const VectorData&)c} {} - GEN_METHOD(CTOR_V4_1) - -#define CTOR_V4_2(_Suffix) \ - template> \ - constexpr Vector(const Vector& a, const TA& b, const TA& c) _Suffix : Base{(const VectorData&)a, b, c}{} - GEN_METHOD(CTOR_V4_2) - -#define CTOR_V4_3(_Suffix) \ - template> \ - constexpr Vector(const Vector& a, const Vector& b) _Suffix : Base { (const VectorData&)a, (const VectorData&)b} {} - GEN_METHOD(CTOR_V4_3) - -#define CTOR_V4_4(_Suffix) \ - template> \ - constexpr Vector(const TA& a, const Vector& b) _Suffix : Base {a, (const VectorData&)b} {} - GEN_METHOD(CTOR_V4_4) - -#define CTOR_V4_5(_Suffix) \ - template> \ - constexpr Vector(const Vector& a, const TA& b) _Suffix : Base{ (const VectorData&)a, b} {} - GEN_METHOD(CTOR_V4_5) - - - //UnitX -#define UNIT_X0(_Suffix) \ - template \ - static typename std::enable_if::type unitX() _Suffix { \ - return Vector(static_cast(1)); \ - } - GEN_METHOD(UNIT_X0) - -#define UNIT_X1(_Suffix) \ - template \ - static typename std::enable_if::type unitX() _Suffix { \ - return Vector(static_cast(1), static_cast(0)); \ - } - GEN_METHOD(UNIT_X1) - -#define UNIT_X2(_Suffix) \ - template \ - static typename std::enable_if::type unitX() _Suffix { \ - return Vector(static_cast(1), static_cast(0), static_cast(0)); \ - } - GEN_METHOD(UNIT_X2) - -#define UNIT_X3(_Suffix) \ - template \ - static typename std::enable_if::type unitX() _Suffix { \ - return Vector(static_cast(1), static_cast(0), static_cast(0), static_cast(0)); \ - } - GEN_METHOD(UNIT_X3) - - - //UnitY -#define UNIT_Y0(_Suffix) \ - template \ - static typename std::enable_if::type unitY() _Suffix { \ - return Vector(static_cast(0), static_cast(1)); \ - } - GEN_METHOD(UNIT_Y0) - -#define UNIT_Y1(_Suffix) \ - template \ - static typename std::enable_if::type unitY() _Suffix { \ - return Vector(static_cast(0), static_cast(1), static_cast(0)); \ - } - GEN_METHOD(UNIT_Y1) - -#define UNIT_Y2(_Suffix) \ - template \ - static typename std::enable_if::type unitY() _Suffix { \ - return Vector(static_cast(0), static_cast(1), static_cast(0), static_cast(0)); \ - } - GEN_METHOD(UNIT_Y2) - - //UnitZ -#define UNIT_Z0(_Suffix) \ - template \ - static typename std::enable_if::type unitZ() _Suffix { \ - return Vector(static_cast(0), static_cast(0), static_cast(1)); \ - } - GEN_METHOD(UNIT_Z0) - -#define UNIT_Z1(_Suffix) \ - template \ - static typename std::enable_if::type unitZ() _Suffix { \ - return Vector(static_cast(0), static_cast(0), static_cast(1), static_cast(0)); \ - } - GEN_METHOD(UNIT_Z1) - - //UnitW -#define UNIT_W0(_Suffix) \ - template \ - static typename std::enable_if::type unitW() _Suffix { \ - return Vector(static_cast(0), static_cast(0), static_cast(0), static_cast(1)); \ - } - GEN_METHOD(UNIT_W0) - - //EMPTY_SUFFIX - -#define VECTOR_ITEM_ACCESSOR_BASE(_Name, _Index, _Modifier, _Restrict) \ - template _Index)>> \ - _Modifier auto& _Name () _Modifier _Restrict { return this->get(_Index); } - -#define VECTOR_ITEM_ACCESSOR(_Name, _Index) \ - VECTOR_ITEM_ACCESSOR_BASE(_Name, _Index, EMPTY_SUFFIX, EMPTY_SUFFIX) \ - VECTOR_ITEM_ACCESSOR_BASE(_Name, _Index, const, EMPTY_SUFFIX) \ - ENABLE_IF_AMP(VECTOR_ITEM_ACCESSOR_BASE(_Name, _Index, EMPTY_SUFFIX, restrict(amp)) ) \ - ENABLE_IF_AMP(VECTOR_ITEM_ACCESSOR_BASE(_Name, _Index, const, restrict(amp)) ) - - //accessors - VECTOR_ITEM_ACCESSOR(x, 0); - VECTOR_ITEM_ACCESSOR(y, 1); - VECTOR_ITEM_ACCESSOR(z, 2); - VECTOR_ITEM_ACCESSOR(w, 3); - - -#define SLICE(_Prefix, _Suffix) \ - template> \ - _Prefix Vector& slice() _Suffix { \ - return *((Vector*)&this->data[Offset]); \ - } - GEN_METHOD2(SLICE) - -#define LINEAR_SLICE_ACCESSOR_BASE(_Name, _Offset, _Length, _Prefix, _Suffix) \ - template> \ - _Prefix auto& _Name () _Suffix { return slice(); } - - -#define LM_VECTOR_LINEAR_SLICE_ACCESSOR_XY(_Prefix, _Suffix) LINEAR_SLICE_ACCESSOR_BASE(xy, 0, 2, _Prefix, _Suffix) -#define LM_VECTOR_LINEAR_SLICE_ACCESSOR_XYZ(_Prefix, _Suffix) LINEAR_SLICE_ACCESSOR_BASE(xyz, 0, 3, _Prefix, _Suffix) -#define LM_VECTOR_LINEAR_SLICE_ACCESSOR_XYZW(_Prefix, _Suffix) LINEAR_SLICE_ACCESSOR_BASE(xyzw, 0, 4, _Prefix, _Suffix) -#define LM_VECTOR_LINEAR_SLICE_ACCESSOR_YZ(_Prefix, _Suffix) LINEAR_SLICE_ACCESSOR_BASE(yz, 1, 2, _Prefix, _Suffix) -#define LM_VECTOR_LINEAR_SLICE_ACCESSOR_YZW(_Prefix, _Suffix) LINEAR_SLICE_ACCESSOR_BASE(yzw, 1, 3, _Prefix, _Suffix) -#define LM_VECTOR_LINEAR_SLICE_ACCESSOR_ZW(_Prefix, _Suffix) LINEAR_SLICE_ACCESSOR_BASE(zw, 2, 2, _Prefix, _Suffix) - - GEN_METHOD2(LM_VECTOR_LINEAR_SLICE_ACCESSOR_XY) - GEN_METHOD2(LM_VECTOR_LINEAR_SLICE_ACCESSOR_XYZ) - GEN_METHOD2(LM_VECTOR_LINEAR_SLICE_ACCESSOR_XYZW) - GEN_METHOD2(LM_VECTOR_LINEAR_SLICE_ACCESSOR_YZ) - GEN_METHOD2(LM_VECTOR_LINEAR_SLICE_ACCESSOR_YZW) - GEN_METHOD2(LM_VECTOR_LINEAR_SLICE_ACCESSOR_ZW) - - -#define LEN_SQ(_Prefix, _Suffix) \ - template> \ - _Prefix auto lengthSquared() _Suffix { \ - TR result = DefaultValues::zero(); \ - for (LmSize i = 0; i < N; ++i) { \ - result += this->get(i) * this->get(i); \ - } \ - return result;\ - } - - GEN_METHOD2(LEN_SQ) - - auto length() const RESTRICT(cpu); -#if defined(LM_AMP_SUPPORTED) - auto length() const RESTRICT(amp); -#endif - -#define OP_INDEX(_Prefix, _Suffix) \ - template \ - _Prefix T& operator [] (LmSize id) _Suffix { \ - return this->get(id); \ - } - GEN_METHOD2(OP_INDEX) - -#define NORMALIZED(_Suffix) \ - auto normalized() _Suffix { \ - return (*this) / length(); \ - } - GEN_METHOD_CONST(NORMALIZED) - - - /*LM_VECTOR_ARITHMETIC_OP(+); - LM_VECTOR_ARITHMETIC_OP(-); - LM_VECTOR_ARITHMETIC_OP(*); - LM_VECTOR_ARITHMETIC_OP(/ );*/ - - template - bool equals(const Vector& other, T tolerance) const; - ENABLE_IF_AMP(template bool equals(const Vector& other, T tolerance) const restrict(amp); ) - -#define OP_NEG(_Suffix) \ - template \ - auto operator-() const _Suffix { \ - Vectorx())>::type, Size> result; \ - for (LmSize i = 0; i < Size; ++i) { \ - result[i] = -this->get(i); \ - } \ - return result; \ - } - - GEN_METHOD(OP_NEG) - -#define OP_EQ(_Suffix) \ - template \ - bool operator==(const Vector& right) const _Suffix { \ - for (LmSize i = 0; i < Size; ++i) { \ - if (this->get(i) != right[i]) { \ - return false; \ - } \ - } \ - return true; \ - } - GEN_METHOD(OP_EQ) - -#define OP_NEQ(_Suffix) \ - template \ - bool operator!=(const Vector& right) const _Suffix { \ - for (LmSize i = 0; i < Size; ++i) { \ - if (this->get(i) != right[i]) { \ - return true; \ - } \ - } \ - return false; \ - } - GEN_METHOD(OP_NEQ) - -#define OP_CAST_RAW(_Prefix, _Suffix) \ - template \ - explicit operator _Prefix T*() _Suffix { \ - return Size == 0 ? nullptr : &this->get(0); \ - } - GEN_METHOD2(OP_CAST_RAW) - - }; - - - - template - auto cross(const Vector& a, const Vector& b) RESTRICT(cpu, amp) { - return Vector, 3>( - (a[1] * b[2]) - (a[2] * b[1]), - (a[2] * b[0]) - (a[0] * b[2]), - (a[0] * b[1]) - (a[1] * b[0])); - } - - template - auto dot(const Vector& left, const Vector& right)RESTRICT(cpu, amp) { - auto result = DefaultValues>::zero(); - for (LmSize i = 0; i < N; ++i) { - result += left[i] * right[i]; - } - return result; - } - - - template - auto normalize(const Vector& v) RESTRICT(cpu, amp) { - return v.normalized(); - } - - - - template - auto lerp(const Vector& a, const Vector& b, TC c)RESTRICT(cpu, amp) { - return a * (DefaultValues::one() - c) + b * c; - } - - template - auto all(const Vector& v) RESTRICT(cpu, amp) { - for (LmSize i = 0; i < N; ++i) { - if (v[i] == DefaultValues::zero()) { - return false; - } - } - return true; - } - - template - auto any(const Vector& v) RESTRICT(cpu, amp) { - for (LmSize i = 0; i < N; ++i) { - if (v[i] != static_cast(0)) { - return true; - } - } - return false; - } - - - namespace impl { - template - struct abs {}; - template<> - struct abs { - static auto exec(const float& v) RESTRICT(cpu) { return std::fabs(v); } - ENABLE_IF_AMP(static auto exec(const float& v) RESTRICT(amp) { return concurrency::precise_math::fabs(v); }) - }; - template<> - struct abs { - static auto exec(const double& v) RESTRICT(cpu) { return std::fabs(v); } - ENABLE_IF_AMP(static auto exec(const double& v) RESTRICT(amp) { return concurrency::precise_math::fabs(v); }) - }; - - template - struct abs> { - static auto exec(const Vector& v) RESTRICT(cpu, amp) { - Vector result; - for (LmSize i = 0; i < N; ++i) { result[i] = abs::exec(v[i]); } - return result; - } - }; - } - - LM_VECTOR_ARITHMETIC_OP(+); - LM_VECTOR_ARITHMETIC_OP(-); - LM_VECTOR_ARITHMETIC_OP(*); - LM_VECTOR_ARITHMETIC_OP(/ ); - - - template - auto abs(const T& v) RESTRICT(cpu, amp) { - return impl::abs::exec(v); - } - - - MATH_VECTOR_FUNC_ONE_PARAM(pow); - MATH_VECTOR_FUNC_NO_PARAM(sin); - MATH_VECTOR_FUNC_NO_PARAM(cos); - MATH_VECTOR_FUNC_NO_PARAM(acos); - MATH_VECTOR_FUNC_NO_PARAM(asin); - MATH_VECTOR_FUNC_NO_PARAM(cosh); - MATH_VECTOR_FUNC_NO_PARAM(sinh); - MATH_VECTOR_FUNC_NO_PARAM(tan); - MATH_VECTOR_FUNC_NO_PARAM(atan); - MATH_VECTOR_FUNC_NO_PARAM(floor); - MATH_VECTOR_FUNC_NO_PARAM(ceil); - MATH_VECTOR_FUNC_NO_PARAM(exp); - MATH_VECTOR_FUNC_NO_PARAM(log); - - MATH_VECTOR_FUNC_NO_PARAM(sqrt); - -#define LM_VEC_METHOD_LENGTH(_Suffix) \ - template \ - auto Vector::length() const _Suffix { \ - return lm::sqrt(lengthSquared()); \ - } - - GEN_METHOD(LM_VEC_METHOD_LENGTH) - - -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - namespace impl { - template - struct min { - static auto exec(const T& a, const T& b) RESTRICT(cpu, amp) { - return a < b ? a : b; - } - }; - - template - struct min> { - static auto exec(const Vector& a, const Vector& b) RESTRICT(cpu, amp) { - Vector result; - for (LmSize i = 0; i < N; ++i) { result[i] = impl::min::exec(a[i], b[i]); } - return result; - } - }; - } - - template - auto min(const T& a, const T& b) RESTRICT(cpu, amp) { - return impl::min::exec(a, b); - } - - template 0)>> - auto min(const Vector& v) RESTRICT(cpu, amp) { - LmSize id = 0; - for (LmSize i = 1; i < N; ++i) { - if (v[i] < v[id]) { - id = i; - } - } - return v[id]; - } - - template 0)>> - auto max(const Vector& v) RESTRICT(cpu, amp) { - LmSize id = 0; - for (LmSize i = 1; i < N; ++i) { - if (v[i] > v[id]) { - id = i; - } - } - return v[id]; - } - - namespace impl { - template - struct max { - static auto exec(const T& a, const T& b) RESTRICT(cpu, amp) { - return a > b ? a : b; - } - }; - - template - struct max> { - static auto exec(const Vector& a, const Vector& b) RESTRICT(cpu, amp) { - Vector result; - for (LmSize i = 0; i < N; ++i) { result[i] = impl::max::exec(a[i], b[i]); } - return result; - } - }; - } - - template - auto max(const T& a, const T& b) RESTRICT(cpu, amp) { - return impl::max::exec(a, b); - } - - template - auto clamp(const T& a, const TRange& minValue, const TRange& maxValue) RESTRICT(cpu, amp) { - return lm::min(lm::max(a, minValue), maxValue); - } - - template - auto saturate(const T& a) RESTRICT(cpu, amp) { - T result; - for (LmSize i = 0; i < T::Size; ++i) { - result[i] = lm::min(lm::max(a[i], static_cast(0)), static_cast(1)); - - } - return result; - } - - - - namespace impl { - template - struct degrees { - static auto exec(const T& a) RESTRICT(cpu, amp) { - return (static_cast(180) / static_cast(pi_d)) * a; - } - }; - - template - struct degrees> { - static auto exec(const Vector& a) RESTRICT(cpu, amp) { - Vector result; - for (LmSize i = 0; i < N; ++i) { result[i] = impl::degrees::exec(a[i]); } - return result; - } - }; - } - - template - auto degrees(const T& a) RESTRICT(cpu, amp) { - return impl::degrees::exec(a); - } - -#define LM_VECTOR_EQUALS(_Suffix) \ - template \ -template \ - bool Vector::equals(const Vector& other, T tolerance) const _Suffix { \ - for (LmSize i = 0; i < N; ++i) { \ - if (lm::abs(this->get(i) - other.get(i)) >= tolerance) { \ - return false; \ - } \ - } \ - return true; \ - } - - GEN_METHOD(LM_VECTOR_EQUALS) - - template - bool equals(const Vector& a, const Vector& b, T tolerance) RESTRICT(cpu, amp) { - return a.equals(b); - } - - template - auto distance(const Vector& v1, const Vector& v2) RESTRICT(cpu, amp) { - return (v2 - v1).length(); - } - - - - typedef Vector float2; - typedef Vector float3; - typedef Vector float4; - typedef Vector double2; - typedef Vector double3; - typedef Vector double4; -} -#endif // lm_vector_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_vector_avx.h b/Dependencies/LMath/Src/LMath/lm_vector_avx.h deleted file mode 100644 index 131c149..0000000 --- a/Dependencies/LMath/Src/LMath/lm_vector_avx.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef lm_vector_avx_h__ -#define lm_vector_avx_h__ - -#include "lm_vector.h" -#include - - -namespace lm { - - template<> - struct VectorData { - VectorData() { - avxValue = _mm256_setzero_pd(); - } - - VectorData(__m256d value) : avxValue(value) { - - } - VectorData(double value) { - avxValue = _mm256_set_pd(value, value, value, value); - } - - VectorData(double x, double y, double z, double w) { - avxValue = _mm256_set_pd(w, z, y, x); - } - - - template - double get() const { - static_assert(Index < 4); - alignas(256) double buffer[4]; - _mm256_store_pd(&buffer[0], avxValue); - return buffer[Index]; - } - double get(LmSize id) const { - if (id == 0) { - return get<0>(); - } - else if (id == 1) { - return get<1>(); - } - else if (id == 2) { - return get<2>(); - } - else { - return get<3>(); - } - } - - __m256d avxValue; - }; - - using double4_avx = Vector; - - double dot(double4_avx l, double4_avx r) { - //AVX code - - auto m = _mm256_mul_pd(l.avxValue, r.avxValue); - auto a0 = _mm256_hadd_pd(m, m); - auto a1 = _mm256_permute4x64_pd(a0, _MM_SHUFFLE(1, 3, 1, 3)); - return _mm_cvtsd_f64(_mm256_castpd256_pd128(_mm256_hadd_pd(a1,a1))); - } - - - double4_avx operator * (double4_avx l, double4_avx r) { return { _mm256_mul_pd(l.avxValue, r.avxValue) }; } - double4_avx operator / (double4_avx l, double4_avx r) { return { _mm256_div_pd(l.avxValue, r.avxValue) }; } - double4_avx operator + (double4_avx l, double4_avx r) { return { _mm256_add_pd(l.avxValue, r.avxValue) }; } - double4_avx operator - (double4_avx l, double4_avx r) { return { _mm256_sub_pd(l.avxValue, r.avxValue) }; } - - double4_avx& operator *= (double4_avx& l, double4_avx r) { l = l * r; return l; } - double4_avx& operator /= (double4_avx& l, double4_avx r) { l = l / r; return l; } - double4_avx& operator += (double4_avx& l, double4_avx r) { l = l + r; return l; } - double4_avx& operator -= (double4_avx& l, double4_avx r) { l = l - r; return l; } - - double4_avx operator == (double4_avx l, double4_avx r) { return { _mm256_cmp_pd(l.avxValue, r.avxValue, _CMP_EQ_OQ) }; } - double4_avx operator != (double4_avx l, double4_avx r) { return { _mm256_cmp_pd(l.avxValue, r.avxValue, _CMP_NEQ_OQ) }; } - double4_avx operator < (double4_avx l, double4_avx r) { return { _mm256_cmp_pd(l.avxValue, r.avxValue, _CMP_LT_OQ) }; } - double4_avx operator <= (double4_avx l, double4_avx r) { return { _mm256_cmp_pd(l.avxValue, r.avxValue, _CMP_LE_OQ) }; } - double4_avx operator > (double4_avx l, double4_avx r) { return { _mm256_cmp_pd(l.avxValue, r.avxValue, _CMP_GT_OQ) }; } - double4_avx operator >= (double4_avx l, double4_avx r) { return { _mm256_cmp_pd(l.avxValue, r.avxValue, _CMP_GE_OQ) }; } - - double4_avx min(double4_avx l, double4_avx r) { return { _mm256_min_pd(l.avxValue, r.avxValue) }; } - double4_avx max(double4_avx l, double4_avx r) { return { _mm256_max_pd(l.avxValue, r.avxValue) }; } - -} -#endif // lm_vector_avx_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_vector_sse.h b/Dependencies/LMath/Src/LMath/lm_vector_sse.h deleted file mode 100644 index 6655b27..0000000 --- a/Dependencies/LMath/Src/LMath/lm_vector_sse.h +++ /dev/null @@ -1,152 +0,0 @@ -#ifndef lm_vector_sse_h__ -#define lm_vector_sse_h__ - -#include "lm_vector.h" -#include - - -namespace lm { - - template<> - struct VectorData { - - VectorData() { - sseValue = _mm_setzero_ps(); - } - - VectorData(float value) { - sseValue = _mm_set_ps1(value); - } - - VectorData(float x, float y, float z, float w) { - sseValue = _mm_set_ps(w, z, y, x); - } - - VectorData(__m128 value) : sseValue(value){ - } - - - template - float get() const { - static_assert(Index < 4); - if constexpr(Index == 0) { - return _mm_cvtss_f32(sseValue); - } - else if constexpr(Index == 1) { - return _mm_cvtss_f32(_mm_shuffle_ps(sseValue, sseValue, _MM_SHUFFLE(1, 1, 1, 1))); - } - else if constexpr(Index == 2) { - return _mm_cvtss_f32(_mm_shuffle_ps(sseValue, sseValue, _MM_SHUFFLE(2, 2, 2, 2))); - } - else { - return _mm_cvtss_f32(_mm_shuffle_ps(sseValue, sseValue, _MM_SHUFFLE(3, 3, 3, 3))); - } - } - - float get(LmSize id) const { - if (id == 0) { - return get<0>(); - } - else if (id == 1) { - return get<1>(); - } - else if (id == 2) { - return get<2>(); - } - else { - return get<3>(); - } - } - - template - void set(float value) { - static_assert(Index < 4); - if constexpr(Index == 0) { - sseValue = _mm_move_ss(sseValue, _mm_set_ss(value)); - } - if constexpr(Index == 1) { - auto temp = _mm_move_ss(sseValue, _mm_set_ss(value)); - temp = _mm_shuffle_ps(temp, temp, _MM_SHUFFLE(3, 2, 0, 0)); - sseValue = _mm_move_ss(temp, sseValue); - } - if constexpr(Index == 2) { - auto temp = _mm_move_ss(sseValue, _mm_set_ss(value)); - temp = _mm_shuffle_ps(temp, temp, _MM_SHUFFLE(3, 0, 1, 0)); - sseValue = _mm_move_ss(temp, sseValue); - } - if constexpr(Index == 3) { - auto temp = _mm_move_ss(sseValue, _mm_set_ss(value)); - temp = _mm_shuffle_ps(temp, temp, _MM_SHUFFLE(0, 2, 1, 0)); - sseValue = _mm_move_ss(temp, sseValue); - } - } - - void set(LmSize id, float value) { - if (id == 0) { - set<0>(value); - } - else if (id == 1) { - set<1>(value); - } - else if (id == 2) { - set<2>(value); - } - else { - set<3>(value); - } - } - - auto mask() const { - return _mm_movemask_ps(sseValue) & 0x7; - } - - __m128 sseValue; - }; - - using float4_sse = Vector; - - float4_sse operator * (float4_sse l, float4_sse r) { return { _mm_mul_ps(l.sseValue, r.sseValue) }; } - float4_sse operator / (float4_sse l, float4_sse r) { return { _mm_div_ps(l.sseValue, r.sseValue) }; } - float4_sse operator + (float4_sse l, float4_sse r) { return { _mm_add_ps(l.sseValue, r.sseValue) }; } - float4_sse operator - (float4_sse l, float4_sse r) { return { _mm_sub_ps(l.sseValue, r.sseValue) }; } - - float4_sse& operator *= (float4_sse& l, float4_sse r) { l = l * r; return l; } - float4_sse& operator /= (float4_sse& l, float4_sse r) { l = l / r; return l; } - float4_sse& operator += (float4_sse& l, float4_sse r) { l = l + r; return l; } - float4_sse& operator -= (float4_sse& l, float4_sse r) { l = l - r; return l; } - - float4_sse operator == (float4_sse l, float4_sse r) { return { _mm_cmpeq_ps(l.sseValue, r.sseValue) }; } - float4_sse operator != (float4_sse l, float4_sse r) { return { _mm_cmpneq_ps(l.sseValue, r.sseValue) }; } - float4_sse operator < (float4_sse l, float4_sse r) { return { _mm_cmplt_ps(l.sseValue, r.sseValue) }; } - float4_sse operator <= (float4_sse l, float4_sse r) { return { _mm_cmple_ps(l.sseValue, r.sseValue) }; } - float4_sse operator > (float4_sse l, float4_sse r) { return { _mm_cmpgt_ps(l.sseValue, r.sseValue) }; } - float4_sse operator >= (float4_sse l, float4_sse r) { return { _mm_cmpge_ps(l.sseValue, r.sseValue) }; } - - float4_sse min(float4_sse l, float4_sse r) { return {_mm_min_ps(l.sseValue, r.sseValue)}; } - float4_sse max(float4_sse l, float4_sse r) { return {_mm_max_ps(l.sseValue, r.sseValue)}; } - - float min(float4_sse l) { - auto ml = _mm_min_ps(l.sseValue, _mm_shuffle_ps(l.sseValue, l.sseValue, _MM_SHUFFLE(3, 2, 3, 2))); - return _mm_cvtss_f32(_mm_min_ps(ml, _mm_shuffle_ps(ml, ml, _MM_SHUFFLE(1, 1, 1, 1)))); - } - - float max(float4_sse l) { - auto ml = _mm_max_ps(l.sseValue, _mm_shuffle_ps(l.sseValue, l.sseValue, _MM_SHUFFLE(3, 2, 3, 2))); - return _mm_cvtss_f32(_mm_max_ps(ml, _mm_shuffle_ps(ml, ml, _MM_SHUFFLE(1, 1, 1, 1)))); - } - - float sum(float4_sse v) { - //SSE3 code - auto tmp = _mm_hadd_ps(v.sseValue, v.sseValue); - return _mm_cvtss_f32(_mm_hadd_ps(tmp, tmp)); - } - - float dot(float4_sse l, float4_sse r) { - //SSE4 code - return _mm_cvtss_f32(_mm_dp_ps(l.sseValue, r.sseValue, 0xff)); - } - - //_mm_dp_ps -} - -#endif // lm_vector_sse_h__ diff --git a/Dependencies/LMath/Src/LMath/lm_vector_traits.h b/Dependencies/LMath/Src/LMath/lm_vector_traits.h deleted file mode 100644 index 53482ca..0000000 --- a/Dependencies/LMath/Src/LMath/lm_vector_traits.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef lm_vector_traits_h__ -#define lm_vector_traits_h__ - -#include "lm_traits.h" -#include "lm_types.h" - -namespace lm { - namespace Detail { - template - struct IsVector : public std::false_type {}; - - template - struct IsVector> : public std::true_type {}; - - template - struct VectorSize : std::integral_constant {}; - - template - struct VectorSize : std::integral_constant {}; - } - - template - struct IsVector : public Detail::IsVector> {}; - - template - struct VectorSize : Detail::VectorSize::value> {}; - -} - -#endif // lm_vector_traits_h__ diff --git a/Dependencies/LMath/Src/LMath/lmath.h b/Dependencies/LMath/Src/LMath/lmath.h deleted file mode 100644 index 7696b22..0000000 --- a/Dependencies/LMath/Src/LMath/lmath.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "lm_vector.h" -#include "lm_matrix.h" -#include "lm_plane.h" -#include "lm_common_intrin.h" -#include "lm_plane_intrin.h" -#include "lm_quaternion.h" -#include "lm_quaternion_intrin.h" -#include "lm_stdio.h" -#include "lm_half.h" diff --git a/Dependencies/LMath/lmath.vcxitems b/Dependencies/LMath/lmath.vcxitems deleted file mode 100644 index 8bb918a..0000000 --- a/Dependencies/LMath/lmath.vcxitems +++ /dev/null @@ -1,22 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - {ac7a7e55-b112-4c1c-a6d0-f35ad8bf5164} - - - - %(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory) - - - - - - - - - - - - \ No newline at end of file diff --git a/Dependencies/LMath/lmath_sandbox/lmath_sandbox.cpp b/Dependencies/LMath/lmath_sandbox/lmath_sandbox.cpp deleted file mode 100644 index 69e3f0a..0000000 --- a/Dependencies/LMath/lmath_sandbox/lmath_sandbox.cpp +++ /dev/null @@ -1,544 +0,0 @@ -#include "../lmath/lmath.h" -#include "../lmath/lm_vector_sse.h" -#include "../lmath/lm_vector_avx.h" -#include -#include -#include - -using namespace concurrency; -using namespace lm; - -void TestCPU() restrict(cpu) { - - double4_avx d0(1.0, 0, 1, 4); - auto dm0 = d0.get<0>(); - auto dm1 = d0.get<1>(); - auto dm2 = d0.get<2>(); - auto dm3 = d0.get<3>(); - - double dt = lm::dot(d0, d0); - - auto pp = lm::min(double4_avx(1, 2, 3, 4), double4_avx(4, 3, 2, 1)); - auto ppp0 = pp.get<0>(); - auto ppp1 = pp.get<1>(); - auto ppp2 = pp.get<2>(); - auto ppp3 = pp.get<3>(); - - auto pplen = pp.length(); - - auto f_sse3 = float4_sse(3) * float4_sse(4); - - auto l = float4_sse(0, 1, 2, 3); - - auto ls = lm::sum(l); - - auto lx = l.get<0>(); - - Vector p00(0U); - Vector p0; - Vector p1((uint16_t)0U, (uint16_t)1U, (uint16_t)2U, (uint16_t)3U, (uint16_t)4U); - - Vector p3((uint16_t)0U, (uint16_t)1U); - Vector p4((uint16_t)0U, (uint16_t)1U, (uint16_t)2U); - Vector p5((uint16_t)0U, (uint16_t)1U, (uint16_t)2U, (uint16_t)3U); - - Vector::unitX(); - Vector::unitX(); - Vector::unitX(); - - auto p3x = p3.y(); - - - p0.lengthSquared(); -// p0.length(); - - auto pp0 = p0 / 2.0f; - auto pp1 = p0 * 2.0f; - auto pp2 = p0 + 2.0f; - auto pp3 = p0 - 2.0f; - - p0 /= 2; - p0 *= 2; - p0 += 2; - p0 -= 2; - //p0.normalized(); - - auto& v = p0.slice<1, 2>(); - - Vector v0(1.0f, 2.0f, 3.0f); - v0 = -v0; - - v0 == v0; - v0 != v0; - - auto v1 = cross(v0, v0 + 1.0f); - auto v2 = dot(v0, v0 + 1.0f); - auto v3 = normalize(v0); -} - -void TestAMP() restrict(amp) { - Vector p00(0U); - - Vector p0; - Vector p1(0U, 1U, 2U, 3U, 4U); - - Vector p3(0U, 1U); - Vector p4(0U, 1U, 2U); - Vector p5(0U, 1U, 2U, 3U); - - Vector::unitX(); - Vector::unitX(); - Vector::unitX(); - - auto& v = p0.slice<1, 2>(); - - - - auto pp0 = p0 / 2.0f; - auto pp1 = p0 * 2.0f; - auto pp2 = p0 + 2.0f; - auto pp3 = p0 - 2.0f; - - p0 /= 2; - p0 *= 2; - p0 += 2; - p0 -= 2; - - Vector v0(1.0f, 2.0f, 3.0f); - v0 = -v0; - - v0 == v0; - v0 != v0; - - auto v1 = cross(v0, v0 + 1.0f); - auto v2 = dot(v0, v0 + 1.0f); - auto v3 = normalize(v0); -} - -int main() { - TestCPU(); - - Vector p0; - - std::vector amp_vector; - std::vector amp_result_vector(amp_vector.size()); - - array_view arr(amp_vector); - array_view arr_result(amp_result_vector); - arr_result.discard_data(); - - - parallel_for_each(arr.extent, [=](index<1> idx) restrict(amp) { - TestAMP(); - }); - - - /*float4x4 ta; - float4x4 tb; - ta = tb; - - float4 pp(1.0f, 2.0f, 3.0f, 4.0f); - float4 pn = -pp; - - auto& xyzw = pp.xyzw(); - auto& xyz = pp.xyz(); - auto& xy = pp.xy(); - - auto& yzw = pp.yzw(); - auto& yz = pp.yz(); - - auto& zw = pp.zw(); - - auto& xx = pn.x(); - auto& yy = pn.y(); - auto& zz = pn.z(); - - float2 fff; - - auto& xf = fff.x(); - auto& yf = fff.y(); - //auto& zf = fff.z(); - - float* pf = (float*)pn; - - pp.slice<1, 2>() = float2(7.0f, 8.0f); - - Matrix vvvv( - Vector(1.0f, 0.0f, 0.0f, 0.0f), - Vector(0.0f, 1.0f, 0.0f, 0.0f), - Vector(0.0f, 0.0f, 1.0f, 0.0f), - Vector(0.0f, 0.0f, 0.0f, 1.0f)); - - auto deg1 = lm::degrees(lm::pi_d); - auto deg2 = lm::degrees(lm::pi_d / 2.0); - auto deg3 = lm::degrees(double2(pi_d / 2.0, pi_d / 3.0)); - - float expf = lm::exp(1.0f); - auto expv = lm::exp(float2(2.0f, 3.0f)); - - float logf = lm::log(1.0f); - auto logv = lm::log(float2(2.0f, 3.0f)); - - float minf1 = lm::min(1.0f, 2.0f); - float minf2 = lm::min(2.0f, 1.0f); - float maxf1 = lm::max(1.0f, 2.0f); - float maxf2 = lm::max(2.0f, 1.0f); - - auto clampt = lm::clamp(float2(1.0f, 2.0f), float2(1.5f), float2(3.0f)); - - auto minv1 = lm::min(float2(1.0f, 2.0f), float2(5.0f, 1.0f)); - auto minv2 = lm::min(float2(2.0f, 1.0f), float2(1.0f, 0.0f)); - auto maxv1 = lm::max(float2(1.0f, 2.0f), float2(0.0f, 0.0f)); - auto maxv2 = lm::max(float2(2.0f, 1.0f), float2(3.0f, 7.0f)); - - auto ux = float3::unitX(); - auto pow_11 = lm::pow(float4(1.0f, 2.0f, 3.0f, 4.0f), 2.0f); - - Vector, 2> vv; - vv[0] = float2(1.0f, 2.0f); - vv[1] = float2(3.0f, 4.0f); - auto pow_22 = lm::pow(vv, 2.0f); - - - test_float2(); - - - - float3 mul_self_0(1.0f, 2.0f, 3.0f); - mul_self_0 *= 2; - mul_self_0 *= float3(2.0f, 3.0f, 4.0f); - mul_self_0 /= 2; - mul_self_0 /= float3(4.0f, 4.0f, 4.0f); - mul_self_0 += 1; - mul_self_0 += float3(4.0f, 4.0f, 4.0f); - - mul_self_0 -= 2; - mul_self_0 -= float3(2.0f, 2.0f, 2.0f); - - //AMP test - parallel_for_each(arr.extent, [=](index<1> idx) restrict(amp) { - - -// Half h1; - - float3x3 m1; - - auto col1 = m1.getColumn(0); - auto m2 = float3x3::identity(); - auto m3 = float4x4::identity(); - - auto b2 = float3x3::identity(); - auto m4 = lm::mul(m1, m2); - - float2x2 m22; - - - auto det1 = determinant(m22); - auto det2 = determinantAffine(m1); - auto det3 = determinantAffine(m3); - - auto mi = inverse(m3, true); - - mi[0] = float4{ 0.0f,1.0f,2.0f,3.0f }; - mi[1] = float4{ 4.0f,5.0f,6.0f,7.0f }; - mi[2] = float4{ 8.0f,9.0f,10.0f,11.0f }; - mi[3] = float4{ 12.0f,13.0f,14.0f,15.0f }; - - auto mm1 = (float2x2)mi; - auto mm2 = (float3x3)mi; - auto mm3 = (double4x4)mi; - - - float3 t3(1.0f); - auto len_1 = t3.lengthSquared(); - auto len_2 = t3.length(); - - auto norm_1 = t3.normalized(); - auto dot_1 = dot(t3, t3); - auto cross_1 = cross(float3::unitY(), float3::unitX()); - - auto pow_1 = lm::pow(float4(1.0f, 2.0f, 3.0f, 4.0f), 2.0f); - auto abs_1 = lm::abs(float4(1.0f, -2.0f, 3.0f, -4.0f)); - auto acos_1 = lm::acos(float4(1.0f, 0.0f, -1.0f, -0.75f)); - - auto asin_1 = lm::asin(float4(1.0f, 0.0f, -1.0f, -0.75f)); - auto atan_1 = lm::atan(float4(1.0f, 0.0f, -1.0f, -0.75f)); - - auto all_1 = lm::all(float4(0.0f, 0.0f, 0.0f, 0.0f)); - auto all_2 = lm::all(float4(0.0f, 0.0f, 0.0f, 1.0f)); - auto all_3 = lm::all(float4(0.0f, 0.0f, 1.0f, 1.0f)); - auto all_4 = lm::all(float4(0.0f, 1.0f, 1.0f, 1.0f)); - auto all_5 = lm::all(float4(1.0f, 1.0f, 1.0f, 1.0f)); - - auto any_1 = lm::any(float4(0.0f, 0.0f, 0.0f, 0.0f)); - auto any_2 = lm::any(float4(0.0f, 0.0f, 0.0f, 1.0f)); - auto any_3 = lm::any(float4(0.0f, 0.0f, 1.0f, 1.0f)); - auto any_4 = lm::any(float4(0.0f, 1.0f, 1.0f, 1.0f)); - auto any_5 = lm::any(float4(1.0f, 1.0f, 1.0f, 1.0f));*/ - -/* arr_result[idx] = lm::normalize(t3) + 2; - - float4x4 mat; - mat.rows[0] = float4(1, 0, 0, 1); - mat.rows[3] = float4(3); - auto col0 = mat.get_column(0); - - auto floor_1 = lm::floor(float4(3.3f, 4.4f, 5.5f, 6.6f)); - auto mat33 = (float3x3)mat; - auto mat44 = (float4x4)mat; - - auto mat33_2 = (float3x3)mat; - - auto is_mat1 = lm::matrix_traits::is_matrix::value; - auto is_mat2 = lm::matrix_traits::is_matrix::value; - - auto mmul1 = lm::matrix_traits::can_multiply::value; - auto mmul2 = lm::matrix_traits::can_multiply::value; - auto mmul3 = lm::matrix_traits::can_multiply::value; - - auto mul_r1 = lm::mul(mat33, mat33_2); - - auto is_identity_constexpr_4x4 = noexcept(float4x4::identity()); - auto is_identity_constexpr_3x3 = noexcept(float3x3::identity()); - auto id0 = float4x4::identity(); - auto id1 = float3x3::identity(); - auto id2 = float2x2::identity(); - - typedef Matrix double5x5; - auto is_identity_constexpr_5x5 = noexcept(double5x5::identity()); - auto id3 = double5x5::identity(); - - auto rc = double5x5::rows_count; - - auto mul_r = lm::mul(float3x4(1), float4x3(1)); - - auto mul_r2 = lm::mul(float3x3::identity(), float3x3::identity()); - - auto mul_r3 = lm::mul( - float2x3(float3(1, 3, 2), float3(0, 4, -1)), - float3x4(float4(2, 0, -1, 1), float4(3, -2, 1, 2), float4(0, 1, 2, 3))); - - - auto clamp_1 = lm::clamp(test_vector, 1.0f, 2.0f); - auto clamp_2 = lm::clamp(test_matrix, 0.0f, 7.0f); - - - auto cosh_1 = lm::cosh(test_vector); - auto cosh_2 = lm::cosh(test_matrix); - - auto cross_2 = lm::cross(float3(0, 1, 0), float3(0, 0, 1)); - auto cross_3 = lm::cross(float3(0, 0, 1), float3(0, 1, 0)); - - auto degrees_0 = lm::degrees(float3((float)LM_PI / 2.0f, (float)LM_PI / 1.0f, (float)LM_PI / 4.0f)); - - auto det_1 = lm::determinant(float2x2(float2(1, 2), float2(-1, 3))); - - auto det_2 = lm::determinant(float3x3::identity()); - - - - auto norm_2 = lm::normalize(float3(1, 2, 4)); - - - - });*/ - - /*arr_result.synchronize(access_type_auto); - - auto val = std::is_same::value; - - static_assert(sizeof(float2) == sizeof(float) * 2, "Float2 size incorrect"); - static_assert(sizeof(double2) == sizeof(double) * 2, "double2 size incorrect"); - - static_assert(sizeof(float3) == sizeof(float) * 3, "Float2 size incorrect"); - static_assert(sizeof(double3) == sizeof(double) * 3, "double3 size incorrect"); - - static_assert(sizeof(float4) == sizeof(float) * 4, "Float4 size incorrect"); - static_assert(sizeof(double4) == sizeof(double) * 4, "double4 size incorrect"); - - //CPU test - test_float2(); - test_float3(); - test_float4(); - - auto asdouble_0 = lm::asdouble(123, 456); - auto asdouble_1 = lm::asdouble(Vector(2, 2), Vector(300, 400)); - - - float3x3 m1; - auto col1 = m1.get_column(0); - auto m2 = float3x3::identity(); - auto m3 = float4x4::identity(); - auto m4 = lm::mul(m1, m2); - auto det1 = lm::determinant(m4); - - float3 t3(1); - auto len_1 = lm::lengthSquared(t3); - auto len_2 = lm::length(t3); - auto norm_1 = lm::normalize(t3); - auto dist_1 = lm::distance(t3, norm_1); - auto dot_1 = lm::dot(lm::normalize(t3), lm::normalize(t3)); - - - - - std::cin.get(); - - - //static_assert(noexcept(Test_amp()), "Not constexpr ("); - - static constexpr float3 f3 = float3::up(); - - static constexpr float4 f4 = float4(1, 0, 0, 1); - - static constexpr float4 f4_value = float4(1); - - static constexpr float4 f4_init = { 1.0f,2.0f,3.0f,4.0f }; - - - - double3 d_add(4); - float3 f_add(1); - f_add = f_add + 2; - - auto b0 = f_add + d_add; - auto b1 = f_add - d_add; - auto b2 = f_add * d_add; - auto b3 = f_add / d_add; - - auto b4 = f_add + 2; - auto b5 = f_add - 2; - auto b6 = f_add * 2; - auto b7 = f_add / 2; - - float3 fup = float3::up() * 2; - double3 dup = double3::up() * 2; - - auto flen_s = lm::lengthSquared(fup); - auto flen = lm::length(fup); - - - auto dlen_s = lm::lengthSquared(dup); - auto dlen = lm::length(dup); - - auto pow_1 = lm::pow(float4(1, 2, 3, 4), 2.0f); - auto abs_1 = lm::abs(float4(1, -2, 3, -4)); - auto acos_1 = lm::acos(float4(1, 0, -1, -0.75f)); - - float4x4 mat; - mat.rows[0] = float4(1, 0, 0, 1); - mat.rows[3] = float4(3); - auto col0 = mat.get_column(0); - - - float4x4 mWorld; - - mWorld = float4x4::identity(); - - - auto mat33 = (float3x3)mat; - auto mat44 = (float4x4)mat; - - auto mat33_2 = (float3x3)mat; - - auto is_mat1 = lm::matrix_traits::is_matrix::value; - auto is_mat2 = lm::matrix_traits::is_matrix::value; - - auto mmul1 = lm::matrix_traits::can_multiply::value; - auto mmul2 = lm::matrix_traits::can_multiply::value; - auto mmul3 = lm::matrix_traits::can_multiply::value; - - auto mul_r1 = lm::mul(mat33, mat33_2); - - - auto is_identity_constexpr_4x4 = noexcept(float4x4::identity()); - auto is_identity_constexpr_3x3 = noexcept(float3x3::identity()); - auto id0 = float4x4::identity(); - auto id1 = float3x3::identity(); - auto id2 = float2x2::identity(); - - - typedef Matrix double5x5; - auto is_identity_constexpr_5x5 = noexcept(double5x5::identity()); - auto id3 = double5x5::identity(); - - auto rc = double5x5::rows_count; - - auto mul_r = lm::mul(float3x4(1), float4x3(1)); - - auto mul_r2 = lm::mul(float3x3::identity(), float3x3::identity()); - - auto mul_r3 = lm::mul( - float2x3(float3(1, 3, 2), float3(0, 4, -1)), - float3x4(float4(2, 0, -1, 1), float4(3, -2, 1, 2), float4(0, 1, 2, 3))); - - auto is_square1 = lm::matrix_traits::is_square::value; - - - - - auto asin_1 = lm::asin(float4(1, 0, -1, -0.75f)); - auto atan_1 = lm::atan(float4(1, 0, -1, -0.75f)); - - auto all_1 = lm::all(float4(0, 0, 0, 0)); - auto all_2 = lm::all(float4(0, 0, 0, 1)); - auto all_3 = lm::all(float4(0, 0, 1, 1)); - auto all_4 = lm::all(float4(0, 1, 1, 1)); - auto all_5 = lm::all(float4(1, 1, 1, 1)); - - auto any_1 = lm::any(float4(0, 0, 0, 0)); - auto any_2 = lm::any(float4(0, 0, 0, 1)); - auto any_3 = lm::any(float4(0, 0, 1, 1)); - auto any_4 = lm::any(float4(0, 1, 1, 1)); - auto any_5 = lm::any(float4(1, 1, 1, 1)); - - - - - float4 test_vector = float4(3.3f, 4.4f, 5.5f, 6.6f); - float3x3 test_matrix = float3x3(float3(1.1f, 2.2f, 3.3f), float3(4.4f, 5.5f, 6.6f), float3(7.7f, 8.8f, 9.9f)); - - auto ceil_1 = lm::ceil(test_vector); - auto ceil_2 = lm::ceil(test_matrix); - - auto clamp_1 = lm::clamp(test_vector, 1.0f, 2.0f); - auto clamp_2 = lm::clamp(test_matrix, 0.0f, 7.0f); - - auto cos_1 = lm::cos(test_vector); - auto cos_2 = lm::cos(test_matrix); - - auto cosh_1 = lm::cosh(test_vector); - auto cosh_2 = lm::cosh(test_matrix); - - auto cross_1 = lm::cross(float3(0, 0, 1), float3(1, 0, 0)); - auto cross_2 = lm::cross(float3(0, 1, 0), float3(0, 0, 1)); - auto cross_3 = lm::cross(float3(0, 0, 1), float3(0, 1, 0)); - - auto degrees_0 = lm::degrees(float3((float)LM_PI / 2.0f, (float)LM_PI / 1.0f, (float)LM_PI / 4.0f)); - - auto det_1 = lm::determinant(float2x2(float2(1, 2), float2(-1, 3))); - - auto det_2 = lm::determinant(float3x3::identity()); - - - - auto norm_2 = lm::normalize(float3(1, 2, 4)); - - auto p1 = float3::up() / lm::length(float3::up()); - - - - - auto dot_2 = lm::dot(float3::up(), float3::up()); - auto dot_3 = lm::dot(float3::up(), lm::normalize(float3::up() + float3::right())); - - auto deg_1 = lm::degrees(std::acos(dot_1)); - auto deg_2 = lm::degrees(std::acos(dot_2)); - auto deg_3 = lm::degrees(std::acos(dot_3)); - - - - */ - return 0; -} - diff --git a/Dependencies/LMath/lmath_sandbox/lmath_sandbox.vcxproj b/Dependencies/LMath/lmath_sandbox/lmath_sandbox.vcxproj deleted file mode 100644 index 033bfc1..0000000 --- a/Dependencies/LMath/lmath_sandbox/lmath_sandbox.vcxproj +++ /dev/null @@ -1,155 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {9CB05983-8BE8-44E9-9E0D-63EBC7F37592} - Win32Proj - lmath_sandbox - 10.0.15063.0 - - - - Application - true - v141 - Unicode - - - Application - false - v141 - true - Unicode - - - Application - true - v141 - Unicode - - - Application - false - v141 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions);LM_AMP_SUPPORTED - stdcpplatest - gnu++1y - - - Console - - - - - - - Level3 - Disabled - _DEBUG;_CONSOLE;%(PreprocessorDefinitions);LM_AMP_SUPPORTED - stdcpplatest - gnu++1y - - - Console - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions);LM_AMP_SUPPORTED - stdcpplatest - gnu++1y - - - Console - true - true - - - - - Level3 - - - MaxSpeed - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions);LM_AMP_SUPPORTED - stdcpplatest - gnu++1y - - - Console - true - true - - - - - - - - - \ No newline at end of file diff --git a/Dependencies/LMath/lmath_test/lm_half_tests.cpp b/Dependencies/LMath/lmath_test/lm_half_tests.cpp deleted file mode 100644 index 1b5a6ba..0000000 --- a/Dependencies/LMath/lmath_test/lm_half_tests.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include "stdafx.h" -#include "CppUnitTest.h" -#include "../Src/lmath/lmath.h" -#include -#include - -using namespace Microsoft::VisualStudio::CppUnitTestFramework; -using namespace lm; - -namespace lmath_test { - TEST_CLASS(lm_half_test_class) { -public: - TEST_METHOD(lm_half_test) { - const float tolerance = 0.01f; - Half h1; - - h1 = 1.0f; - Assert::AreEqual(1.0f, h1.toFloat(), tolerance); - h1 = 0.0f; - Assert::AreEqual(0.0f, h1.toFloat(), tolerance); - h1 = -1.0f; - Assert::AreEqual(-1.0f, h1.toFloat(), tolerance); - h1 = -2.34f; - Assert::AreEqual(-2.34f, h1.toFloat(), tolerance); - - - Assert::IsFalse(h1.isNan()); - Assert::IsFalse(std::isnan(h1.toFloat())); - Assert::IsFalse(h1.isInf()); - Assert::IsFalse(std::isinf(h1.toFloat())); - - h1 = std::numeric_limits::signaling_NaN(); - Assert::IsTrue(h1.isNan()); - Assert::IsTrue(std::isnan(h1.toFloat())); - - h1 = std::numeric_limits::infinity(); - Assert::IsTrue(h1.isInf()); - Assert::IsTrue(std::isinf(h1.toFloat())); - - } - }; -} \ No newline at end of file diff --git a/Dependencies/LMath/lmath_test/lm_matrix_test.cpp b/Dependencies/LMath/lmath_test/lm_matrix_test.cpp deleted file mode 100644 index fb7d3d6..0000000 --- a/Dependencies/LMath/lmath_test/lm_matrix_test.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "stdafx.h" -#include "CppUnitTest.h" -#include "../Src/lmath/lmath.h" - -using namespace Microsoft::VisualStudio::CppUnitTestFramework; -using namespace lm; - -namespace lmath_test { - TEST_CLASS(lm_matrix_test_class) { -public: - TEST_METHOD(lm_matrix_test) { - lm::float3 z = lm::float3::unitZ(); - auto ryp90 = lm::matrix4x4RotationY(lm::pi_f / 2.0f); - auto ryn90 = lm::matrix4x4RotationY(-lm::pi_f / 2.0f); - auto xp = lm::mul(ryp90, lm::float4(z, 1.0f)).slice<0,3>(); - auto xn = lm::mul(ryn90, lm::float4(z, 1.0f)).slice<0, 3>(); - - Assert::IsTrue(xp.equals(lm::float3::unitX(), 0.001f)); - Assert::IsTrue(xn.equals(lm::float3::unitX() * -1.0f, 0.001f)); - } - - TEST_METHOD(lm_matrix_rotation_quaternion) { - auto m0 = lm::matrix4x4RotationY(lm::pi_f / 2.0f); - auto m1 = matrix4x4RotationQuaternion(lm::Quaternion_f::angleAxis(lm::pi_f / 2.0f, float3::unitY())); - - for (LmSize y = 0; y < 4; ++y) { - for (LmSize x = 0; x < 4; ++x) { - Assert::AreEqual(m0[y][x], m1[y][x], 0.0001f); - } - } - } - }; -} \ No newline at end of file diff --git a/Dependencies/LMath/lmath_test/lm_quaternion_test.cpp b/Dependencies/LMath/lmath_test/lm_quaternion_test.cpp deleted file mode 100644 index bd68358..0000000 --- a/Dependencies/LMath/lmath_test/lm_quaternion_test.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "stdafx.h" -#include "CppUnitTest.h" -#include "../Src/lmath/lmath.h" - -using namespace Microsoft::VisualStudio::CppUnitTestFramework; -using namespace lm; - -namespace lmath_test { - TEST_CLASS(lm_quaternion_test_class) { -public: - TEST_METHOD(lm_quaternion_test) { - lm::Quaternion q(0.0f, 1.0f, 2.0f, 3.0f); - Assert::AreEqual(0.0f, q[0]); - Assert::AreEqual(1.0f, q[1]); - Assert::AreEqual(2.0f, q[2]); - Assert::AreEqual(3.0f, q[3]); - - q = Quaternion::identity(); - Assert::AreEqual(0.0f, q[0]); - Assert::AreEqual(0.0f, q[1]); - Assert::AreEqual(0.0f, q[2]); - Assert::AreEqual(1.0f, q[3]); - - - lm::Quaternion q2 = q; - - auto q1 = lm::Quaternion_f::angleAxis(lm::pi_f / 2.0f, float3::unitY()); - - Assert::AreEqual(0.0f, q1[0], L"Q0"); - Assert::AreEqual(lm::cos(lm::pi_f / 4.0f), q1[1], L"Q1"); - Assert::AreEqual(0.0f, q1[2], L"Q2"); - Assert::AreEqual(lm::cos(lm::pi_f / 4.0f), q1[3], L"Q3"); - - q1 = q1 * q1; - - auto q3 = lm::Quaternion_f::angleAxis(lm::pi_f, float3::unitY()); - - const float epsilon = 0.0001f; - Assert::AreEqual(q3[0], q1[0], epsilon, L"Q0"); - Assert::AreEqual(q3[1], q1[1], epsilon, L"Q1"); - Assert::AreEqual(q3[2], q1[2], epsilon, L"Q2"); - Assert::AreEqual(q3[3], q1[3], epsilon, L"Q3"); - - Assert::AreEqual(0.0f, q1[0], epsilon, L"Q0"); - Assert::AreEqual(1.0f, q1[1], epsilon, L"Q1"); - Assert::AreEqual(0.0f, q1[2], epsilon, L"Q2"); - Assert::AreEqual(0.0f, q1[3], epsilon, L"Q3"); - - } - }; -} \ No newline at end of file diff --git a/Dependencies/LMath/lmath_test/lm_traits_test.cpp b/Dependencies/LMath/lmath_test/lm_traits_test.cpp deleted file mode 100644 index 10e3b1b..0000000 --- a/Dependencies/LMath/lmath_test/lm_traits_test.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "stdafx.h" -#include "CppUnitTest.h" -#include "../Src/lmath/lmath.h" - -using namespace Microsoft::VisualStudio::CppUnitTestFramework; -using namespace lm; - -namespace lmath_test{ - TEST_CLASS(lm_traits_test_class){ - public: - TEST_METHOD(lm_traits_test){ - - } - }; -} \ No newline at end of file diff --git a/Dependencies/LMath/lmath_test/lm_vector_test.cpp b/Dependencies/LMath/lmath_test/lm_vector_test.cpp deleted file mode 100644 index 74ad108..0000000 --- a/Dependencies/LMath/lmath_test/lm_vector_test.cpp +++ /dev/null @@ -1,424 +0,0 @@ -#include "stdafx.h" -#include "CppUnitTest.h" -#include "../Src/lmath/lmath.h" -#include "../Src/lmath/lm_vector_sse.h" - -using namespace Microsoft::VisualStudio::CppUnitTestFramework; -using namespace lm; - -namespace lmath_test { - TEST_CLASS(lm_vector_test_class) { -public: - - TEST_METHOD(lm_vector_test_sse_constructors_and_getters) { - lm::float4_sse v0; - Assert::AreEqual(0.0f, v0.get<0>()); - Assert::AreEqual(0.0f, v0.get<1>()); - Assert::AreEqual(0.0f, v0.get<2>()); - Assert::AreEqual(0.0f, v0.get<3>()); - - lm::float4_sse v1(5.0f); - Assert::AreEqual(5.0f, v1.get<0>(), L"0"); - Assert::AreEqual(5.0f, v1.get<1>(), L"1"); - Assert::AreEqual(5.0f, v1.get<2>(), L"2"); - Assert::AreEqual(5.0f, v1.get<3>(), L"3"); - - lm::float4_sse v2(2,3,4,5); - Assert::AreEqual(2.0f, v2.get<0>(), L"0"); - Assert::AreEqual(3.0f, v2.get<1>(), L"1"); - Assert::AreEqual(4.0f, v2.get<2>(), L"2"); - Assert::AreEqual(5.0f, v2.get<3>(), L"3"); - - Assert::AreEqual(v2.get(0), v2.get<0>(), L"0"); - Assert::AreEqual(v2.get(1), v2.get<1>(), L"1"); - Assert::AreEqual(v2.get(2), v2.get<2>(), L"2"); - Assert::AreEqual(v2.get(3), v2.get<3>(), L"3"); - - - auto m1 = v2 * v2; - Assert::AreEqual(m1.get<0>(), 4.0f, L"0"); - Assert::AreEqual(m1.get<1>(), 9.0f, L"1"); - Assert::AreEqual(m1.get<2>(), 16.0f, L"2"); - Assert::AreEqual(m1.get<3>(), 25.0f, L"3"); - - v2 *= v2; - Assert::AreEqual(v2.get<0>(), 4.0f, L"0"); - Assert::AreEqual(v2.get<1>(), 9.0f, L"1"); - Assert::AreEqual(v2.get<2>(), 16.0f, L"2"); - Assert::AreEqual(v2.get<3>(), 25.0f, L"3"); - - auto d1 = lm::float4_sse{ 2,4,6,8 }; - auto d2 = d1 / lm::float4_sse{ 2,2,3,4 }; - - Assert::AreEqual(d2.get<0>(), 1.0f, L"0"); - Assert::AreEqual(d2.get<1>(), 2.0f, L"1"); - Assert::AreEqual(d2.get<2>(), 2.0f, L"2"); - Assert::AreEqual(d2.get<3>(), 2.0f, L"3"); - - d1 /= lm::float4_sse{ 2,2,3,4 }; - Assert::AreEqual(d1.get<0>(), 1.0f, L"0"); - Assert::AreEqual(d1.get<1>(), 2.0f, L"1"); - Assert::AreEqual(d1.get<2>(), 2.0f, L"2"); - Assert::AreEqual(d1.get<3>(), 2.0f, L"3"); - - } - - template - void testMin() { - Assert::IsTrue(lm::min(1.0f, 2.0f) == 1.0f); - Assert::IsTrue(lm::min(2.0f, 1.0f) == 1.0f); - - V v1(1.0f, 2.0f, 3.0f, 4.0f); - V v2(-5.0f, 0.0f, 5.0f, 7.0f); - - const float epsilon = 0.001f; - Assert::IsTrue(lm::min(v1, v2).equals(V(-5.0f, 0.0f, 3.0f, 4.0f), epsilon)); - Assert::IsTrue(lm::min(v2, v1).equals(V(-5.0f, 0.0f, 3.0f, 4.0f), epsilon)); - Assert::IsTrue(lm::max(v1, v2).equals(V(1.0f, 2.0f, 5.0f, 7.0f), epsilon)); - Assert::IsTrue(lm::max(v2, v1).equals(V(1.0f, 2.0f, 5.0f, 7.0f), epsilon)); - - Assert::AreEqual(1.0f, lm::min(v1), epsilon); - Assert::AreEqual(-5.0f, lm::min(v2), epsilon); - - Assert::AreEqual(4.0f, lm::max(v1), epsilon); - Assert::AreEqual(7.0f, lm::max(v2), epsilon); - } - - TEST_METHOD(lm_vector_test_min_sse) { - testMin(); - } - TEST_METHOD(lm_vector_test_dot_sse) { - Assert::AreEqual(0.0f, dot(float4_sse(), float4_sse())); - Assert::AreEqual(1.0f, dot(float4_sse(1,1,1,1), float4_sse(1,0,0,0))); - } - - TEST_METHOD(lm_vector_test_min) { - testMin(); - } - TEST_METHOD(lm_vector_test_operators) { - float3 v1(0.0f); - float3 v2(2.0f); - double3 v3(0.0); - - Assert::IsTrue(v1 == v1); - Assert::IsFalse(v1 != v1); - - Assert::IsFalse(v1 == v2); - Assert::IsTrue(v1 != v2); - - Assert::IsTrue(v1 == v3); - Assert::IsFalse(v1 != v3); - const float epsilon = 0.0001f; - - v2 = v2 / 2.0f; - Assert::IsTrue(v2.equals(float3(1.0f), epsilon)); - v2 = v2 * 5.0f; - Assert::IsTrue(v2.equals(float3(5.0f), epsilon)); - v2 = v2 + 5.0f; - Assert::IsTrue(v2.equals(float3(10.0f), epsilon)); - v2 = v2 - 9.0f; - Assert::IsTrue(v2.equals(float3(1.0f), epsilon)); - v2 *= 3.0f; - Assert::IsTrue(v2.equals(float3(3.0f), epsilon)); - v2 /= 6.0f; - Assert::IsTrue(v2.equals(float3(0.5f), epsilon)); - v2 += 1.5f; - Assert::IsTrue(v2.equals(float3(2.0f), epsilon)); - v2 -= 2.0f; - Assert::IsTrue(v2.equals(float3(0.0f), epsilon)); - - } - TEST_METHOD(lm_vector_test_constructors_N1) { - Vector v1{}; - Vector v2(2.2f); - Vector v3{ 3.3f }; - Vector v4 = v3; - - Vector v5; - v5 = v3; - - Assert::AreEqual(2.2f, v2[0], L"v2 ctor fail"); - Assert::AreEqual(3.3f, v3[0], L"v3 ctor fail"); - Assert::AreEqual(3.3f, v4[0], L"v4 ctor fail"); - Assert::AreEqual(3.3f, v5[0], L"v5 ctor fail"); - } - TEST_METHOD(lm_vector_test_constructors_N2) { - Vector v1{}; - Vector v2(2.2f, 3.3f); - Vector v3{ 4.4f }; - Assert::AreEqual(2.2f, v2[0], L"v2 ctor fail"); - Assert::AreEqual(3.3f, v2[1], L"v2 ctor fail"); - Assert::AreEqual(4.4f, v3[0], L"v3 ctor fail"); - Assert::AreEqual(4.4f, v3[1], L"v3 ctor fail"); - } - TEST_METHOD(lm_vector_test_constructors_N3) { - Vector v1{}; - Vector v2(2.2f, 3.3f, 4.4f); - Vector v3{ 5.5f }; - - Assert::AreEqual(2.2f, v2[0], L"v2 ctor fail"); - Assert::AreEqual(3.3f, v2[1], L"v2 ctor fail"); - Assert::AreEqual(4.4f, v2[2], L"v2 ctor fail"); - - Assert::AreEqual(5.5f, v3[0], L"v3 ctor fail"); - Assert::AreEqual(5.5f, v3[1], L"v3 ctor fail"); - Assert::AreEqual(5.5f, v3[2], L"v3 ctor fail"); - - Vector v4(1.1f, 2.2f); - Vector v5(v4, 3.3f); - - Assert::AreEqual(1.1f, v5[0], L"v5 ctor fail"); - Assert::AreEqual(2.2f, v5[1], L"v5 ctor fail"); - Assert::AreEqual(3.3f, v5[2], L"v5 ctor fail"); - - Vector v6(3.3f, v4); - - Assert::AreEqual(3.3f, v6[0], L"v6 ctor fail"); - Assert::AreEqual(1.1f, v6[1], L"v6 ctor fail"); - Assert::AreEqual(2.2f, v6[2], L"v6 ctor fail"); - } - TEST_METHOD(lm_vector_test_constructors_N4) { - Vector v1{}; - Vector v2(1.1f, 2.2f, 3.3f, 4.4f); - Vector v3{ 5.5f }; - - Assert::AreEqual(1.1f, v2[0], L"v2 ctor fail"); - Assert::AreEqual(2.2f, v2[1], L"v2 ctor fail"); - Assert::AreEqual(3.3f, v2[2], L"v2 ctor fail"); - Assert::AreEqual(4.4f, v2[3], L"v2 ctor fail"); - - Assert::AreEqual(5.5f, v3[0], L"v3 ctor fail"); - Assert::AreEqual(5.5f, v3[1], L"v3 ctor fail"); - Assert::AreEqual(5.5f, v3[2], L"v3 ctor fail"); - Assert::AreEqual(5.5f, v3[3], L"v3 ctor fail"); - - Vector p2_1{ 6.6f, 7.7f }; - Vector p2_2{ 8.8f, 9.9f }; - Vector p3{ 6.0f, 7.0f, 8.0f }; - - Vector v4{ p2_1, p2_2 }; - Assert::AreEqual(p2_1[0], v4[0], L"v4 ctor fail"); - Assert::AreEqual(p2_1[1], v4[1], L"v4 ctor fail"); - Assert::AreEqual(p2_2[0], v4[2], L"v4 ctor fail"); - Assert::AreEqual(p2_2[1], v4[3], L"v4 ctor fail"); - - Vector v5(p2_1, 2.0f, 3.0f); - Assert::AreEqual(p2_1[0], v5[0], L"v5 ctor fail"); - Assert::AreEqual(p2_1[1], v5[1], L"v5 ctor fail"); - Assert::AreEqual(2.0f, v5[2], L"v5 ctor fail"); - Assert::AreEqual(3.0f, v5[3], L"v5 ctor fail"); - - Vector v6(2.0f, 3.0f, p2_1); - Assert::AreEqual(2.0f, v6[0], L"v6 ctor fail"); - Assert::AreEqual(3.0f, v6[1], L"v6 ctor fail"); - Assert::AreEqual(p2_1[0], v6[2], L"v6 ctor fail"); - Assert::AreEqual(p2_1[1], v6[3], L"v6 ctor fail"); - - - Vector v7(p3, 9.9f); - Assert::AreEqual(p3[0], v7[0], L"v7 ctor fail"); - Assert::AreEqual(p3[1], v7[1], L"v7 ctor fail"); - Assert::AreEqual(p3[2], v7[2], L"v7 ctor fail"); - Assert::AreEqual(9.9f, v7[3], L"v7 ctor fail"); - - Vector v8(9.9f, p3); - Assert::AreEqual(9.9f, v8[0], L"v8 ctor fail"); - Assert::AreEqual(p3[0], v8[1], L"v8 ctor fail"); - Assert::AreEqual(p3[1], v8[2], L"v8 ctor fail"); - Assert::AreEqual(p3[2], v8[3], L"v8 ctor fail"); - - } - TEST_METHOD(lm_vector_test_constructors_N) { - Vector v1(5.5f); - for (LmSize i = 0; i < 7; ++i) { - Assert::AreEqual(5.5f, v1[i], L"Vector N ctor fail"); - } - - Vector v2(0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f); - for (LmSize i = 0; i < 7; ++i) { - Assert::AreEqual((float)i, v2[i], L"Vector N ctor fail"); - } - - v1 = v2; - - for (LmSize i = 0; i < 7; ++i) { - Assert::AreEqual((float)i, v1[i], L"Vector N ctor fail"); - } - } - TEST_METHOD(lm_vector_test_slice) { - float3 v1(1.0f, 2.0f, 3.0f); - - auto& s1 = v1.slice<0, 1>(); - Assert::AreEqual((LmSize)1, s1.Size, L"Invalid slice size"); - Assert::AreEqual(1.0f, s1[0], L"Invalid slice value"); - - auto& s2 = v1.slice<0, 2>(); - Assert::AreEqual((LmSize)2, s2.Size, L"Invalid slice size"); - Assert::AreEqual(1.0f, s2[0], L"Invalid slice value"); - Assert::AreEqual(2.0f, s2[1], L"Invalid slice value"); - - auto& s3 = v1.slice<0, 3>(); - Assert::AreEqual((LmSize)3, s3.Size, L"Invalid slice size"); - Assert::AreEqual(1.0f, s3[0], L"Invalid slice value"); - Assert::AreEqual(2.0f, s3[1], L"Invalid slice value"); - Assert::AreEqual(3.0f, s3[2], L"Invalid slice value"); - - auto& s4 = v1.slice<1, 1>(); - Assert::AreEqual((LmSize)1, s4.Size, L"Invalid slice size"); - Assert::AreEqual(2.0f, s4[0], L"Invalid slice value"); - - auto& s5 = v1.slice<2, 1>(); - Assert::AreEqual((LmSize)1, s5.Size, L"Invalid slice size"); - Assert::AreEqual(3.0f, s5[0], L"Invalid slice value"); - } - TEST_METHOD(lm_vector_test_dot) { - double3 x{ 1.0, 0.0, 0.0 }; - double3 y{ 0.0, 1.0, 0.0 }; - double3 z{ 0.0, 0.0, 1.0 }; - - double3 _x{ -1.0, 0.0, 0.0 }; - - const double dotTolerance = 0.01; - Assert::AreEqual(1.0, lm::dot(x, x), dotTolerance, L"Dot fail"); - Assert::AreEqual(1.0, lm::dot(y, y), dotTolerance, L"Dot fail"); - Assert::AreEqual(1.0, lm::dot(z, z), dotTolerance, L"Dot fail"); - - Assert::AreEqual(0.0, lm::dot(x, y), dotTolerance, L"Dot fail"); - Assert::AreEqual(0.0, lm::dot(y, z), dotTolerance, L"Dot fail"); - Assert::AreEqual(0.0, lm::dot(x, z), dotTolerance, L"Dot fail"); - - Assert::AreEqual(-1.0, lm::dot(x, _x), dotTolerance, L"Dot fail"); - - double3 w{ 1.0, 1.0, 0.0 }; - w = lm::normalize(w); - - Assert::AreEqual(std::cos(lm::pi_d / 4.0), lm::dot(y, w), dotTolerance, L"Dot fail"); - Assert::AreEqual(-std::cos(lm::pi_d / 4.0), lm::dot(y, w * -1.0f), dotTolerance, L"Dot fail"); - } - TEST_METHOD(lm_vector_test_trigonometry) { - float3 v{ 2.0f, 3.0f, 4.0f }; - - auto vSin = lm::sin(v); - - Assert::AreEqual(std::sin(v[0]), vSin[0], L"Sin fail"); - Assert::AreEqual(std::sin(v[1]), vSin[1], L"Sin fail"); - Assert::AreEqual(std::sin(v[2]), vSin[2], L"Sin fail"); - } - TEST_METHOD(lm_vector_test_all_any) { - float3 v1{ 0.0f, 0.0f, 0.0f }; - float3 v2{ 0.0f, 0.0f, 3.0f }; - float3 v3{ 3.0f, 3.0f, 3.0f }; - - Assert::IsFalse(lm::all(v1)); - Assert::IsFalse(lm::any(v1)); - - Assert::IsFalse(lm::all(v2)); - Assert::IsTrue(lm::any(v2)); - - Assert::IsTrue(lm::all(v3)); - Assert::IsTrue(lm::any(v3)); - } - TEST_METHOD(lm_vector_test_unit) { - auto x2 = float2::unitX(); - auto y2 = float2::unitY(); - - Assert::AreEqual(1.0f, x2[0]); - Assert::AreEqual(0.0f, x2[1]); - - Assert::AreEqual(0.0f, y2[0]); - Assert::AreEqual(1.0f, y2[1]); - - auto z3 = float3::unitZ(); - auto w4 = float4::unitW(); - - Assert::AreEqual(0.0f, z3[0]); - Assert::AreEqual(0.0f, z3[1]); - Assert::AreEqual(1.0f, z3[2]); - - - Assert::AreEqual(0.0f, w4[0]); - Assert::AreEqual(0.0f, w4[1]); - Assert::AreEqual(0.0f, w4[2]); - Assert::AreEqual(1.0f, w4[3]); - } - TEST_METHOD(lm_vector_test_length_lengthSquared) { - float3 v1{ 1.0f, 0.0f, 0.0f }; - float3 v2{ 0.0f, 2.0f, 0.0f }; - float3 v3{ 1.0f, 1.0f, 0.0f }; - const float tolerance = 0.001f; - - Assert::AreEqual(1.0f, v1.length(), tolerance); - Assert::AreEqual(1.0f, v1.lengthSquared(), tolerance); - - Assert::AreEqual(2.0f, v2.length(), tolerance); - Assert::AreEqual(4.0f, v2.lengthSquared(), tolerance); - - Assert::AreEqual(std::sqrt(2.0f), v3.length(), tolerance); - Assert::AreEqual(2.0f, v3.lengthSquared(), tolerance); - } - - TEST_METHOD(lm_vector_test_equals) { - float3 v1(1.0f, 2.0f, 3.0f); - float3 v2(2.0f, 2.0f, 3.0f); - - float tolerance = 0.001f; - Assert::IsTrue(v1.equals(v1, tolerance)); - Assert::IsFalse(v1.equals(v2, tolerance)); - - for (LmSize i = 0; i < 3; ++i) { - v2[i] = v1[i] + tolerance * 2.0f; - } - - Assert::IsFalse(v1.equals(v2, tolerance)); - - } - - TEST_METHOD(lm_vector_test_cross) { - float3 x{ 1.0f, 0.0f, 0.0f }; - float3 y{ 0.0f, 1.0f, 0.0f }; - float3 z{ 0.0f, 0.0f, 1.0f }; - const float tolerance = 0.001f; - - auto c1 = lm::cross(y, z); - auto c2 = lm::cross(z, y); - - Assert::AreEqual(1.0f, c1[0], tolerance); - Assert::AreEqual(0.0f, c1[1], tolerance); - Assert::AreEqual(0.0f, c1[2], tolerance); - - Assert::AreEqual(-1.0f, c2[0], tolerance); - Assert::AreEqual(0.0f, c2[1], tolerance); - Assert::AreEqual(0.0f, c2[2], tolerance); - - } - - TEST_METHOD(lm_vector_test_normalize) { - float3 v1{ 1.0f,0.0f, 0.0f }; - float3 v2{ 2.0f,0.0f, 0.0f }; - float3 v3{ 2.0f,2.0f, 2.0f }; - float3 v4{ -2.0f, -2.0f, -2.0f }; - - const float tolerance = 0.001f; - Assert::AreEqual(1.0f, v1.normalized().length(), tolerance); - Assert::AreEqual(1.0f, v2.normalized().length(), tolerance); - Assert::AreEqual(1.0f, v3.normalized().length(), tolerance); - Assert::AreEqual(1.0f, v4.normalized().length(), tolerance); - } - - TEST_METHOD(lm_vector_test_lerp) { - float3 v1{ -1.0f }; - float3 v2{ 1.0f}; - - const float tolerance = 0.001f; - Assert::IsTrue(lm::lerp(v1, v2, 0.0f).equals(v1, tolerance)); - Assert::IsTrue(lm::lerp(v1, v2, 1.0f).equals(v2, tolerance)); - Assert::IsTrue(lm::lerp(v1, v2, 0.5f).equals(float3(0.0f, 0.0f, 0.0f), tolerance)); - Assert::IsTrue(lm::lerp(v1, v2, 0.1f).equals(float3(-0.8f, -0.8f, -0.8f), tolerance)); - Assert::IsTrue(lm::lerp(v1, v2, 0.9f).equals(float3(0.8f, 0.8f, 0.8f), tolerance)); - } - - - - - }; -} \ No newline at end of file diff --git a/Dependencies/LMath/lmath_test/lmath_test.vcxproj b/Dependencies/LMath/lmath_test/lmath_test.vcxproj deleted file mode 100644 index 6e6f625..0000000 --- a/Dependencies/LMath/lmath_test/lmath_test.vcxproj +++ /dev/null @@ -1,180 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {DD9111B5-C46C-4BA6-973C-362BD5946348} - Win32Proj - lmath_test - 10.0 - - - - DynamicLibrary - true - v143 - Unicode - false - - - DynamicLibrary - false - v143 - true - Unicode - false - - - DynamicLibrary - true - v143 - Unicode - false - - - DynamicLibrary - false - v143 - true - Unicode - false - - - - - - - - - - - - - - - - - - - - - true - - - true - - - true - - - true - - - - Use - Level3 - Disabled - $(VCInstallDir)UnitTest\include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;%(PreprocessorDefinitions) - true - stdcpplatest - - - Windows - true - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories) - - - - - Use - Level3 - Disabled - $(VCInstallDir)UnitTest\include;%(AdditionalIncludeDirectories) - _DEBUG;%(PreprocessorDefinitions) - true - stdcpplatest - - - Windows - true - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories) - - - - - Level3 - Use - MaxSpeed - true - true - $(VCInstallDir)UnitTest\include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;%(PreprocessorDefinitions) - true - stdcpplatest - - - Windows - true - true - true - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories) - - - - - Level3 - Use - MaxSpeed - true - true - $(VCInstallDir)UnitTest\include;%(AdditionalIncludeDirectories) - NDEBUG;%(PreprocessorDefinitions) - true - stdcpplatest - - - Windows - true - true - true - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories) - - - - - - - - - - - - - Create - Create - Create - Create - - - - - - - \ No newline at end of file diff --git a/Dependencies/LMath/lmath_test/stdafx.cpp b/Dependencies/LMath/lmath_test/stdafx.cpp deleted file mode 100644 index 75a4c59..0000000 --- a/Dependencies/LMath/lmath_test/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// lmath_test.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/Dependencies/LMath/lmath_test/stdafx.h b/Dependencies/LMath/lmath_test/stdafx.h deleted file mode 100644 index 43280fc..0000000 --- a/Dependencies/LMath/lmath_test/stdafx.h +++ /dev/null @@ -1,13 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#include "targetver.h" - -// Headers for CppUnitTest -#include "CppUnitTest.h" - -// TODO: reference additional headers your program requires here diff --git a/Dependencies/LMath/lmath_test/targetver.h b/Dependencies/LMath/lmath_test/targetver.h deleted file mode 100644 index 87c0086..0000000 --- a/Dependencies/LMath/lmath_test/targetver.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -// Including SDKDDKVer.h defines the highest available Windows platform. - -// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and -// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. - -#include diff --git a/Dependencies/LibPad/.gitignore b/Dependencies/LibPad/.gitignore deleted file mode 100644 index 259148f..0000000 --- a/Dependencies/LibPad/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app diff --git a/Dependencies/LibPad/CMakeLists.txt b/Dependencies/LibPad/CMakeLists.txt deleted file mode 100644 index 16fdc05..0000000 --- a/Dependencies/LibPad/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ - - -add_library(LibPad INTERFACE) - -target_include_directories(LibPad -INTERFACE - Src -) - -target_sources(LibPad -INTERFACE - Src/LibPad/PsIoPhy.h - Src/LibPad/PsIo.h - Src/LibPad/PsMemCard.h - Src/LibPad/PsPad.h -) \ No newline at end of file diff --git a/Dependencies/LibPad/LICENSE b/Dependencies/LibPad/LICENSE deleted file mode 100644 index 0444664..0000000 --- a/Dependencies/LibPad/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Sergey Serb - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Dependencies/LibPad/LibPad.pri b/Dependencies/LibPad/LibPad.pri deleted file mode 100644 index 85b297a..0000000 --- a/Dependencies/LibPad/LibPad.pri +++ /dev/null @@ -1,8 +0,0 @@ -SOURCES += $$files($$PWD/src/*.cpp, true) \ - $$PWD/src/LibPad/PsPad.c -SOURCES += $$files($$PWD/src/*.c, true) -HEADERS += $$files($$PWD/src/*.h, true) \ - $$PWD/src/LibPad/PsIo.h \ - $$PWD/src/LibPad/PsMemCard.h \ - $$PWD/src/LibPad/PsPad.h -INCLUDEPATH += $$PWD/Src diff --git a/Dependencies/LibPad/README.md b/Dependencies/LibPad/README.md deleted file mode 100644 index 9f15921..0000000 --- a/Dependencies/LibPad/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# LibPad -Low-level PS1/PS2 gamepad communication library (mostly for embedded usage) - -## Data interface -It is just SPI: LSB first, CPOL=1, CPHA=1 - -## Pad pinout - -| Pin number | Pin name | Meaning | -| ------------- | ------------------ |------------------------------------------------| -| 1 | DATA [Open-drain!] | Data from joypad/memory card (SPI_MISO on MCU). Open drain (requires pull-up) | -| 2 | CMD | Data to joypad/memory card (SPI_MOSI on MCU) | -| 3 | +7.6V | Power supply for vibration motors | -| 4 | GND | Ground | -| 5 | VCC | 3.6V (should work fine with 3.3V) | -| 6 | ATT | Attention (SPI_CS on MCU) | -| 7 | CLK | Clock (SPI_CLK on MCU) PS1: 250KHz for controller and memory card, 500KHz or 1MHz for multitap. PS2: 250KHz for controller, 25MHz for memory card | -| 8 | N/C [IRQ10] | Joy only (Konami Justifier). Typically not connected | -| 9 | Ack [IRQ7] [Open-drain!]| Goes low for at least 1 clock after each 8 bits transmitted with 60us timeout . Open drain (requires pull-up)| diff --git a/Dependencies/LibPad/Src/LibPad/PsIo.h b/Dependencies/LibPad/Src/LibPad/PsIo.h deleted file mode 100644 index 7210799..0000000 --- a/Dependencies/LibPad/Src/LibPad/PsIo.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -#include "PsIoPhy.h" - -struct PsIoBuffer { - uint8_t size; - uint8_t data[200] = {}; -}; - -struct PsIoPort { - uint8_t id; - PsIoPhy* phy; - PsIoBuffer rxBuffer; - - inline bool psIoPortExecuteCommand(uint8_t* cmd, uint8_t cmdSize) { - uint8_t i; - - if(!phy->begin()){ - return false; - } - - rxBuffer.size = 0; - for(i = 0; i < cmdSize; ++i){ - if(!phy->shift(cmd[i], &rxBuffer.data[i])){ - break; - } - rxBuffer.size = i + 1; - } - - phy->end(); - return true; - } -}; diff --git a/Dependencies/LibPad/Src/LibPad/PsIoPhy.h b/Dependencies/LibPad/Src/LibPad/PsIoPhy.h deleted file mode 100644 index 23b0d52..0000000 --- a/Dependencies/LibPad/Src/LibPad/PsIoPhy.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -struct PsIoPhy { - virtual ~PsIoPhy() = default; - virtual bool begin() = 0; - virtual bool shift(uint8_t txData, uint8_t* rxData) = 0; - virtual void end() = 0; -}; \ No newline at end of file diff --git a/Dependencies/LibPad/Src/LibPad/PsMemCard.h b/Dependencies/LibPad/Src/LibPad/PsMemCard.h deleted file mode 100644 index 35efb7c..0000000 --- a/Dependencies/LibPad/Src/LibPad/PsMemCard.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include "PsIo.h" -#include - -#define PS_MEM_CARD_BLOCK_STATE_BEGIN 0xA1 -#define PS_MEM_CARD_BLOCK_STATE_MIDDLE 0xA2 -#define PS_MEM_CARD_BLOCK_STATE_END 0xA2 -#define PS_MEM_CARD_BLOCK_STATE_FORMATTED 0xA0 -#define PS_MEM_CARD_BLOCK_STATE_BEGIN_DELETED 0xA1 -#define PS_MEM_CARD_BLOCK_STATE_MIDDLE_DELETED 0xA2 -#define PS_MEM_CARD_BLOCK_STATE_END_DELETED 0xA2 - -struct PsMemCard { - uint8_t slot; - struct PsIoPort* port; -}; - -int psMemCardReadId(struct PsMemCard* memcard){ - uint8_t cmd[] = { memcard->slot, 0x53, 0, 0, 0, 0, 0, 0, 0, 0 }; - return psIoPortExecuteCommand(memcard->port, cmd, sizeof(cmd)); -} - -int psMemCardRead(struct PsMemCard* memcard, uint16_t addr, uint8_t* rxBuffer128){ //Addr: 0..3FFh - int error; - - uint8_t cmd[10 + 128 + 2]; - memset(cmd, 0, sizeof(cmd)); - - cmd[0] = memcard->slot; - cmd[1] = 0x52; - cmd[4] = (uint8_t)((addr & 0xff00) >> 8); - cmd[5] = (uint8_t)(addr & 0xff); - - error = psIoPortExecuteCommand(memcard->port, cmd, sizeof(cmd)); - if(!error){ - memcpy(rxBuffer128, &memcard->port->rxBuffer.data[10], 128); - } - return error; -} diff --git a/Dependencies/LibPad/Src/LibPad/PsPad.h b/Dependencies/LibPad/Src/LibPad/PsPad.h deleted file mode 100644 index dce97be..0000000 --- a/Dependencies/LibPad/Src/LibPad/PsPad.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include "PsIo.h" - -struct PsPad { - uint8_t slot = 0x01; - struct PsIoPort* port; - - //(SCPH-1010) - inline bool psPadPollDigital(){ - uint8_t cmd[5] = {slot, 0x42, 0x00, 0x00, 0x00}; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - // (SCPH-1110) or (SCPH-1180) - inline bool psPadPollAnalog(){ - uint8_t cmd[9] = {slot, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - // DualShock 1,2 (SCPH-1180, SCPH-1200, SCPH-10010) - inline bool psPadPollAnalogRumble(std::uint8_t rightMotor, std::uint8_t leftMotor){ - uint8_t cmd[9] = {slot, 0x42, 0x00, 0x00, 0x00, rightMotor, leftMotor, 0x00, 0x00}; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - // DualShock 2 SCPH-10010 - inline bool psPadPollDualshock2(){ - uint8_t cmd[21] = {slot, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - - inline int psPadSetDataMask(uint8_t b0, uint8_t b1, uint8_t b2) { - uint8_t cmd[] = { slot, 0x4F, 0x00, b0, b1, b2, 0x00, 0x00, 0x00 }; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - inline int psPadConfigEnter() { - uint8_t cmd[] = { slot, 0x43, 0x00, 0x01, 0x00}; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - inline int psPadConfigExit() { - uint8_t cmd[] = { slot, 0x43, 0x00, 0x00, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A }; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - inline int psPadConfigQueryModel() { //no args 100% - uint8_t cmd[9] = { slot, 0x45, 0x00, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A }; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - inline int psPadConfigQueryAct(uint8_t b1) { //b1 = index - uint8_t cmd[9] = { slot, 0x46, 0x00, b1, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A }; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - inline int psPadConfigQueryComb(uint8_t b1) { //b1 - maybe index, not failed but single record - uint8_t cmd[9] = { slot, 0x47, 0x00, b1, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A }; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - inline int psPadConfigQueryMode(uint8_t b1) { //byte #6 - supported mode, b1 = index - uint8_t cmd[9] = { slot, 0x4c, 0x00, b1, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A }; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } - - inline int psPadSetControllerMode(uint8_t analog, uint8_t lockMode) { - uint8_t cmd[] = { slot, 0x44, 0x00, (uint8_t)(analog ? 0x01 : 0x00), (uint8_t)(lockMode ? 0x03 : 0x5A), 0x00, 0x00, 0x00, 0x00 }; - return port->psIoPortExecuteCommand(cmd, sizeof(cmd)); - } -}; diff --git a/Dependencies/SoftGL/.gitignore b/Dependencies/SoftGL/.gitignore deleted file mode 100644 index 3c7d0c7..0000000 --- a/Dependencies/SoftGL/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -Demo_TexturedTriangle/Debug/ -*.filters -*.user -Debug/ -*.suo -*.db -*.opendb -*.plog -Demo_TexturedTriangle/Release/Demo_Tex.C6A5DFA2.tlog/CL.command.1.tlog -Demo_TexturedTriangle/Release/ -SoftGL/Release/ -Release/ -SoftGL/BlockRasterizer.i-58160ea9 -SoftGL/BlockRasterizer.i-f3af7022 -/build diff --git a/Dependencies/SoftGL/CMakeLists.txt b/Dependencies/SoftGL/CMakeLists.txt deleted file mode 100644 index 1ddd9aa..0000000 --- a/Dependencies/SoftGL/CMakeLists.txt +++ /dev/null @@ -1,84 +0,0 @@ - - -add_library(SoftGL INTERFACE) - -target_include_directories(SoftGL -INTERFACE - Src -) - -target_link_libraries(SoftGL -INTERFACE - LMath -) - -target_sources(SoftGL -INTERFACE - Src/SoftGL/Bitmap.h - Src/SoftGL/BlockRasterizer.h - Src/SoftGL/Buffer.h - Src/SoftGL/config.h - Src/SoftGL/Debug.h - Src/SoftGL/DisplayMode.h - Src/SoftGL/dynamic_buffer.h - Src/SoftGL/Engine/FpsCounter.h - Src/SoftGL/Graphics2D.h - Src/SoftGL/IndexBuffer.h - Src/SoftGL/InputLayout.h - Src/SoftGL/InputSystem.h - Src/SoftGL/IRenderWindow.h - Src/SoftGL/IShader.h - Src/SoftGL/LString.h - Src/SoftGL/mip_utils.h - Src/SoftGL/PixelShader.h - Src/SoftGL/PSDefault.h - Src/SoftGL/PSDefaultColor.h - Src/SoftGL/PSFont.h - Src/SoftGL/PSTextured.h - Src/SoftGL/RasterizerSettings.h - Src/SoftGL/Ray.h - Src/SoftGL/RegisterBlock.h - Src/SoftGL/ResourceManager.h - Src/SoftGL/StaticBuffer.h - Src/SoftGL/StaticTexture.h - Src/SoftGL/static_mip_chain.h - Src/SoftGL/static_vector.h - Src/SoftGL/Texture.h - Src/SoftGL/TextureSampler.h - Src/SoftGL/texture_utils.h - Src/SoftGL/Tools.h - Src/SoftGL/Vertex.h - Src/SoftGL/VertexShader.h - Src/SoftGL/Viewport.h - Src/SoftGL/VSDefault.h - Src/SoftGL/VSScreenSpace.h - - - Src/SoftGL/Engine/camera.h - Src/SoftGL/Engine/camera_controller.h - Src/SoftGL/Engine/cube_generator.h - Src/SoftGL/Engine/FpsCounter.h - Src/SoftGL/Engine/fresnel.h - Src/SoftGL/Engine/gameobject.h - Src/SoftGL/Engine/imesh.h - Src/SoftGL/Engine/mesh.h - Src/SoftGL/Engine/plane_generator.h - Src/SoftGL/Engine/PsNormalMap.h - Src/SoftGL/Engine/transform.h - Src/SoftGL/Engine/shaders/textured_no_lit.h - - - Src/SoftGL/ImageDataAccessorR5G6B5.h - Src/SoftGL/ImageDataAccessorR8G8B8.h -INTERFACE - Src/SoftGL/BlockRasterizer.cpp - -) - - -if (WIN32) - target_sources(SoftGL - INTERFACE - Src/SoftGL/Platform/Windows/RenderWindow.cpp - ) -endif (WIN32) \ No newline at end of file diff --git a/Dependencies/SoftGL/LICENSE b/Dependencies/SoftGL/LICENSE deleted file mode 100644 index 0444664..0000000 --- a/Dependencies/SoftGL/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Sergey Serb - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Dependencies/SoftGL/README.md b/Dependencies/SoftGL/README.md deleted file mode 100644 index 7bb5e72..0000000 --- a/Dependencies/SoftGL/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# softgl -C++ Software 3D renderer diff --git a/Dependencies/SoftGL/Src/SoftGL/BRDF/lighting_core.h b/Dependencies/SoftGL/Src/SoftGL/BRDF/lighting_core.h deleted file mode 100644 index 6c1750d..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/BRDF/lighting_core.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef lighting_core_h__ -#define lighting_core_h__ - -#include -#include - -#ifndef MATH_PI -#define MATH_PI 3.1415926535 -#endif - -using namespace lm; - -float FresnelSchlickDielectric(float ior, float3 l, float3 h) { - float f0 = std::pow((1.0f - ior) / (1.0f + ior), 2.0f); - return f0 + (1.0f - f0) * std::pow(1.0f - dot(l, h), 5.0f); -} - -float FresnelSchlickConductor(float ior, float absorbtion, float3 l, float3 h) { - float n = ior; - float k = absorbtion; - return (std::pow(n - 1, 2) + 4.0f * n*std::pow(1.0f - dot(l, h), 5.0f) + k*k) / (std::pow(n + 1.0f, 2.0f) + k*k); -} - -float G_implicit(float3 n, float3 h, float3 v, float3 l) { - return (std::max)(0, dot(n, l)) * (std::max)(0, dot(n, v)); -} - -float G_Cook_Torrance(float3 n, float3 h, float3 v, float3 l) { - float VdotH = dot(v, h) + 1e-5f; - float NdotV = dot(n, v); - float NdotH = dot(n, h); - float NdotL = dot(n, l); - - float g1 = (2.0f * dot(n, h) * NdotV) / VdotH; - float g2 = (2.0f * dot(n, h) * dot(n, l)) / VdotH; - return (std::min)(1.0f, (std::min)(g1, g2)); -} - - -float D_BlinnPhong(lm::float3 h, lm::float3 n, float power) { - float normalization = ((power + 2.0f) / (2.0f * MATH_PI)); - //float normalization = 1; - //float normalization = ((power + 8) / (8.0f * MATH_PI)); - //float normalization = (power + 2) / (4 * MATH_PI*(2 - exp(-power / 2))); - //float normalization = ((power + 2)*(power + 4)) / (2 * MATH_PI*(pow(2, -power / 2) + power)); - return normalization * std::pow((std::max)(0.0f, lm::dot(n, h)), power); -} - -float chiGGX(float v) { - return v > 0 ? 1 : 0; -} - -float GGX_Distribution(float3 n, float3 h, float alpha) { - float NoH = dot(n, h); - float alpha2 = alpha * alpha; - float NoH2 = NoH * NoH; - float den = NoH2 * alpha2 + (1 - NoH2); - return (chiGGX(NoH) * alpha2) / (MATH_PI * den * den); -} - -float GGX_PartialGeometryTerm(float3 v, float3 n, float3 h, float alpha) { - float VoH2 = (std::max)(0.0f, (dot(v, h))); - float chi = chiGGX(VoH2 / (std::max)(0.0f, dot(v, n))); - VoH2 = VoH2 * VoH2; - float tan2 = (1.0f - VoH2) / VoH2; - return (chi * 2.0f) / (1.0f + std::sqrt(1.0f + alpha * alpha * tan2)); -} - -inline float D_Beckmann(lm::float3 h, lm::float3 n, float m) { - float c = lm::dot(n, h); - float T = c * c; - float M = m*m; - return std::exp((T - 1.0f) / (M*T)) / (M * T * T); -} - -float PhongToBeckmann(float a) { - return std::sqrt(2.0f / (a + 2.0f)); -} - -float BeckmannToPhong(float m) { - return 2.0f / (m*m) - 2.0f; -} - -float Fresnel(float c, float ior) { - float g = std::sqrt(ior*ior + c*c - 1); - return 0.5f * std::pow(g - c, 2.0f) / std::pow(g + c, 2.0f) * (1.0f + std::pow(c*(g + c) - 1.0f, 2.0f) / std::pow(c*(g - c) + 1.0f, 2.0f)); -} -#endif // lighting_core_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Bitmap.h b/Dependencies/SoftGL/Src/SoftGL/Bitmap.h deleted file mode 100644 index 335e374..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Bitmap.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef BITMAP_H -#define BITMAP_H - -#include - -/*struct BITMAPFILEHEADER { - int16 bfType; - int32 bfSize; - int16 Reserved1; - int16 Reserved2; - int32 bfOffBits; -};*/ - -#if defined(_MSC_VER) -#include -#else -#pragma pack(push,2) -typedef struct tagBITMAPFILEHEADER { - unsigned short bfType; - unsigned long bfSize; - unsigned short bfReserved1; - unsigned short bfReserved2; - unsigned long bfOffBits; -} BITMAPFILEHEADER, *LPBITMAPFILEHEADER, *PBITMAPFILEHEADER; -#pragma pack(pop) - - -#pragma pack(push,2) -typedef struct tagBITMAPINFOHEADER { - unsigned long biSize; - long biWidth; - long biHeight; - unsigned short biPlanes; - unsigned short biBitCount; - unsigned long biCompression; - unsigned long biSizeImage; - long biXPelsPerMeter; - long biYPelsPerMeter; - unsigned long biClrUsed; - unsigned long biClrImportant; -}BITMAPINFOHEADER, *PBITMAPINFOHEADER; -#pragma pack(pop) -#endif - -#endif // BITMAP_H diff --git a/Dependencies/SoftGL/Src/SoftGL/BlockRasterizer.cpp b/Dependencies/SoftGL/Src/SoftGL/BlockRasterizer.cpp deleted file mode 100644 index f6703e3..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/BlockRasterizer.cpp +++ /dev/null @@ -1,384 +0,0 @@ -#include "BlockRasterizer.h" -#include "TextureSampler.h" -#include -#include -#include "ImageDataAccessorR5G6B5.h" -#include "ImageDataAccessorR8G8B8.h" - -BlockRasterizer::BlockRasterizer() - :primitiveType(PT_TRIANGLE_LIST), vs(0), ps(0), geomLayout(0){ - - blendState.AlphaOperation = BLEND_OP_ADD; - blendState.SrcAlpha = BLEND_SRC_ALPHA; - blendState.DstAlpha = BLEND_INV_SRC_ALPHA; - blendState.BlendEnable = false; - - - NDCPlanes[0] = RasterizerPlane(1, 0, 0, 1);//left - NDCPlanes[1] = RasterizerPlane(-1, 0, 0, 1);//right - NDCPlanes[2] = RasterizerPlane(0, 1, 0, 1);//top - NDCPlanes[3] = RasterizerPlane(0, -1, 0, 1);//bottom - NDCPlanes[4] = RasterizerPlane(0, 0, 1, 0);//near plane (D3D NDC, NeraClip Z == 0) - NDCPlanes[5] = RasterizerPlane(0, 0, -1, 1);//far - - //NDCPlanes[6] = RasterizerPlane(0, 0, 0, 1);//WTF? -} - -BlockRasterizer::~BlockRasterizer() { - -} - - - - - -bool BlockRasterizer::ClipToFrustumPlane(RasterizerPlane plane, ClipVector& src, ClipVector& dst, size_t regCount) { - auto face_count = src.size(); - bool clipped = false; - for (size_t i = 0; i < face_count; i++) { - //read face from input - ClipFace face = src[i]; - int v0out, v1out, v2out, vout_cnt; - v0out = v1out = v2out = vout_cnt = 0; - if (lm::dot(plane, face.v0.reg[0]) <= 0) { v0out++; vout_cnt++; } - if (lm::dot(plane, face.v1.reg[0]) <= 0) { v1out++; vout_cnt++; } - if (lm::dot(plane, face.v2.reg[0]) <= 0) { v2out++; vout_cnt++; } - - - switch (vout_cnt) { - case 3://all 3 vertices behind plane! Clip entire triangle - clipped = true; - continue; - case 2: - { - //printf("2 vertices behind plane!\n"); - clipped = true; - RegisterBlock* vert[3]; - RegisterBlock vA, vB; - if (v0out && v1out) { vert[0] = &face.v0; vert[1] = &face.v1; vert[2] = &face.v2; } - if (v1out && v2out) { vert[0] = &face.v1; vert[1] = &face.v2; vert[2] = &face.v0; } - if (v2out && v0out) { vert[0] = &face.v2; vert[1] = &face.v0; vert[2] = &face.v1; } - - float alpha_a = lm::dot(plane, vert[2]->reg[0]) / (lm::dot(plane, vert[2]->reg[0]) - lm::dot(plane, vert[1]->reg[0])); - float alpha_b = lm::dot(plane, vert[2]->reg[0]) / (lm::dot(plane, vert[2]->reg[0]) - lm::dot(plane, vert[0]->reg[0])); - - for (size_t k = 0; k < regCount; k++) { - vA.reg[k] = vert[2]->reg[k] + (vert[1]->reg[k] - vert[2]->reg[k]) * alpha_a; - vB.reg[k] = vert[2]->reg[k] + (vert[0]->reg[k] - vert[2]->reg[k]) * alpha_b; - } - - ClipFace fa; - fa.v0 = vA; - fa.v1 = *vert[2]; - fa.v2 = vB; - dst.push_back(fa); - - } - break; - case 1: - { - clipped = true; - RegisterBlock* vert[3]; - RegisterBlock vA, vB; - if (v0out) { vert[0] = &face.v0; vert[1] = &face.v1; vert[2] = &face.v2; } - if (v1out) { vert[0] = &face.v1; vert[1] = &face.v2; vert[2] = &face.v0; } - if (v2out) { vert[0] = &face.v2; vert[1] = &face.v0; vert[2] = &face.v1; } - - float alpha_a = lm::dot(plane, vert[2]->reg[0]) / (lm::dot(plane, vert[2]->reg[0]) - lm::dot(plane, vert[0]->reg[0])); - float alpha_b = lm::dot(plane, vert[1]->reg[0]) / (lm::dot(plane, vert[1]->reg[0]) - lm::dot(plane, vert[0]->reg[0])); - - for (size_t k = 0; k < regCount; k++) { - vA.reg[k] = vert[2]->reg[k] + (vert[0]->reg[k] - vert[2]->reg[k]) * alpha_a; - vB.reg[k] = vert[1]->reg[k] + (vert[0]->reg[k] - vert[1]->reg[k]) * alpha_b; - } - - ClipFace fa; - fa.v0 = vB; - fa.v1 = *vert[1]; - fa.v2 = vA; - dst.push_back(fa); - - ClipFace fb; - fb.v0 = vA; - fb.v1 = *vert[1]; - fb.v2 = *vert[2]; - dst.push_back(fb); - - //DrawTriangle(rA_out, *vert[1], *vert[2]); - } - break; - case 0: - dst.push_back(face); //nothing to crop! Just push it - break; - } - } - return clipped; -} - -void BlockRasterizer::ClipToFrustum(ClipFace face, ClipVector& dst, size_t regCount) { - - cv1.clear(); - cv2.clear(); - - dst.clear(); - - cv1.push_back(face); - - if(ClipToFrustumPlane(NDCPlanes[0], cv1, cv2, regCount)){ - std::cout << "Clipped with plane 0" << std::endl; - } - cv1.clear(); - - if (ClipToFrustumPlane(NDCPlanes[1], cv2, cv1, regCount)) { - std::cout << "Clipped with plane 1" << std::endl; - } - cv2.clear(); - - if (ClipToFrustumPlane(NDCPlanes[2], cv1, cv2, regCount)) { - std::cout << "Clipped with plane 2" << std::endl; - } - cv1.clear(); - - if (ClipToFrustumPlane(NDCPlanes[3], cv2, cv1, regCount)) { - std::cout << "Clipped with plane 3" << std::endl; - } - cv2.clear(); - - if (ClipToFrustumPlane(NDCPlanes[4], cv1, cv2, regCount)) { - std::cout << "Clipped with plane 4" << std::endl; - } - //cv1.clear(); - - if (ClipToFrustumPlane(NDCPlanes[5], cv2, dst, regCount)) { - std::cout << "Clipped with plane 5" << std::endl; - } - /*if (ClipToFrustumPlane(NDCPlanes[6], cv1, dst)) { - std::cout << "Clipped with plane 6" << std::endl; - }*/ -} - -Texture* BlockRasterizer::GetBackBuffer() { - return backBuffer; -} - -Texture* BlockRasterizer::GetDepthBuffer() { - return depthBuffer; -} - -void BlockRasterizer::setColorBuffer(Texture* buffer) { - backBuffer = buffer; -} - -void BlockRasterizer::setDepthBuffer(Texture* buffer) { - depthBuffer = buffer; -} - -void BlockRasterizer::SetPrimitiveType(int type) { - primitiveType = type; -} - -void BlockRasterizer::Draw(size_t offset, size_t length) { - if (!length) return; - switch (primitiveType) { - case PT_TRIANGLE_LIST: - { - auto faceCount = length / 3; - Buffer* geom = vbSlots[0].buffer; - - if (!faceCount){ - DebugInfo("No faces to draw"); - return; - } - if (!geom){ - DebugError("Vertex Buffer is not set"); - return; - } - - auto stride = vbSlots[0].stride; - - //Buffer is too small for this draw call - if (geom->Size() / stride < faceCount * 3) { - DebugError("[Draw] Vertex Buffer is too small!"); - return; - } - uint8_t* data = (uint8_t*)geom->GetPointer(); - for (size_t i = 0; i < faceCount; i++) { - //setup vertex data pointers - uint8_t* v0 = data + ((offset + 0 + i * 3) * stride); - uint8_t* v1 = data + ((offset + 1 + i * 3) * stride); - uint8_t* v2 = data + ((offset + 2 + i * 3) * stride); - draw_impl(v0, v1, v2); - } - } - break; - } -} - -void BlockRasterizer::DrawIndexed(size_t index_count, size_t start_index_location) -{ - if (index_count == 0) return; - switch (primitiveType) { - case PT_TRIANGLE_LIST: - { - int faceCount = index_count / 3; - Buffer* geom = vbSlots[0].buffer; - Buffer* indices = ibSlots[0]; - - if (!faceCount) { - DebugInfo("No faces to draw"); - return; - } - if (!geom) { - DebugError("Vertex Buffer is not set"); - return; - } - if (!indices) { - DebugError("Index Buffer is not set"); - return; - } - int stride = vbSlots[0].stride; - - uint8_t* vertex_data = (uint8_t*)geom->GetPointer(); - auto vertices_count = geom->Size() / vbSlots[0].stride; - indices_t* index_data = (indices_t*)indices->GetPointer(); - - for (size_t i = 0; i < index_count; i+=3) { - //setup vertex data pointers - auto id0 = index_data[i + 0 + start_index_location]; - auto id1 = index_data[i + 1 + start_index_location]; - auto id2 = index_data[i + 2 + start_index_location]; - - uint8_t* v0 = vertex_data + id0 * stride; - uint8_t* v1 = vertex_data + id1 * stride; - uint8_t* v2 = vertex_data + id2 * stride; - draw_impl(v0, v1, v2); - } - } - break; - } -} - -void BlockRasterizer::draw_impl(void* v0, void* v1, void* v2) -{ - int elements = geomLayout->Size(); - for (int i = 0; i < elements; i++) { //TODO: OMG WTF! Fix memory corruption!!! - InputElement* e = geomLayout->GetElement(i); - int rd = regMapping[i]; - if(rd >= 0){ - r0_in[rd] = reinterpret_cast((uint8_t*)v0 + e->Offset); - r1_in[rd] = reinterpret_cast((uint8_t*)v1 + e->Offset); - r2_in[rd] = reinterpret_cast((uint8_t*)v2 + e->Offset); - } - } - vs->Execute(&r0_in[0], &r0_out.reg[0]); - vs->Execute(&r1_in[0], &r1_out.reg[0]); - int numInterpolators = vs->Execute(&r2_in[0], &r2_out.reg[0]); - - - //r0_out.reg[0].y() = -r0_out.reg[0].y(); - //r1_out.reg[0].y() = -r1_out.reg[0].y(); - //r2_out.reg[0].y() = -r2_out.reg[0].y(); - - ClipVector cv; - ClipFace cf; - cf.v0 = r0_out; - cf.v1 = r1_out; - cf.v2 = r2_out; - - ClipToFrustum(cf, cv, numInterpolators); - - - auto bbDesc = backBuffer->Desc(); - - - if (bbDesc.BytesPerPixel == 4) { - for (size_t l = 0; l < cv.size(); l++) { - ClipFace cf_render = cv[l]; - DrawTriangle(cf_render.v0, cf_render.v1, cf_render.v2); - } - } - else if (bbDesc.BytesPerPixel == 2) { - for (size_t l = 0; l < cv.size(); l++) { - ClipFace cf_render = cv[l]; - DrawTriangle(cf_render.v0, cf_render.v1, cf_render.v2); - } - } - else { - //Not supported - } - - -} - -void BlockRasterizer::FixupMapping() { - if (geomLayout != 0) { - if (vs != 0) { - auto elements = geomLayout->Size(); - for (size_t i = 0; i < elements; i++) { - regMapping[i] = vs->FindRegister(geomLayout->GetElement(i)->name); - } - } - } -} - -void BlockRasterizer::SetVertexBuffer(Buffer* vb, size_t slot, size_t stride) { - vbSlots[slot].buffer = vb; - vbSlots[slot].stride = stride; -} - -void BlockRasterizer::SetIndexBuffer(Buffer* ib, size_t slot){ - ibSlots[slot] = ib; -} - -void BlockRasterizer::SetInputLayout(IInputLayout* layout) { - geomLayout = layout; - FixupMapping(); -} - -void BlockRasterizer::SetPixelShader(PixelShader* shader) { - ps = shader; -} - -void BlockRasterizer::SetVertexShader(VertexShader* shader) { - vs = shader; - FixupMapping(); -} - -void BlockRasterizer::SetBlendState(BlendState* state) { - blendState = *state; -} - -float BlockRasterizer::GetBlendAlpha(BLEND_SOURCE src, const float4& srcColor, const float4& dstColor) { - switch (src) { - case BLEND_ZERO: - return 0.0f; - case BLEND_ONE: - return 1.0f; - case BLEND_SRC_ALPHA: - return srcColor.w(); - case BLEND_INV_SRC_ALPHA: - return 1.0f - srcColor.w(); - } - return 0; -} - -uint32_t BlockRasterizer::ConvertColor(const float4& color) { - uint32_t r = (uint32_t)(color.x() * 255.0f); - uint32_t g = (uint32_t)(color.y() * 255.0f); - uint32_t b = (uint32_t)(color.z() * 255.0f); - uint32_t a = (uint32_t)(color.w() * 255.0f); - - return (a << 24) | (r << 16) | (g << 8) | (b); -} - -float4 BlockRasterizer::ConvertColor(uint32_t color) { - float d = 1.0f / 255.0f; - - float a = (float)((color >> 24) & 0xff) * d; - float r = (float)((color >> 16) & 0xff) * d; - float g = (float)((color >> 8) & 0xff) * d; - float b = (float)((color >> 0) & 0xff) * d; - - return float4(r, g, b, a); -} - diff --git a/Dependencies/SoftGL/Src/SoftGL/BlockRasterizer.h b/Dependencies/SoftGL/Src/SoftGL/BlockRasterizer.h deleted file mode 100644 index c32bc30..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/BlockRasterizer.h +++ /dev/null @@ -1,483 +0,0 @@ -#ifndef BlockRasterizer_h__ -#define BlockRasterizer_h__ - -#include "Texture.h" -#include "Viewport.h" -#include "InputLayout.h" -#include "VertexShader.h" -#include "PixelShader.h" -#include -#include -#include "Tools.h" -#include -#include "IRenderWindow.h" -#include "static_vector.h" -#include "RasterizerSettings.h" -#include -#include "Debug.h" -#include "RegisterBlock.h" -#include - -using namespace lm; - -enum PRIMITIVE_TYPE -{ - PT_TRIANGLE_LIST = 0, - PT_TRIANGLE_STRIP = 1, - PT_LINE_LIST = 2, - PT_LINE_STRIP = 3, - PT_POINT_LIST = 4 - -}; -enum BLEND_SOURCE -{ - BLEND_ZERO = 0, - BLEND_ONE = 1, - BLEND_SRC_ALPHA = 3, - BLEND_INV_SRC_ALPHA = 4 -}; -enum BLEND_OP -{ - BLEND_OP_ADD = 0 -}; -struct BlendState -{ - BLEND_SOURCE SrcAlpha; - BLEND_SOURCE DstAlpha; - BLEND_OP AlphaOperation; - bool BlendEnable; -}; -enum NDCZone -{ - ZONE_ZERO = 0, - ZONE_LEFT = 1, - ZONE_RIGHT = 2, - ZONE_BOTTOM = 3, - ZONE_TOP = 4, - ZONE_FAR = 5, - ZONE_NEAR = 6 -}; - -static constexpr const char* NDCZoneStr[7]{ - "ZONE_ZERO", - "ZONE_LEFT", - "ZONE_RIGHT", - "ZONE_BOTTOM", - "ZONE_TOP", - "ZONE_FAR", - "ZONE_NEAR" -}; - -struct ClipFace -{ - RegisterBlock v0; - RegisterBlock v1; - RegisterBlock v2; -}; - - -class BlockRasterizer { -public: - typedef Plane RasterizerPlane; - typedef Static_vector ClipVector; - - BlockRasterizer(); - ~BlockRasterizer(); - bool ClipToFrustumPlane(RasterizerPlane plane, ClipVector& src, ClipVector& dst, size_t regCount); - void ClipToFrustum(ClipFace face, ClipVector& dst, size_t regCount); - Texture* GetBackBuffer(); - Texture* GetDepthBuffer(); - - void setColorBuffer(Texture* buffer); - void setDepthBuffer(Texture* buffer); - - void SetPrimitiveType(int type); - void Draw(size_t offset, size_t length); - void DrawIndexed(size_t index_count, size_t start_index_location); - void FixupMapping(); - void SetVertexBuffer(Buffer* vb, size_t slot, size_t stride); - void SetIndexBuffer(Buffer* ib, size_t slot); - - void SetInputLayout(IInputLayout* layout); - void SetPixelShader(PixelShader* shader); - void SetVertexShader(VertexShader* shader); - void SetBlendState(BlendState* state); - - float GetBlendAlpha(BLEND_SOURCE src, const float4& srcColor, const float4& dstColor); -private: - ClipVector cv1, cv2; - void draw_impl(void* v0, void* v1, void* v2); - - IRenderWindow* render_window; - std::array NDCPlanes; - - uint32_t ConvertColor(const float4& color); - float4 ConvertColor(uint32_t color); - - - template - inline void CalcDerivatives( - int dy10, int dy20, - int dx10, int dx20, - _Var z0, _Var z1, _Var z2, _Var& ddx, _Var& ddy) { - - const auto dc10 = z1 - z0; - const auto dc20 = z2 - z0; - - //(iy1 - iy0) - auto A = dc20 * dy10 - dc10 * dy20; - auto B = dc10 * dx20 - dc20 * dx10; - int C = dy20 * dx10 - dx20 * dy10; - - ddx = A / (float)-C; - ddy = B / (float)-C; - } - - - template - void DrawTriangle(RegisterBlock r0_src, RegisterBlock r1_src, RegisterBlock r2_src) { - float scrW_h = (float)(backBuffer->Desc().Width / 2); - float scrH_h = (float)(backBuffer->Desc().Height / 2); - - RegisterBlock* p0 = &r0_src; - RegisterBlock* p1 = &r1_src; - RegisterBlock* p2 = &r2_src; - - //p1->reg[0].W = abs(p1->reg[0].W); - float iw0 = 1.0f / p0->reg[0].w(); - float iw1 = 1.0f / p1->reg[0].w(); - float iw2 = 1.0f / p2->reg[0].w(); - - //transform vertices to viewport space - p0->reg[0].x() = (p0->reg[0].x() * iw0) * scrW_h + scrW_h; - p0->reg[0].y() = (p0->reg[0].y() * iw0) * scrH_h + scrH_h; - p0->reg[0].z() = (p0->reg[0].z() * iw0); - - p1->reg[0].x() = (p1->reg[0].x() * iw1) * scrW_h + scrW_h; - p1->reg[0].y() = (p1->reg[0].y() * iw1) * scrH_h + scrH_h; - p1->reg[0].z() = (p1->reg[0].z() * iw1); - - p2->reg[0].x() = (p2->reg[0].x() * iw2) * scrW_h + scrW_h; - p2->reg[0].y() = (p2->reg[0].y() * iw2) * scrH_h + scrH_h; - p2->reg[0].z() = (p2->reg[0].z() * iw2); - - float3 camZ(p0->reg[0].z(), p1->reg[0].z(), p2->reg[0].z()); - - bool disableCulling = false; - if (disableCulling) - if (((p1->reg[0].x() - p0->reg[0].x()) * (p2->reg[0].y() - p0->reg[0].y()) - (p1->reg[0].y() - p0->reg[0].y()) * (p2->reg[0].x() - p0->reg[0].x()) <= 0)) { - RegisterBlock* pTmp = p0; - p0 = p2; - p2 = pTmp; - } - - - const int x0 = (int)std::round(16.0f * p0->reg[0].x()); - const int x1 = (int)std::round(16.0f * p1->reg[0].x()); - const int x2 = (int)std::round(16.0f * p2->reg[0].x()); - const int y0 = (int)std::round(16.0f * p0->reg[0].y()); - const int y1 = (int)std::round(16.0f * p1->reg[0].y()); - const int y2 = (int)std::round(16.0f * p2->reg[0].y()); - - const int Dx01 = x0 - x1; - const int Dx12 = x1 - x2; - const int Dx20 = x2 - x0; - - const int Dy01 = y0 - y1; - const int Dy12 = y1 - y2; - const int Dy20 = y2 - y0; - - const int FDx01 = Dx01 << 4; - const int FDx12 = Dx12 << 4; - const int FDx20 = Dx20 << 4; - - const int FDy01 = Dy01 << 4; - const int FDy12 = Dy12 << 4; - const int FDy20 = Dy20 << 4; - - //bounding rectangle - int minX = ((std::min)((std::min)(x0, x1), x2) + 0xF) >> 4; - int maxX = ((std::max)((std::max)(x0, x1), x2) + 0xF) >> 4; - int minY = ((std::min)((std::min)(y0, y1), y2) + 0xF) >> 4; - int maxY = ((std::max)((std::max)(y0, y1), y2) + 0xF) >> 4; - - const int ix0 = (x0 + 0xf) >> 4; - const int ix1 = (x1 + 0xf) >> 4; - const int ix2 = (x2 + 0xf) >> 4; - - const int iy0 = (y0 + 0xf) >> 4; - const int iy1 = (y1 + 0xf) >> 4; - const int iy2 = (y2 + 0xf) >> 4; - - const int diy20 = iy2 - iy0; - const int dix20 = ix2 - ix0; - const int diy10 = iy1 - iy0; - const int dix10 = ix1 - ix0; - - const int area = dix10 * diy20 - dix20 * diy10; - - if (area == 0) return; - - - if (maxY < 0) - return; - if (minY >= (int)backBuffer->Desc().Height) - return; - if (maxX < 0) - return; - if (minX >= (int)backBuffer->Desc().Width) - return; - - if (minY < 0) - minY = 0; - if (maxY >= (int)backBuffer->Desc().Height) - maxY = (int)backBuffer->Desc().Height - 1; - - if (minX < 0) - minX = 0; - if (maxX >= (int)backBuffer->Desc().Width) - maxX = (int)backBuffer->Desc().Width - 1; - - - int blockSize = 8; - - minX &= ~(blockSize - 1); - minY &= ~(blockSize - 1); - - auto bbPtr = reinterpret_cast(backBuffer->LockWrite()); - - auto dbPtr = reinterpret_cast(depthBuffer->LockWrite()); - - bbPtr += minY * backBuffer->Desc().Width; - dbPtr += minY * depthBuffer->Desc().Width; - - int C1 = Dy01 * x0 - Dx01 * y0; - int C2 = Dy12 * x1 - Dx12 * y1; - int C3 = Dy20 * x2 - Dx20 * y2; - - - //top-left fill convention fix - if (!(Dy01 < 0 || (Dy01 == 0 && Dx01 > 0))) C1--; - if (!(Dy12 < 0 || (Dy12 == 0 && Dx12 > 0))) C2--; - if (!(Dy20 < 0 || (Dy20 == 0 && Dx20 > 0))) C3--; - - RegisterBlock triDerivX; - RegisterBlock triDerivY; - - RegisterBlock invRegs[3]; - for (int i = 1; i < REG_COUNT; i++) { - invRegs[0].reg[i] = p0->reg[i] * iw0; - invRegs[1].reg[i] = p1->reg[i] * iw1; - invRegs[2].reg[i] = p2->reg[i] * iw2; - } - - for (int i = 1; i < REG_COUNT; i++) { - CalcDerivatives<8, float4>(diy10, diy20, dix10, dix20, invRegs[0].reg[i], invRegs[1].reg[i], invRegs[2].reg[i], triDerivX.reg[i], triDerivY.reg[i]); - } - float2 derivZW_X; - float2 derivZW_Y; - - float2 p0zw = p0->reg[0].zw(); - p0zw.y() = 1.0f / p0zw.y(); - - float2 p1zw = p1->reg[0].zw(); - p1zw.y() = 1.0f / p1zw.y(); - - float2 p2zw = p2->reg[0].zw(); - p2zw.y() = 1.0f / p2zw.y(); - - CalcDerivatives<8, float2>(diy10, diy20, dix10, dix20, p0zw, p1zw, p2zw, derivZW_X, derivZW_Y); - - //scan all blocks - for (int y = minY; y < maxY; y += blockSize) { - for (int x = minX; x < maxX; x += blockSize) { - //find block corners - int x0 = x << 4; - int x1 = (x + blockSize - 1) << 4; - int y0 = y << 4; - int y1 = (y + blockSize - 1) << 4; - - //evaluate half space functions for each corner - bool a00 = C1 + Dx01 * y0 - Dy01 * x0 < 0; - bool a01 = C1 + Dx01 * y0 - Dy01 * x1 < 0; - bool a10 = C1 + Dx01 * y1 - Dy01 * x0 < 0; - bool a11 = C1 + Dx01 * y1 - Dy01 * x1 < 0; - int a = (a00 << 0) | (a10 << 1) | (a01 << 2) | (a11 << 3); - - bool b00 = C2 + Dx12 * y0 - Dy12 * x0 < 0; - bool b01 = C2 + Dx12 * y0 - Dy12 * x1 < 0; - bool b10 = C2 + Dx12 * y1 - Dy12 * x0 < 0; - bool b11 = C2 + Dx12 * y1 - Dy12 * x1 < 0; - int b = (b00 << 0) | (b10 << 1) | (b01 << 2) | (b11 << 3); - - bool c00 = C3 + Dx20 * y0 - Dy20 * x0 < 0; - bool c01 = C3 + Dx20 * y0 - Dy20 * x1 < 0; - bool c10 = C3 + Dx20 * y1 - Dy20 * x0 < 0; - bool c11 = C3 + Dx20 * y1 - Dy20 * x1 < 0; - int c = ((uint32_t)c00 << 0) | ((uint32_t)c10 << 1) | ((uint32_t)c01 << 2) | ((uint32_t)c11 << 3); - - //Skip entire block if all it's 4 corners outside of triangle edges - if (a == 0 || b == 0 || c == 0) - continue; - - auto colorBuffer = bbPtr; - auto zBuffer = dbPtr; - - RegisterBlock var00; - //interpolate registers - for (int r = 1; r < REG_COUNT; r++) { - var00.reg[r] = invRegs[0].reg[r] + triDerivX.reg[r] * (x - ix0) + triDerivY.reg[r] * (y - iy0); - } - - //Whole block is inside triangle! - if (a == 0xf && b == 0xf && c == 0xf) { - for (int by = 0; by < blockSize; by++) { - for (int bx = x; bx < (x + blockSize); bx++) { - //compute interpolation weights - - auto ddx0 = (bx - ix0); - auto ddy0 = (y + by - iy0); - float2 zw = p0zw + derivZW_X * ddx0 + derivZW_Y * ddy0; - - //interpolate Z - float z_interp = zw.x(); - - if (zBuffer[bx] > z_interp) - { - zBuffer[bx] = z_interp; - //interpolate registers - - for (int r = 1; r < REG_COUNT; r++) { - r_ps.reg[r] = (var00.reg[r] + triDerivX.reg[r] * (bx - x)) / zw.y(); - } - - /*for (int r = 1; r < REG_COUNT; r++) { - r_ps.reg[r] = invRegs[0].reg[r] + triDerivX.reg[r] * ddx0 + triDerivY.reg[r] * ddy0; - }*/ - - float4 pixel_color = ps->Execute(&r_ps.reg[0]); - - if (blendState.BlendEnable) { - uint32_t dc = colorBuffer[bx]; - - float4 dstColor = ColorDataAccessor::ConvertColor(dc); - - //get source alpha - float srcAlpha = GetBlendAlpha(blendState.SrcAlpha, pixel_color, dstColor); - float dstAlpha = GetBlendAlpha(blendState.DstAlpha, pixel_color, dstColor); - - pixel_color = pixel_color * srcAlpha + dstColor * dstAlpha; - } - //colorBuffer[bx] += 0x00606060; - colorBuffer[bx] = ColorDataAccessor::ConvertColor(pixel_color); - } - } - colorBuffer += backBuffer->Desc().Width; - zBuffer += depthBuffer->Desc().Width; - - //increment Y variables - for (int r = 1; r < REG_COUNT; r++) { - var00.reg[r] = var00.reg[r] + triDerivY.reg[r]; - } - } - } - else //Partially covered block - { - int CY1 = C1 + Dx01 * y0 - Dy01 * x0; - int CY2 = C2 + Dx12 * y0 - Dy12 * x0; - int CY3 = C3 + Dx20 * y0 - Dy20 * x0; - - for (int by = y; by < (y + blockSize); by++) { - int CX1 = CY1; - int CX2 = CY2; - int CX3 = CY3; - - for (int bx = x; bx < (x + blockSize); bx++) { - if (CX1 < 0 && CX2 < 0 && CX3 < 0) { - auto ddx0 = bx - ix0; - auto ddy0 = (by - iy0); - float2 zw = p0zw + derivZW_X * ddx0 + derivZW_Y * ddy0; - - float z_interp = zw.x(); - - if (zBuffer[bx] > z_interp) { - zBuffer[bx] = z_interp; - //interpolate registers - for (int r = 1; r < REG_COUNT; r++) { - r_ps.reg[r] = invRegs[0].reg[r] + triDerivX.reg[r] * ddx0 + triDerivY.reg[r] * ddy0; - r_ps.reg[r] /= zw.y();//add perspective correction - } - - float4 rst; - rst = ps->Execute(&r_ps.reg[0]); - - //UINT texcolor = ConvertColor(rst); - - if (blendState.BlendEnable) { - uint32_t dc = colorBuffer[bx]; - - float4 dstColor = ColorDataAccessor::ConvertColor(dc); - - float srcAlpha; - float dstAlpha; - - //get source alpha - srcAlpha = GetBlendAlpha(blendState.SrcAlpha, rst, dstColor); - dstAlpha = GetBlendAlpha(blendState.DstAlpha, rst, dstColor); - - rst = rst * srcAlpha + dstColor * dstAlpha; - } - //colorBuffer[bx] += 0x00606060; - colorBuffer[bx] = ColorDataAccessor::ConvertColor(rst); - } - } - - CX1 -= FDy01; - CX2 -= FDy12; - CX3 -= FDy20; - } - CY1 += FDx01; - CY2 += FDx12; - CY3 += FDx20; - - colorBuffer += backBuffer->Desc().Width; - zBuffer += depthBuffer->Desc().Width; - } - } - } - bbPtr += backBuffer->Desc().Width * blockSize; - dbPtr += depthBuffer->Desc().Width * blockSize; - } - } - - std::array r0_in; - std::array r1_in; - std::array r2_in; - - RegisterBlock r0_out; - RegisterBlock r1_out; - RegisterBlock r2_out; - RegisterBlock rA_out; - RegisterBlock rB_out; - RegisterBlock r_ps; - - BlendState blendState; - - IInputLayout* geomLayout; - std::array regMapping; - - struct vertex_buffer_slot{ - Buffer* buffer; - size_t stride; - }; - - std::array vbSlots; - std::array ibSlots; - VertexShader* vs; - PixelShader* ps; - int primitiveType; - - Texture* backBuffer; - Texture* depthBuffer; -}; -#endif // BlockRasterizer_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Buffer.h b/Dependencies/SoftGL/Src/SoftGL/Buffer.h deleted file mode 100644 index f160c3d..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Buffer.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef Buffer_h__ -#define Buffer_h__ - -#include -#include -#include "Debug.h" - -class Buffer { -public: - constexpr Buffer() - { - - } - virtual ~Buffer() = default; - void Write(void* src, size_t offset, size_t length){ - SGL_ASSERT(src != nullptr, "Invalid pointer"); - SGL_ASSERT((offset + length) <= Size(), "Invalid pointer"); - - memcpy((uint8_t*)GetPointer() + offset, src, length); - } - void Read(void* dst, size_t offset, int length){ - memcpy(dst, (uint8_t*)GetPointer() + offset, length); - } - virtual void* GetPointer() = 0; - virtual size_t Size() = 0; - virtual size_t ItemSize() - { - return 1; - } -}; -#endif // Buffer_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Debug.h b/Dependencies/SoftGL/Src/SoftGL/Debug.h deleted file mode 100644 index 0d352f6..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Debug.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef Debug_h__ -#define Debug_h__ - -#include -#include - -#if defined(DEBUG) || defined(_DEBUG) -#define SGL_DEBUG -#define SGL_ASSERT(__expr, __text) assert(__expr && __text); -#else -#define SGL_ASSERT(__expr, __text) -#endif - -#define DebugInfo(...) printf("Info: "); printf(__VA_ARGS__); printf("\n"); -#define DebugError(...) printf("Error: "); printf(__VA_ARGS__); printf("\n"); - -#endif // Debug_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/DisplayMode.h b/Dependencies/SoftGL/Src/SoftGL/DisplayMode.h deleted file mode 100644 index 29965d2..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/DisplayMode.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef DisplayMode_h__ -#define DisplayMode_h__ - -#include - -struct DisplayMode { - uint32_t width; - uint32_t height; - uint32_t refreshRate; - uint32_t bpp; -}; - -#endif // DisplayMode_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/FpsCounter.h b/Dependencies/SoftGL/Src/SoftGL/Engine/FpsCounter.h deleted file mode 100644 index 73b9fce..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/FpsCounter.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once - -#include - - -template -class FpsCounter -{ -public: - - using Clock = std::chrono::steady_clock; - using Duration = std::chrono::steady_clock::duration; - using TimePoint = std::chrono::steady_clock::time_point; - - FpsCounter():position(0),avgFps(0) { - _lastClock = Clock::now(); - timeElapsed = timeElapsed.zero(); - for (size_t i = 0; i < AveragingFramesCount; ++i) { - _buffer[i] = {}; - } - } - ~FpsCounter() - { - - } - void ComputeFPS(){ - auto nowTime = Clock::now(); - timeElapsed = nowTime - _lastClock; - _lastClock = nowTime; - - _buffer[position] = timeElapsed; - position = (position + 1) % AveragingFramesCount; - - Duration sum = {}; - for (size_t i = 0; i < AveragingFramesCount; ++i) { - sum += _buffer[i]; - } - - auto us = std::chrono::duration_cast(sum).count() / AveragingFramesCount; - if (us == 0) { - avgFps = 0.0f; - } else { - avgFps =1.0f / ( (float)us / 1000000.0f); - } - } - float PreciseFPS() { - float time = GetFrameTimeSeconds(); - if (time <= 0.0f) { - return 0.0f; - } - return 1.0f / time; - } - float AverageFPS() - { - return avgFps; - } - float GetFrameTimeSeconds() const { - return (float)std::chrono::duration_cast(timeElapsed).count() / 1000000.0f; - } - Duration GetTimeElapsed() const { - return timeElapsed; - } -private: - TimePoint _lastClock; - Duration timeElapsed; - float avgFps; - Duration _buffer[AveragingFramesCount]; - int position; -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/PsNormalMap.h b/Dependencies/SoftGL/Src/SoftGL/Engine/PsNormalMap.h deleted file mode 100644 index b9efe11..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/PsNormalMap.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include -#include - -class PsNormalMap : public PixelShader { -public: - float3 camPosition; - float4 diffuse; - Texture* diffuse_map; - Texture* normal_map; - Texture* ao_map; - float ior = 1.5f; - float M = 0.7f; - - PsNormalMap() :diffuse_map(nullptr), normal_map(nullptr), diffuse(0) { - - } - float4 Execute(float4* input) { - //return float4(1, 1, 0, 1); - //return float4(input[1].x, input[1].y, 0, 1); - - float3 lightColor = float3(1.0f, 1.0f, 0.9f); - - float3 ambientColor = float3(0.1f, 0.1f, 0.25f); - - float4 normal_tbn = tex2D(normal_map, input[1].x(), input[1].y(), TextureFilter::Bilinear); - auto tmp = normal_tbn.y(); - normal_tbn.y() = normal_tbn.z(); - normal_tbn.z() = tmp; - - float4 ao = tex2D(ao_map, input[1].x(), input[1].y(), TextureFilter::Bilinear); - - //return float4(normal_tbn.x, normal_tbn.y, normal_tbn.z, 1); - - float3 N = lm::normalize(normal_tbn.xyz() * 2.0f - 1.0f); //lm::normalize(input[2].xyz); - - float3 L = lm::normalize(float3(1, 1, 1)); - float3 V = lm::normalize(camPosition - input[3].xyz()); - float3 H = normalize(L + V); - - float NdotL = std::max(0, lm::dot(N, L)); - float NdotV = std::max(0, lm::dot(N, V)); - float LdotH = lm::dot(L, H); - - float F = Fresnel(LdotH, ior); - - float G = G_Cook_Torrance(N, H, V, L); - - float D = D_Beckmann(H, N, M); - - float r_microfacet = (F * G * D) / (4 * NdotL * NdotV + 1.0e-7) * MATH_PI* NdotL; - - float4 diffuse = tex2D(diffuse_map, input[1].x(), input[1].y(), TextureFilter::Bilinear); - - float3 result = float3(0, 0, 0); - result = diffuse.xyz() * (lightColor * diffuse.xyz()) * NdotL + lightColor * r_microfacet + ambientColor * diffuse.xyz() * ao.x(); - - result = lm::saturate(result); - - float4 retval; - retval.xyz() = result; - retval.w() = diffuse.w(); - return retval; - } -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/camera.h b/Dependencies/SoftGL/Src/SoftGL/Engine/camera.h deleted file mode 100644 index 0bc75d1..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/camera.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include -#include "gameobject.h" - -class Camera { -public: - Camera(Game_object* object): - _fov(3.1415f/4.0f), _zNear(0.3f), _zFar(100.0f), _aspect(1.0f), _object(object){ - UpdateProjection(); - } - - lm::float4x4 world_to_camera_matrix(){ - auto tf = _object->transform.get_global_transform(); - return lm::inverse(tf, false); - } - Game_object* GameObject() - { - return _object; - } - float4x4 GetProjection() const{ - return _projection; - } - float GetFov() const{ - return _fov; - } - void SetFov(float fov) { - _fov = fov; - UpdateProjection(); - } - float GetAspect() const { - return _aspect; - } - void SetAspect(float aspect) { - _aspect = aspect; - UpdateProjection(); - } - float GetZNear() const { - return _zNear; - } - void SetZNear(float zNear) { - _zNear = zNear; - UpdateProjection(); - } - float GetZFar() const { - return _zFar; - } - void SetZFar(float zFar) { - _zFar = zFar; - UpdateProjection(); - } -private: - void UpdateProjection(){ - _projection = lm::matrix4x4Perspective(_fov, _aspect, _zNear, _zFar); - } - float _fov; - float _zNear; - float _zFar; - float _aspect; - float4x4 _projection; - Game_object* _object; -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/camera_controller.h b/Dependencies/SoftGL/Src/SoftGL/Engine/camera_controller.h deleted file mode 100644 index 10c6651..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/camera_controller.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include "camera.h" -#include -#include - -class CameraController{ -public: - float mouse_speed; - float move_speed = 3.0f; - static constexpr float pi = 3.14159265358979f; - - CameraController(Camera* camera) : mouse_speed(0.01f), _camera(camera) { - _angle_x = _angle_y = 0.0f; - } - - void Tick(float deltaTime) { - auto mice = Input::Instance()->mice(); - auto mouse = mice[1]; - - if(mouse->GetKeyState(1)){ - _angle_x += mouse_speed * mouse->GetDx(); - _angle_y += mouse_speed * mouse->GetDy(); - _angle_y = clamp(_angle_y, -pi / 2.0f, pi / 2.0f); - auto rv = lm::Quaternion_f::angleAxis(_angle_y, lm::float3(1, 0, 0)); - auto rh = lm::Quaternion_f::angleAxis(_angle_x, lm::float3(0, 1, 0)); - _camera->GameObject()->transform.set_local_rotation(lm::mul(rh, rv)); - } - - auto keyboard = Input::Instance()->keyboards()[3]; - auto& tf = _camera->GameObject()->transform; - - if (keyboard->GetKeyState(0x57)) { - tf.SetLocalPosition(tf.GetLocalPosition() + tf.Forward() * (deltaTime * move_speed)); - } - - if (keyboard->GetKeyState(0x53)) { - tf.SetLocalPosition(tf.GetLocalPosition() - tf.Forward() * (deltaTime * move_speed)); - } - - if (keyboard->GetKeyState(0x41)) { - tf.SetLocalPosition(tf.GetLocalPosition() - tf.right() * (deltaTime * move_speed)); - } - - if (keyboard->GetKeyState(0x44)) { - tf.SetLocalPosition(tf.GetLocalPosition() + tf.right() * (deltaTime * move_speed)); - } - } -private: - Camera* _camera; - float _angle_x; - float _angle_y; -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/cube_generator.h b/Dependencies/SoftGL/Src/SoftGL/Engine/cube_generator.h deleted file mode 100644 index 8157ac4..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/cube_generator.h +++ /dev/null @@ -1,91 +0,0 @@ -#pragma once - -#include "imesh.h" -#include - -#include - -using namespace lm; - -template -struct CubeGenerator { - static constexpr size_t VertexCount = 24; - static constexpr size_t IndexCount = 36; - - static constexpr float4 Corner(size_t id) { - return float4(id % 2 == 0 ? -1.0f : 1.0f, id < 4 ? 1.0f : -1.0f, (id % 4) < 2 ? 1.0f : -1.0f, 1.0f); - } - - static bool Generate(IMesh* m) { - if (m == nullptr) { - return false; - } - - auto vb = m->GetVertexBuffer(); - if (vb == nullptr || (vb->Size() / vb->ItemSize()) < VertexCount) { - return false; - } - - auto ib = m->GetSubmeshBuffer(0); - if (ib == nullptr || (ib->Size() / ib->ItemSize()) < IndexCount) { - return false; - } - - static constexpr float extent = 0.5f; - - - // 0-1 - //2-3 - // - // 4-5 - //6-7 - - static constexpr std::array sides[6] = { - { 3,1,5,7 }, - { 0,2,6,4 }, - { 0,1,3,2 }, - { 6,7,5,4 }, - { 1,0,4,5 }, - { 2,3,7,6 } - }; - - static constexpr std::array normals = { - float3(1.0f,0.0f,0.0f), - float3(-1.0f,0.0f,0.0f), - float3(0.0f,1.0f,0.0f), - float3(0.0f,-1.0f,0.0f), - float3(0.0f,0.0f,1.0f), - float3(0.0f,0.0f,-1.0f) - }; - - static constexpr float2 uvs[4] = { - float2(0.0f,0.0f), - float2(1.0f,0.0f), - float2(1.0f,1.0f), - float2(0.0f,1.0f) - }; - - static constexpr size_t indexMap[6] = { - 0,1,3,3,1,2 - }; - - auto vertices = (TVertex*)vb->GetPointer(); - auto indices = (TIndex*)ib->GetPointer(); - - for(size_t i = 0; i < 6; ++i){ - //update vertices - for (size_t j = 0; j < 4; ++j) { - auto& vertex = vertices[i * 4 + j]; - vertex.Position = Corner(sides[i][j]); - vertex.Normal = normals[i]; - vertex.UV0 = uvs[j]; - } - auto indexBase = i * 4; - for (size_t j = 0; j < 6; ++j) { - indices[i * 6 + j] = indexBase + indexMap[j]; - } - } - - return true; - } -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/fresnel.h b/Dependencies/SoftGL/Src/SoftGL/Engine/fresnel.h deleted file mode 100644 index c317549..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/fresnel.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef fresnel_h__ -#define fresnel_h__ - -#include - -inline float Fresnel(float c, float ior) { - float g = std::sqrt(ior*ior + c*c - 1); - return 0.5f * std::pow(g - c, 2) / std::pow(g + c, 2) * (1 + std::pow(c*(g + c) - 1, 2) / std::pow(c*(g - c) + 1, 2)); -} -#endif // fresnel_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/gameobject.h b/Dependencies/SoftGL/Src/SoftGL/Engine/gameobject.h deleted file mode 100644 index a4d12c0..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/gameobject.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef gameobject_h__ -#define gameobject_h__ - -#include "transform.h" - -class Game_object { -public: - Transform transform; - Game_object():transform(this) - { - - } -}; -#endif // gameobject_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/imesh.h b/Dependencies/SoftGL/Src/SoftGL/Engine/imesh.h deleted file mode 100644 index 343cfd1..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/imesh.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include -#include - -class IMesh { -public: - virtual Buffer* GetVertexBuffer() = 0; - virtual size_t GetSubmeshCount() const = 0; - virtual Buffer* GetSubmeshBuffer(size_t id) const = 0; -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/mesh.h b/Dependencies/SoftGL/Src/SoftGL/Engine/mesh.h deleted file mode 100644 index 6cb7360..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/mesh.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef mesh_h__ -#define mesh_h__ - -#include "imesh.h" -#include - -template -class Mesh : public IMesh { -public: - Buffer* vertexBuffer; - std::array submeshes; - - virtual Buffer* GetVertexBuffer() override { - return vertexBuffer; - } - - virtual size_t GetSubmeshCount() const override { - return SubmeshCount; - } - - virtual Buffer* GetSubmeshBuffer(size_t id) const override { - return submeshes[id]; - } - -}; - - - -#endif // mesh_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/plane_generator.h b/Dependencies/SoftGL/Src/SoftGL/Engine/plane_generator.h deleted file mode 100644 index 8a286cc..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/plane_generator.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include "imesh.h" -#include - -using namespace lm; - -template -struct PlaneGenerator { - static constexpr size_t VertexCount = 4; - static constexpr size_t IndexCount = 6; - - static constexpr float4 Corner(size_t id) { - return float4(id % 2 == 0 ? -1.0f : 1.0f, 0.0f, (id % 4) < 2 ? 1.0f : -1.0f, 1.0f); - } - - static bool Generate(IMesh* m) { - if (m == nullptr) { - return false; - } - - auto vb = m->GetVertexBuffer(); - if (vb == nullptr || (vb->Size() / vb->ItemSize()) < VertexCount) { - return false; - } - - auto ib = m->GetSubmeshBuffer(0); - if (ib == nullptr || (ib->Size() / ib->ItemSize()) < IndexCount) { - return false; - } - - static constexpr std::array normals = { - float3(1.0f,0.0f,0.0f), - float3(-1.0f,0.0f,0.0f), - float3(0.0f,1.0f,0.0f), - float3(0.0f,-1.0f,0.0f), - float3(0.0f,0.0f,1.0f), - float3(0.0f,0.0f,-1.0f) - }; - - static constexpr float2 uvs[4] = { - float2(0.0f, 0.0f), - float2(1.0f, 0.0f), - float2(0.0f, 1.0f), - float2(1.0f, 1.0f) - }; - - static constexpr size_t planeIndices[6] = { - 0,1,2,2,1,3 - }; - - auto vertices = (TVertex*)vb->GetPointer(); - auto indices = (TIndex*)ib->GetPointer(); - - //update vertices - for (size_t j = 0; j < 4; ++j) { - auto& vertex = vertices[j]; - vertex.Position = Corner(j); - vertex.Normal = float3(0.0f, 1.0f, 0.0f); - vertex.UV0 = uvs[j]; - } - - for (size_t j = 0; j < 6; ++j) { - indices[j] = planeIndices[j]; - } - - - return true; - } -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/shaders/textured_no_lit.h b/Dependencies/SoftGL/Src/SoftGL/Engine/shaders/textured_no_lit.h deleted file mode 100644 index eae8fe4..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/shaders/textured_no_lit.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include - -class PSTexturedNoLit : public PixelShader { -public: - Texture* diffuseMap; - - PSTexturedNoLit() :diffuseMap(nullptr) {} - - float4 Execute(float4* input) { - float4 diffuse = float4(0, 0, 0, 0); - if (diffuseMap != nullptr) { - diffuse = tex2D(diffuseMap, input[1].x(), input[1].y(), TextureFilter::Bilinear); - } - return diffuse; - } -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Engine/transform.h b/Dependencies/SoftGL/Src/SoftGL/Engine/transform.h deleted file mode 100644 index bf96e86..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Engine/transform.h +++ /dev/null @@ -1,84 +0,0 @@ -#pragma once - -#include - -using namespace lm; - -class Game_object; - -class Transform { -public: - Transform* parent; - lm::Quaternion_f _rotation; - float3 _position; - float3 _scale; - - Transform(Game_object* game_object) - :parent(nullptr), _scale(1, 1, 1), _position(0, 0, 0), _rotation(0, 0, 0, 1), _game_object(game_object) { - - } - - std::wstring class_name() const { - return L"Transform"; - } - - void SetLocalPosition(const float3& position) { - _position = position; - } - float3 GetLocalPosition() { - return _position; - } - - float3 Forward() const { - return get_global_transform()[2].xyz(); - } - - float3 right() const { - return get_global_transform()[0].xyz(); - } - - float3 up() const { - return get_global_transform()[1].xyz(); - } - - void set_local_rotation(const Quaternion_f& rotation) { - _rotation = rotation; - } - - Quaternion_f get_local_rotation() { - return _rotation; - } - - void set_local_scale(const float3& scale) { - _scale = scale; - } - - float3 get_local_scale() { - return _scale; - } - - float4x4 get_local_transform() const { - float4x4 scaleMatrix = matrix4x4Scale(_scale); - float4x4 rotationMatrix = matrix4x4RotationQuaternion(_rotation); - float4x4 positionMatrix = matrix4x4Translation(_position); - return lm::mul(lm::mul(scaleMatrix, rotationMatrix), positionMatrix); - } - - float4x4 get_global_transform() const { - if (parent == nullptr) { - return get_local_transform(); - } - return lm::mul(get_local_transform(), parent->get_global_transform()); - } - - float3 get_global_position() { - auto tf = get_global_transform(); - return float3(tf[3][0], tf[3][1], tf[3][2]); - } - - void RotateLocal(const Quaternion_f& rotation) { - _rotation = lm::mul(_rotation, rotation); - } -private: - Game_object* _game_object; -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Graphics2D.h b/Dependencies/SoftGL/Src/SoftGL/Graphics2D.h deleted file mode 100644 index 7482745..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Graphics2D.h +++ /dev/null @@ -1,108 +0,0 @@ -#ifndef Graphics2D_h__ -#define Graphics2D_h__ - -#include "Texture.h" - - -struct TextureWriter { - Texture* texture; - - size_t width() { - return texture->Desc().Width; - } - size_t height() { - return texture->Desc().Height; - } - template - void setPixel(int32_t x, int32_t y, Color color) { - if (x < 0 || y < 0) { - return; - } - if (x >= (int64_t)width() || y >= (int64_t)height()) { - return; - } - uint8_t* data = ((uint8_t*)texture->LockWrite()) + (y * width() + x) * sizeof(color); - memcpy(data, &color, sizeof(color)); - - } -}; - -template -void clear(PixelWriter& writer, const Color& color) { - for (size_t y = 0; y < writer.height(); ++y) { - for (size_t x = 0; x < writer.width(); ++x) { - writer.setPixel(x, y, color); - } - } -} - -template -void drawCircle(int X1, int Y1, int R, PixelWriter& writer, const Color& color) { - int x = 0; - int y = R; - int delta = 1 - 2 * R; - int error = 0; - while (y >= 0) { - writer.setPixel(X1 + x, Y1 + y, color); - writer.setPixel(X1 + x, Y1 - y, color); - writer.setPixel(X1 - x, Y1 + y, color); - writer.setPixel(X1 - x, Y1 - y, color); - error = 2 * (delta + y) - 1; - if ((delta < 0) && (error <= 0)) { - delta += 2 * ++x + 1; - continue; - } - error = 2 * (delta - x) - 1; - if ((delta > 0) && (error > 0)) { - delta += 1 - 2 * --y; - continue; - } - x++; - delta += 2 * (x - y); - y--; - } -} - -template -void drawLine(int32_t x0, int32_t y0, int32_t x1, int32_t y1, PixelWriter& writer, const Color& color) { - int32_t steep = abs(y1 - y0) > abs(x1 - x0); - if (steep) { - std::swap(x0, y0); - std::swap(x1, y1); - } - - if (x0 > x1) { - std::swap(x0, x1); - std::swap(y0, y1); - } - - int32_t dx = x1 - x0; - int32_t dy = abs(y1 - y0); - - auto err = dx / 2; - int32_t ystep; - - if (y0 < y1) { - ystep = 1; - } - else { - ystep = -1; - } - - for (; x0 <= x1; x0++) { - if (steep) { - writer.setPixel(y0, x0, color); - } - else { - writer.setPixel(x0, y0, color); - } - err -= dy; - if (err < 0) { - y0 += ystep; - err += dx; - } - } -} - - -#endif // Graphics2D_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/IRenderWindow.h b/Dependencies/SoftGL/Src/SoftGL/IRenderWindow.h deleted file mode 100644 index 4eccf7a..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/IRenderWindow.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include "LString.h" -#include "DisplayMode.h" -#include -#include -#include "Texture.h" - -class IRenderWindow{ -public: - virtual ~IRenderWindow(void) {} - virtual void Update() = 0; - virtual void SetCaption(const String& caption) = 0; - virtual std::size_t GetWindowHandle() = 0; - virtual int GetWidth() = 0; - virtual int GetHeight() = 0; - virtual int GetTop() = 0; - virtual int GetLeft() = 0; - virtual void SetPosition(int top, int left) = 0; - virtual void SetSize(int w, int h) = 0; - virtual const String& GetCaption() = 0; - - virtual bool IsFullScreen() = 0; - virtual void SetFullScreen(bool state) = 0; - virtual bool SwitchMode(bool fullscreen) = 0; - virtual void SetFullscreenMode(DisplayMode mode) = 0; - - virtual const DisplayMode& GetFullscreenMode() - { - return fsMode; - } - virtual void Present(Texture* tex) = 0; - - virtual void OnActivate() = 0; - virtual void OnDeactivate() = 0; - virtual void OnResize() = 0; - virtual bool IsActive() = 0; - virtual bool IsModeSwitching() = 0; - virtual void SetCursorVisible(bool state) = 0; - virtual bool IsCursorVisible() = 0; - virtual void CenterWindow() = 0; -protected: - bool bCursorVisible; - bool bModeSwitching; - bool bFullscreen; - bool bActive; - int width; - int height; - String caption; - DisplayMode fsMode; -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/IShader.h b/Dependencies/SoftGL/Src/SoftGL/IShader.h deleted file mode 100644 index f557676..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/IShader.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef IShader_h__ -#define IShader_h__ - -#include "LString.h" -#include -#include - -using namespace lm; -using namespace std; - -class IShader -{ -protected: - typedef std::vector RegisterList; - RegisterList inputs; - -public: - int RegisterCount() - { - return inputs.size(); - } - int FindRegister(const String& name) - { - int cnt = inputs.size(); - if(!cnt) return -1; - - RegisterList::iterator it = inputs.begin(); - for(int i = 0; i < cnt; i++) - { - if((*it) == name) return i; - it++; - } - return -1; - } - - IShader() - { - - } - virtual ~IShader() - { - - } -}; -#endif // IShader_h__ \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/ImageDataAccessorR5G6B5.h b/Dependencies/SoftGL/Src/SoftGL/ImageDataAccessorR5G6B5.h deleted file mode 100644 index 345aaa3..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/ImageDataAccessorR5G6B5.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include -#include - -class ImageDataAccessorR5G6B5 { -public: - - using PixelDataType = std::uint16_t; - static constexpr bool HasAlpha = true; - - static PixelDataType ConvertColor(const lm::float4& color) { - PixelDataType r = (uint32_t)(color.x() * 0x1f); - PixelDataType g = (uint32_t)(color.y() * 0x3f); - PixelDataType b = (uint32_t)(color.z() * 0x1f); - - return (r << 11) | (g << 5) | (b); - } - - static lm::float4 ConvertColor(PixelDataType color) { - float r = (float)(color >> 11) / 0x1f; - float g = (float)((color >> 5) & 0x3f) / 0x3f; - float b = (float)((color >> 0) & 0x1f) / 0x1f; - return lm::float4(r, g, b, 1.0f); - } -}; \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/ImageDataAccessorR8G8B8.h b/Dependencies/SoftGL/Src/SoftGL/ImageDataAccessorR8G8B8.h deleted file mode 100644 index 040f662..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/ImageDataAccessorR8G8B8.h +++ /dev/null @@ -1,31 +0,0 @@ - -#pragma once - -#include -#include - -class ImageDataAccessorR8G8B8 { -public: - - using PixelDataType = std::uint32_t; - static constexpr bool HasAlpha = true; - - static uint32_t ConvertColor(const lm::float4& color) { - uint32_t r = (uint32_t)(color.x() * 255.0f); - uint32_t g = (uint32_t)(color.y() * 255.0f); - uint32_t b = (uint32_t)(color.z() * 255.0f); - uint32_t a = (uint32_t)(color.w() * 255.0f); - - return (a << 24) | (r << 16) | (g << 8) | (b); - } - - static lm::float4 ConvertColor(uint32_t color) { - float d = 1.0f / 255.0f; - - float a = (float)((color >> 24) & 0xff) * d; - float r = (float)((color >> 16) & 0xff) * d; - float g = (float)((color >> 8) & 0xff) * d; - float b = (float)((color >> 0) & 0xff) * d; - return lm::float4(r, g, b, a); - } -}; \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/IndexBuffer.h b/Dependencies/SoftGL/Src/SoftGL/IndexBuffer.h deleted file mode 100644 index 2f21b39..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/IndexBuffer.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef IndexBuffer_h__ -#define IndexBuffer_h__ - - - -#endif // IndexBuffer_h__ \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/InputLayout.h b/Dependencies/SoftGL/Src/SoftGL/InputLayout.h deleted file mode 100644 index 4ca0753..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/InputLayout.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef InputLayout_h__ -#define InputLayout_h__ - -#include "LString.h" -#include "RasterizerSettings.h" -#include "Debug.h" -#include - -enum class RegType { - float1 = 0, - float2 = 1, - float3 = 2, - float4 = 3 -}; - -struct InputElement { - char name[InputElementNameLength]; - uint8_t Offset; - RegType type; - uint8_t StreamId; - - InputElement() :name{0}, Offset(0), type(RegType::float1), StreamId(0){ - - } - InputElement(const char* _name, uint8_t offset, RegType t, uint8_t stream) { - SGL_ASSERT(strlen(_name) < InputElementNameLength, "Too long name for InputElement"); - strcpy(name, _name); - Offset = offset; - type = t; - StreamId = stream; - } -}; - -class IInputLayout { -public: - virtual size_t Size() = 0; - virtual InputElement* GetElement(size_t id) = 0; - int FindElement(const char* name) { - auto size = Size(); - for (size_t i = 0; i < size; i++) { - if (strcmp(GetElement(i)->name, name) == 0) - return i; - } - return -1; - } -}; - -template -class StaticInputLayout : public IInputLayout { -public: - std::array elements; - virtual size_t Size() override { - return _Size; - } - virtual InputElement* GetElement(size_t id) override { - return &elements[id]; - } -}; -#endif // InputLayout_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/InputSystem.h b/Dependencies/SoftGL/Src/SoftGL/InputSystem.h deleted file mode 100644 index a6e8d02..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/InputSystem.h +++ /dev/null @@ -1,109 +0,0 @@ -#ifndef InputSystem_h__ -#define InputSystem_h__ - -#include -#include -#include "RenderWindow.h" -#include "Delegate.h" - -#ifdef _DEBUG -#pragma comment (lib, "OIS_static_d.lib") -#else -#pragma comment (lib, "OIS_static.lib") -#endif - -using namespace OIS; - -class InputSystem : public OIS::KeyListener, public OIS::MouseListener -{ -public: - EVENT1(KBEvent, int); - KBEvent Event_KeyDown; - KBEvent Event_KeyUp; - - EVENT4(MSEvent, int, int, int, int); - MSEvent Event_MouseMove; - - InputSystem(RenderWindow* window, int sw, int sh) - { - //init Input - ParamList pl; - - HWND hw = (HWND)window->GetWindowHandle(); - std::ostringstream wnd; - wnd << (size_t)hw; - pl.insert(std::make_pair( std::string("WINDOW"), wnd.str() )); - - bool hideCursor = false; - - if( !hideCursor) - { - pl.insert(std::make_pair(std::string("w32_mouse") , std::string("DISCL_BACKGROUND" ))); - - pl.insert(std::make_pair(std::string("w32_mouse") , std::string("DISCL_NONEXCLUSIVE"))); - } - pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_BACKGROUND"))); - - pl.insert(std::make_pair(std::string("w32_keyboard"), std::string ("DISCL_NONEXCLUSIVE") )); - - - - - input = InputManager::createInputSystem(pl); - keyboard = (Keyboard*)input->createInputObject(OISKeyboard,1); - mouse = (Mouse*)input->createInputObject(OISMouse,1); - mouse->getMouseState().width = sw; - mouse->getMouseState().height = sh; - - keyboard->setEventCallback(this); - mouse->setEventCallback(this); - } - ~InputSystem() - { - input->destroyInputObject(mouse); - input->destroyInputObject(keyboard); - InputManager::destroyInputSystem(input); - } - void Capture() - { - mouse->capture(); - keyboard->capture(); - } - - bool keyPressed(const KeyEvent &arg) - { - Event_KeyDown.Invoke((int)arg.key); - return true; - } - bool keyReleased(const KeyEvent &arg) - { - Event_KeyUp.Invoke((int)arg.key); - return true; - } - - bool mouseMoved( const MouseEvent &arg ) - { - Event_MouseMove.Invoke(arg.state.X.abs, arg.state.Y.abs, arg.state.X.rel, arg.state.Y.rel); - return true; - } - bool mousePressed( const MouseEvent &arg, MouseButtonID id ) - { - return true; - } - bool mouseReleased( const MouseEvent &arg, MouseButtonID id ) - { - - return true; - } - void SetKeyDownCallback() - { - - } - -private: - InputManager* input; - Keyboard* keyboard; - Mouse* mouse; - -}; -#endif // InputSystem_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/LString.h b/Dependencies/SoftGL/Src/SoftGL/LString.h deleted file mode 100644 index f151c73..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/LString.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef LSTRING_H__ -#define LSTRING_H__ -#include - -#ifdef _UNICODE -#define _text(str) L##str -typedef std::wstring String; -#define PRINT wprintf -#define STRCMP wcscmp -typedef wchar_t tchar; -#define string_size(str) (str.length() * 2) -#else -#define _text(str) str -#define PRINT printf -typedef std::string String; -typedef char tchar; -#define STRCMP strcmp -#define string_size(str) (str.length()) -#endif - -#ifdef WIN32 -#define PATH_SPLITTER _text("\\") -#else -#define PATH_SPLITTER _text("/") -#endif - -extern String GetFileName(const String& path); - -extern String GetFileName(const String& path, const String& pathSplitter); - -extern String GetFileNameWithoutExtention(const String& path); - -extern String GetFilePath(const String& path, const String& pathSplitter); - -extern void GetRootFolderS(const String& path, String& folderName, String& resultPath); - -extern void GetRootFolderS(const String& path, String& folderName); - -extern String GetDirectoryName(const String& path); - -#define AS_STRING(omg) String(omg) -#define STR(omg) String(omg) - -#endif diff --git a/Dependencies/SoftGL/Src/SoftGL/PSDefault.h b/Dependencies/SoftGL/Src/SoftGL/PSDefault.h deleted file mode 100644 index b599c21..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/PSDefault.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef PSDefault_h__ -#define PSDefault_h__ - -#include "PixelShader.h" -#include - -class PSDefault : public PixelShader -{ -public: - float3 camPosition; - float4 diffuse; - Texture* diffuse_map; - float ior = 1.5f; - float M = 0.7f; - - PSDefault():diffuse_map(nullptr), diffuse(0){ - - } - float4 Execute(float4* input) { - using namespace lm; - - //return float4(1, 1, 0, 1); - //return float4(input[1].x, input[1].y, 0, 1); - - float3 lightColor = float3(1.0f, 1.0f, 0.9f); - - float3 ambientColor = float3(0.1f, 0.1f, 0.2f); - - float3 N = lm::normalize(input[2].xyz()); - float3 L = lm::normalize(float3(1, 1, 1)); - float3 V = lm::normalize(camPosition - input[3].xyz()); - float3 H = normalize(L + V); - - float NdotL = std::max(0, lm::dot(N, L)); - float NdotV = std::max(0, lm::dot(N, V)); - float LdotH = lm::dot(L, H); - - float F = Fresnel(LdotH, ior); - - float G = G_Cook_Torrance(N, H, V, L); - - float D = D_Beckmann(H, N, M); - - float r_microfacet = (F * G * D) / (4 * NdotL * NdotV + 1.0e-7) * MATH_PI* NdotL; - - float4 diffuse = float4(0, 0, 0, 0); - if (diffuse_map != nullptr) { - diffuse = tex2D(diffuse_map, input[1].x(), input[1].y(), TextureFilter::Bilinear); - }; - - - - - float3 result = float3(0, 0, 0); - result = diffuse.xyz() * (lightColor * diffuse.xyz()) * NdotL + lightColor * r_microfacet + ambientColor * diffuse.xyz(); - - result = lm::saturate(result); - - float4 retval; - retval.xyz() = result; - retval.w() = diffuse.w(); - return retval; - } -}; -#endif // PSDefault_h__ \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/PSDefaultColor.h b/Dependencies/SoftGL/Src/SoftGL/PSDefaultColor.h deleted file mode 100644 index e2784c7..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/PSDefaultColor.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include "PixelShader.h" -#include - -class PSDefaultColor : public PixelShader -{ -public: - float4 diffuse; - - PSDefaultColor(): diffuse(1.0f, 1.0f, 1.0f, 1.0f){ - - } - float4 Execute(float4* input) { - return diffuse; - } -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/PSFont.h b/Dependencies/SoftGL/Src/SoftGL/PSFont.h deleted file mode 100644 index ac97884..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/PSFont.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef PSFont_h__ -#define PSFont_h__ - -#include "PixelShader.h" - -class PSFont : public PixelShader -{ -public: - float appTime; - float4 diffuse; - Texture2D* diffuseTex; - - PSFont() - { - - } - float4 Execute(float4* input) - { - float4 out; - - tex2D(diffuseTex, &out, input[1].X, input[1].Y); - - out = float4(1,1,1,1) - out; - out.W = out.X; - return out; - } -}; -#endif // PSFont_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/PSTextured.h b/Dependencies/SoftGL/Src/SoftGL/PSTextured.h deleted file mode 100644 index 8adcb31..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/PSTextured.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef PSTextured_h__ -#define PSTextured_h__ - -#include "PixelShader.h" - -class PSTextured : public PixelShader -{ -public: - float appTime; - float4 diffuse; - Texture2D* diffuseTex; - - PSTextured() - { - - } - float4 Execute(float4* input) - { - /* float f = (sinf(appTime * 4.0f) * 0.5f + 0.5f); - float4 color = diffuse * (sinf((input[0].Y / 2.0f)) * 0.5f + 0.5f)* (cosf((input[0].X / 2.0f)) * 0.5f * f + 0.5f); - color.W = 0.6f;*/ - //return color; - //return diffuse; - float4 out; - sample2D(diffuseTex, &out, input[1].X, input[1].Y); - - //out = float4(1,1,1,1) - out; - out.W = 0.5f; - //return float4(1,1,1,1); - return out; - - - - //return float4(1,1,0,1); - } -}; -#endif // PSTextured_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/PixelShader.h b/Dependencies/SoftGL/Src/SoftGL/PixelShader.h deleted file mode 100644 index 202afbd..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/PixelShader.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef PixelShader_h__ -#define PixelShader_h__ - -#include "IShader.h" -#include "Texture.h" -#include -#include - -using namespace lm; - -enum class TextureFilter { - Point, - Bilinear, - Trilinear, - Anisotropic -}; - -#define CLIP -1231345391 -class PixelShader : public IShader { -public: - virtual ~PixelShader() { - - } - virtual float4 Execute(float4* input) = 0; - float4 tex2D(Texture* tex, float tx, float ty, TextureFilter filter) { - if (tex == nullptr) { - return float4(0, 0, 0, 0); - } - auto width = tex->Desc().Width; - auto height = tex->Desc().Height; - auto bpp = tex->Desc().BytesPerPixel; - - auto tw = (float)(width - 1); - auto th = (float)(height - 1); - - auto mips = tex->LockRead(); - - if (tx > 1.0f) { - tx = 1.0f; - } - if (tx < 0.0f) { - tx = 0.0f; - } - if (ty > 1.0f) { - ty = 1.0f; - } - if (ty < 0.0f) { - ty = 0.0f; - } - if (filter == TextureFilter::Bilinear) { - float x = (tx * tw); - float y = (ty * th); - int px = (int)x; - int py = (int)y; - - float fx = x - px; - float fy = y - py; - float fx1 = 1.0f - fx; - float fy1 = 1.0f - fy; - - int w1 = (int)(fx1 * fy1 * 256.0f); - int w2 = (int)(fx * fy1 * 256.0f); - int w3 = (int)(fx1 * fy * 256.0f); - int w4 = (int)(fx * fy * 256.0f); - - auto mem = reinterpret_cast(mips); - - auto p1 = mem + ((py + 0)*width + (px + 0))* bpp; - auto p2 = mem + ((py + 0)*width + (px + 1))* bpp; - auto p3 = mem + ((py + 1)*width + (px + 0))* bpp; - auto p4 = mem + ((py + 1)*width + (px + 1))* bpp; - - int outr = p1[0] * w1 + p2[0] * w2 + p3[0] * w3 + p4[0] * w4; - int outg = p1[1] * w1 + p2[1] * w2 + p3[1] * w3 + p4[1] * w4; - int outb = p1[2] * w1 + p2[2] * w2 + p3[2] * w3 + p4[2] * w4; - - return float4( - ((float)(outr >> 8)) / 255.0f, - ((float)(outg >> 8)) / 255.0f, - ((float)(outb >> 8)) / 255.0f, - 1.0f); - - } else { - tx += 0.5f / tw; - ty += 0.5f / th; - int x = (int)(tx * tw); - int y = (int)(ty * th); - auto ptr = reinterpret_cast(mips); - ptr += (y*width + x)* bpp; - return float4( - ((float)ptr[0]) / 255.0f, - ((float)ptr[1]) / 255.0f, - ((float)ptr[2]) / 255.0f, - 1.0f); - } - } -}; -#endif // PixelShader_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Platform/Linux/RenderWindowXORG.cpp b/Dependencies/SoftGL/Src/SoftGL/Platform/Linux/RenderWindowXORG.cpp deleted file mode 100644 index 41461b5..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Platform/Linux/RenderWindowXORG.cpp +++ /dev/null @@ -1,202 +0,0 @@ -#include "RenderWindowXORG.h" - -#if defined(LINUX) -#include -#include - - -RenderWindowXORG::RenderWindowXORG(uint16 width, uint16 height) - :img(0) -{ - display_name = XOpenDisplay(NULL); - screen = DefaultScreen(display_name); - depth = DefaultDepth(display_name,screen); - connection = ConnectionNumber(display_name); - - visual = DefaultVisual(display_name, 0); - - - if(depth == 1) - printf("You live in prehistoric times\n"); - else - printf("You've got a coloured monitor with depth of %d\n",depth); - - rootwindow = RootWindow(display_name,screen); - - window = XCreateSimpleWindow(display_name, rootwindow, - 0, 0, width, height, 1, 0, 0); - - gc = XCreateGC(display_name, window, 0, NULL); - - XMapWindow(display_name, window); - XFlush(display_name); - XSynchronize(display_name, 1); -} - -int RenderWindowXORG::GetTop() -{ - XWindowAttributes xwa; - XGetWindowAttributes(display_name, window, &xwa); - return xwa.y; -} - -int RenderWindowXORG::GetLeft() -{ - XWindowAttributes xwa; - XFlush(display_name); - XGetWindowAttributes(display_name, window, &xwa); - return xwa.x; -} - -void RenderWindowXORG::SetPosition(int top, int left) -{ - XMoveWindow(display_name, window, top, left); - XSync(display_name, 1); - XFlush(display_name); - XSynchronize(display_name, 1); -} - - -void RenderWindowXORG::Update() -{ - -} - -void RenderWindowXORG::SetCaption(const String& caption) -{ - XStoreName(display_name, window, caption.c_str()); - XFlush(display_name); -} - -int RenderWindowXORG::GetWindowHandle() -{ - return -1; -} - -int RenderWindowXORG::GetWidth() -{ - XWindowAttributes xwa; - XGetWindowAttributes(display_name, window, &xwa); - return xwa.width; -} - -int RenderWindowXORG::GetHeight() -{ - XWindowAttributes xwa; - XGetWindowAttributes(display_name, window, &xwa); - return xwa.height; -} - -void RenderWindowXORG::SetSize(int w, int h) -{ - XResizeWindow(display_name, window, w, h); - XFlush(display_name); - XSync(display_name, 1); -} - -const String& RenderWindowXORG::GetCaption() -{ - return String("Not yet implemented"); -} - -bool RenderWindowXORG::IsFullScreen() -{ - return false; -} - -void RenderWindowXORG::SetFullScreen(bool state) -{ - -} - -bool RenderWindowXORG::SwitchMode(bool fullscreen) -{ - -} - -void RenderWindowXORG::SetFullscreenMode(DisplayMode mode) -{ - -} - -void RenderWindowXORG::Present(Texture2D* tex) -{ - - // char buf[256]; - - - - - if(img == 0) - { - // SetCaption("Create image!"); - img = XCreateImage(display_name, visual, 24, ZPixmap, 0, (char *)tex->getBuffer()->getDataPtr(), tex->width, tex->height, 32, 0); - } - - - XPutImage(display_name, window, gc, img, 0, 0, 0, 0, tex->width, tex->height); - XFlushGC(display_name, gc); - XFlush(display_name); - XSync(display_name, true); - - - - // sprintf(buf, "Data ptr = 0x%x", img->data); - - // SetCaption(String(buf)); - - // img->data = NULL; - // XDestroyImage(img); - - -} - -void RenderWindowXORG::OnActivate() -{ - -} - -void RenderWindowXORG::OnDeactivate() -{ - -} - -void RenderWindowXORG::OnResize() -{ - -} - -bool RenderWindowXORG::IsActive() -{ - return true; -} - -bool RenderWindowXORG::IsModeSwitching() -{ - return false; -} - -void RenderWindowXORG::SetCursorVisible(bool state) -{ - -} - -bool RenderWindowXORG::IsCursorVisible() -{ - return true; -} - -void RenderWindowXORG::CenterWindow() -{ - int dw = DisplayWidth(display_name,screen); - int dh = DisplayHeight(display_name,screen); - - int ww = GetWidth(); - int wh = GetHeight(); - int px = (dw - ww) / 2; - int py = (dh - wh) / 2; - - SetPosition(px, py); - XFlush(display_name); -} -#endif diff --git a/Dependencies/SoftGL/Src/SoftGL/Platform/Linux/RenderWindowXORG.h b/Dependencies/SoftGL/Src/SoftGL/Platform/Linux/RenderWindowXORG.h deleted file mode 100644 index d155006..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Platform/Linux/RenderWindowXORG.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef RENDERWINDOWXORG_H -#define RENDERWINDOWXORG_H - -#if defined(LINUX) - -#include "IRenderWindow.h" -#include -#include -#include - -class RenderWindowXORG : public IRenderWindow -{ -public: - RenderWindowXORG(uint16 width, uint16 height); - void Update(); - void SetCaption(const String& caption); - int GetWindowHandle(); - int GetWidth(); - int GetHeight(); - void SetSize(int w, int h); - const String& GetCaption(); - - int GetTop(); - int GetLeft(); - void SetPosition(int top, int left); - - bool IsFullScreen(); - void SetFullScreen(bool state); - bool SwitchMode(bool fullscreen); - void SetFullscreenMode(DisplayMode mode); - - void Present(Texture2D* tex); - - void OnActivate(); - void OnDeactivate(); - void OnResize(); - bool IsActive(); - bool IsModeSwitching(); - void SetCursorVisible(bool state); - bool IsCursorVisible(); - void CenterWindow(); -private: - uint8_t* image32; - Visual *visual; - GC gc; - Display *display_name; - XImage* img; - int depth,screen,connection; - Window window, rootwindow; -}; - -#endif //LINUX - -#endif // RENDERWINDOWXORG_H diff --git a/Dependencies/SoftGL/Src/SoftGL/Platform/Windows/RenderWindow.cpp b/Dependencies/SoftGL/Src/SoftGL/Platform/Windows/RenderWindow.cpp deleted file mode 100644 index 0af5556..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Platform/Windows/RenderWindow.cpp +++ /dev/null @@ -1,351 +0,0 @@ -#include "RenderWindow.h" - - -#include -#include - -RenderWindow::RenderWindow() - :UpdateCamera(false) { - bFullscreen = false; - bActive = true; - bModeSwitching = false; - bCursorVisible = true; - bAltEnterLocked = false; - - width = 256; - height = 256; - - g_hInst = GetModuleHandle(NULL); - g_hwnd = NULL; - - //memset(&g_wndClass,0,sizeof(WNDCLASSEX)); - - WNDCLASSEX g_wndClass = { NULL }; - - g_wndClass.cbSize = sizeof(WNDCLASSEX); - g_wndClass.cbClsExtra = NULL; - g_wndClass.cbWndExtra = NULL; - g_wndClass.hbrBackground = (HBRUSH)GetStockObject(1); - g_wndClass.hCursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW); - g_wndClass.hIcon = LoadIcon(g_hInst, IDI_APPLICATION); - g_wndClass.hIconSm = LoadIcon(g_hInst, IDI_APPLICATION); - g_wndClass.hInstance = g_hInst; - g_wndClass.lpfnWndProc = &RenderWindow::WndProc; - g_wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; - g_wndClass.lpszMenuName = NULL; - g_wndClass.lpszClassName = _text("Onotole"); - - if (!RegisterClassEx(&g_wndClass)) { - MessageBox(g_hwnd, _text("Can not create window class! We all gonna die!!"), _text("OH SHIT!"), MB_OK); - } - - - //calculate window size - RECT NewWindowSize; - NewWindowSize.top = 30; - NewWindowSize.left = 300; - NewWindowSize.bottom = NewWindowSize.top + height; - NewWindowSize.right = NewWindowSize.left + width; - - AdjustWindowRect(&NewWindowSize, WS_OVERLAPPEDWINDOW, false); - - /*WS_MINIMIZEBOX - WS_MAXIMIZEBOX*/ - - - if (!(g_hwnd = CreateWindowEx(NULL, _text("Onotole"), _text("LifeEngine render window"), WS_OVERLAPPEDWINDOW, - NewWindowSize.left, NewWindowSize.top, NewWindowSize.right - NewWindowSize.left, NewWindowSize.bottom - NewWindowSize.top, NULL, NULL, g_hInst, NULL))) { - MessageBox(g_hwnd, _text("Can not create window!"), _text("Can not create window!"), MB_OK); - return; - } - - ShowWindow(g_hwnd, SW_SHOWNORMAL); - SetForegroundWindow(g_hwnd); - SetFocus(g_hwnd); - - - ZeroMemory(&mode, sizeof(DEVMODE)); - mode.dmSize = sizeof(DEVMODE); - EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &mode); - - RenderWindow* ptr = this; - LONG_PTR val = (LONG_PTR)ptr; - SetWindowLongPtr(g_hwnd, GWLP_USERDATA, val); - - fsMode.width = 640; - fsMode.height = 480; - fsMode.refreshRate = 60; - fsMode.bpp = 4; - - ::ZeroMemory(&bitmapInfo, sizeof(BITMAPINFOHEADER)); - bitmapInfo.biSize = sizeof(BITMAPINFOHEADER); - bitmapInfo.biWidth = width; - bitmapInfo.biHeight = -height; - bitmapInfo.biPlanes = 1; - bitmapInfo.biBitCount = 32; - bitmapInfo.biCompression = 0; - bitmapInfo.biSizeImage = width * height * 4; - - info.bmiHeader = bitmapInfo; - - context = ::GetDC(g_hwnd); - - CenterWindow(); -} -void RenderWindow::Update() { -#ifdef L_WIN32 - MSG msg = { 0 }; - while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { - switch (msg.message) { - case WM_QUIT: - event_activate(); - exit(0); - - break; - } - TranslateMessage(&msg); - DispatchMessage(&msg); - } -#endif -} -void RenderWindow::SetCaption(const String& val) { - caption = val; - SetWindowText(g_hwnd, caption.c_str()); -} -void RenderWindow::SetFullScreen(bool state) { - bFullscreen = state; -} -bool RenderWindow::IsFullScreen() { - return bFullscreen; -} -RenderWindow::~RenderWindow(void) { - ChangeDisplaySettings(&mode, 0); -} - - -void RenderWindow::OnActivate() { - bActive = true; - event_activate(); -} -void RenderWindow::OnDeactivate() { - bActive = false; - event_deactivate(); -} -void RenderWindow::OnResize() { - if (!IsFullScreen() || !bModeSwitching) { - RECT r; - ::GetClientRect(g_hwnd, &r); - width = r.right - r.left; - height = r.bottom - r.top; - - ::ZeroMemory(&bitmapInfo, sizeof(BITMAPINFOHEADER)); - bitmapInfo.biSize = sizeof(BITMAPINFOHEADER); - bitmapInfo.biWidth = width; - bitmapInfo.biHeight = -height; - bitmapInfo.biPlanes = 1; - bitmapInfo.biBitCount = 32; - bitmapInfo.biCompression = 0; - bitmapInfo.biSizeImage = width * height * 4; - - info.bmiHeader = bitmapInfo; - } - event_resize(); -} -bool RenderWindow::IsActive() { - return bActive; -} -bool RenderWindow::IsModeSwitching() { - return bModeSwitching; -} -void RenderWindow::SetCursorVisible(bool state) { - bCursorVisible = state; -} -bool RenderWindow::IsCursorVisible() { - return bCursorVisible; -} - - -bool RenderWindow::SwitchMode(bool fullscreen) { - bFullscreen = fullscreen; - - if (bFullscreen) { - bModeSwitching = true; - DEVMODE fmode; - ZeroMemory(&fmode, sizeof(DEVMODE)); - fmode.dmSize = sizeof(DEVMODE); - fmode.dmPelsWidth = fsMode.width; - fmode.dmPelsHeight = fsMode.height; - fmode.dmBitsPerPel = mode.dmBitsPerPel; - fmode.dmDisplayFrequency = fsMode.refreshRate; - fmode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY; - - //if(ChangeDisplaySettings(&fmode,0)!= DISP_CHANGE_SUCCESSFUL) - // return false; - - SetWindowLong(g_hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_TOPMOST); - SetWindowLong(g_hwnd, GWL_STYLE, WS_POPUP); - SetWindowPos(g_hwnd, HWND_TOPMOST, 0, 0, fsMode.width, fsMode.height, SWP_SHOWWINDOW | SWP_FRAMECHANGED); - bModeSwitching = false; - } else { - //if(ChangeDisplaySettings(&mode_window,0)!= DISP_CHANGE_SUCCESSFUL) - // return false; - SetWindowLong(g_hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW); - SetWindowLong(g_hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW); - SetSize(width, height); - CenterWindow(); - } - event_switch_fullscreen(); - return true; -} -void RenderWindow::CenterWindow() { - int mx = GetSystemMetrics(SM_CXSCREEN); - int my = GetSystemMetrics(SM_CYSCREEN); - - int nx = (mx - width) / 2; - int ny = (my - height) / 2; - - SetWindowPos(g_hwnd, NULL, nx, ny, -1, -1, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); -} -void RenderWindow::SetFullscreenMode(DisplayMode _mode) { - fsMode = _mode; -} -void RenderWindow::SetSize(int w, int h) { - if (!IsFullScreen()) { - width = w; - height = h; - RECT NewWindowSize; - NewWindowSize.top = 50; - NewWindowSize.left = 50; - NewWindowSize.bottom = NewWindowSize.top + h; - NewWindowSize.right = NewWindowSize.left + w; - - AdjustWindowRect(&NewWindowSize, WS_OVERLAPPEDWINDOW, false); - SetWindowPos(g_hwnd, HWND_TOP, NewWindowSize.left, NewWindowSize.top, NewWindowSize.right - NewWindowSize.left, NewWindowSize.bottom - NewWindowSize.top, SWP_SHOWWINDOW | SWP_FRAMECHANGED); - //::MoveWindow(g_hwnd,NewWindowSize.left, NewWindowSize.top, NewWindowSize.right - NewWindowSize.left, NewWindowSize.bottom - NewWindowSize.top, true); - CenterWindow(); - } -} -LRESULT __stdcall RenderWindow::WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { - switch (message) { - case WM_SIZE: - { - - if (wparam != SIZE_MINIMIZED) { - LONG_PTR val = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (val) { - RenderWindow* wnd = (RenderWindow*)val; - wnd->OnResize(); - } - } - } - break; - case WM_SETCURSOR: - { - static bool hiddencursor = false; - WORD ht = LOWORD(lparam); - - LONG_PTR val = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (val) { - RenderWindow* wnd = (RenderWindow*)val; - if (wnd->IsCursorVisible()) { - ShowCursor(true); - } else { - if (HTCLIENT == ht && !hiddencursor) { - hiddencursor = true; - ShowCursor(false); - } else if (HTCLIENT != ht && hiddencursor) { - hiddencursor = false; - ShowCursor(true); - } - } - } - - - - } - break; - case WM_ACTIVATE: //Catch Alt + Tab - { - switch (wparam) { - case WA_ACTIVE: - { - LONG_PTR val = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (val) { - RenderWindow* wnd = (RenderWindow*)val; - wnd->OnActivate(); - } - } - break; - case WA_INACTIVE: - { - LONG_PTR val = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (val) { - RenderWindow* wnd = (RenderWindow*)val; - wnd->OnDeactivate(); - } - } - break; - } - } - break; - case WM_DESTROY: - PostQuitMessage(0); - DestroyWindow(hwnd); - break; - case WM_SYSKEYDOWN: - switch (wparam) { - case VK_RETURN: - { - if (GetKeyState(VK_MENU)) //Alt + Enter - { - LONG_PTR val = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (val) { - - RenderWindow* wnd = (RenderWindow*)val; - if (!wnd->IsAltEnterLocked()) { - wnd->SetAltEnterLocked(true); - wnd->SwitchMode(!wnd->IsFullScreen()); - } - } - } - } - break; - } - break; - case WM_SYSKEYUP: - { - switch (wparam) { - case VK_RETURN: - { - LONG_PTR val = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (val) { - - RenderWindow* wnd = (RenderWindow*)val; - wnd->SetAltEnterLocked(false); - } - } - break; - } - } - break; - case WM_KEYDOWN: - switch (wparam) { - case VK_SPACE: - { - LONG_PTR val = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (val) { - RenderWindow* wnd = (RenderWindow*)val; - wnd->UpdateCamera = !wnd->UpdateCamera; - } - } - break; - case VK_ESCAPE: - PostQuitMessage(0); - exit(0); - break; - } - } - return DefWindowProc(hwnd, message, wparam, lparam); -} - diff --git a/Dependencies/SoftGL/Src/SoftGL/Platform/Windows/RenderWindow.h b/Dependencies/SoftGL/Src/SoftGL/Platform/Windows/RenderWindow.h deleted file mode 100644 index b02b08d..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Platform/Windows/RenderWindow.h +++ /dev/null @@ -1,123 +0,0 @@ -#pragma once -#ifdef _WIN32 -#include -#include -#include -#include -#include - -class RenderWindow : public IRenderWindow { -public: - /*virtual ~RenderWindow(void) {} - virtual void Update() = 0; - virtual void SetCaption(const String& caption) = 0; - virtual int GetWindowHandle() = 0; - virtual int GetWidth() = 0; - virtual int GetHeight() = 0; - virtual const String& GetCaption() = 0;*/ - - bool UpdateCamera; - - RenderWindow(); - ~RenderWindow(void); - void Update(); - void SetCaption(const String& caption); - std::size_t GetWindowHandle() { return (std::size_t)g_hwnd; } - void SetSize(int w, int h); - bool IsFullScreen(); - void SetFullScreen(bool state); - bool SwitchMode(bool fullscreen); - void SetFullscreenMode(DisplayMode mode); - - - bool IsActive(); - bool IsModeSwitching(); - void SetCursorVisible(bool state); - bool IsCursorVisible(); - void CenterWindow(); - - int GetWidth() { - return width; - } - virtual int GetHeight() { - return height; - } - const String& GetCaption() { - return caption; - } - void SetAltEnterLocked(bool state) { - bAltEnterLocked = state; - } - bool IsAltEnterLocked() { - return bAltEnterLocked; - } - virtual void event_activate() { - - } - virtual void event_deactivate() { - - } - virtual void event_resize() { - - } - virtual void event_switch_fullscreen() { - - } - virtual void Present(Texture* tex) override { - if (tex->Desc().BytesPerPixel == 4) { - - SetDIBitsToDevice( - context, - 0, - 0, - tex->Desc().Width, - tex->Desc().Height, - 0, - 0, - 0, - tex->Desc().Height, - tex->LockWrite(), - &info, - 0 - ); - }else{ - DebugError("Can't present not 4 bytes pixels"); - } - } -protected: - bool bAltEnterLocked; - HINSTANCE g_hInst; - HWND g_hwnd; - DEVMODE mode; -private: - void OnActivate(); - void OnDeactivate(); - void OnResize(); - static LRESULT __stdcall WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); - - virtual int GetTop() override { - RECT rect; - GetWindowRect(g_hwnd, &rect); - return rect.top; - } - - virtual int GetLeft() override { - RECT rect; - GetWindowRect(g_hwnd, &rect); - return rect.left; - } - - virtual void SetPosition(int top, int left) override { - RECT rect; - GetWindowRect(g_hwnd, &rect); - SetWindowPos(g_hwnd, NULL, left, top, GetWidth(), GetHeight(), 0); - } - - BITMAPINFOHEADER bitmapInfo; - BITMAPINFO info; - HDC context; - - -}; - -#endif diff --git a/Dependencies/SoftGL/Src/SoftGL/RasterizerSettings.h b/Dependencies/SoftGL/Src/SoftGL/RasterizerSettings.h deleted file mode 100644 index f654fc9..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/RasterizerSettings.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef RasterizerSettings_h__ -#define RasterizerSettings_h__ - -#include - -typedef uint32_t indices_t; -#define MAX_TEX_SLOTS 16 - -static constexpr size_t InputElementNameLength = 16; - -#endif // RasterizerSettings_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Ray.h b/Dependencies/SoftGL/Src/SoftGL/Ray.h deleted file mode 100644 index ce92219..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Ray.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef Ray_h__ -#define Ray_h__ - -#include "LMath.h" - -class Ray -{ -public: - float3 Origin; - float3 Direction; - Ray() - :Origin(0,0,0), Direction(0,0,0) - { - - } - Ray(const float3& orig, const float3& dir) - { - Origin = orig; - Direction = dir; - } -}; -#endif // Ray_h__ \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/RegisterBlock.h b/Dependencies/SoftGL/Src/SoftGL/RegisterBlock.h deleted file mode 100644 index cbd00d4..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/RegisterBlock.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef RegisterBlock_h__ -#define RegisterBlock_h__ - -#include -#include - -using namespace lm; - -#define REG_COUNT 5 - -struct RegisterBlock { - std::array reg; - - inline static void Sub(const RegisterBlock& b1, const RegisterBlock& b2, RegisterBlock& result) { - for (int i = 0; i < REG_COUNT; i++) { - result.reg[i] = b1.reg[i] - b2.reg[i]; - } - } - inline static void Add(const RegisterBlock& b1, const RegisterBlock& b2, RegisterBlock& result) { - for (int i = 0; i < REG_COUNT; i++) { - result.reg[i] = b1.reg[i] + b2.reg[i]; - } - } - inline static void Mul(const RegisterBlock& b1, float val, RegisterBlock& result) { - for (int i = 0; i < REG_COUNT; i++) { - result.reg[i] = b1.reg[i] * val; - } - } - inline static void Div(const RegisterBlock& b1, float val, RegisterBlock& result) { - for (int i = 0; i < REG_COUNT; i++) { - result.reg[i] = b1.reg[i] / val; - } - } - inline static void Mul(RegisterBlock& b1, float val) { - for (int i = 0; i < REG_COUNT; i++) { - b1.reg[i] *= val; - } - } - inline static void Div(RegisterBlock& b1, float val) { - for (int i = 0; i < REG_COUNT; i++) { - b1.reg[i] /= val; - } - } - inline static void Clone(const RegisterBlock& from, RegisterBlock& to) { - for (int i = 0; i < REG_COUNT; i++) { - to.reg[i] = from.reg[i]; - } - } -}; -#endif // RegisterBlock_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/ResourceManager.h b/Dependencies/SoftGL/Src/SoftGL/ResourceManager.h deleted file mode 100644 index 36f4e34..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/ResourceManager.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef ResourceManager_h__ -#define ResourceManager_h__ - -#include "Buffer.h" - - -#endif // ResourceManager_h__ \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/SoftGL.pro b/Dependencies/SoftGL/Src/SoftGL/SoftGL.pro deleted file mode 100644 index c376a06..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/SoftGL.pro +++ /dev/null @@ -1,68 +0,0 @@ -TEMPLATE = lib -CONFIG += debug \ - staticlib \ - warn_off - - -DESTDIR = ../../bin -CONFIG -= release \ - warn_on - -HEADERS += \ - VSScreenSpace.h \ - VSDefault.h \ - Viewport.h \ - VertexShader.h \ - VertexBuffer.h \ - Vertex.h \ - float4.h \ - float3.h \ - Vector2D.h \ - Types.h \ - Tools.h \ - Timer.h \ - Texture2D.h \ - Scene.h \ - ResourceManager.h \ - RenderWindowXORG.h \ - RenderWindow.h \ - Renderer3D.h \ - Renderer.h \ - Ray.h \ - Quaternion.h \ - PSTextured.h \ - PSFont.h \ - PSDefault.h \ - Primitive.h \ - Plane.h \ - PixelShader.h \ - Mesh.h \ - Matrix4x4.h \ - Matrix3x3.h \ - LString.h \ - LMath.h \ - IShader.h \ - IRenderWindow.h \ - InputSystem.h \ - InputLayout.h \ - Inline.h \ - IndexBuffer.h \ - FpsCounter.h \ - DisplayMode.h \ - Delegate_base.h \ - Delegate.h \ - Camera.h \ - Buffer.h \ - BlockRasterizer.h \ - Bitmap.h \ - TextureSampler.h - -SOURCES += \ - RenderWindowXORG.cpp \ - RenderWindow.cpp \ - Mesh.cpp \ - BlockRasterizerTest.cpp \ - BlockRasterizer.cpp - -CONFIG += link_pkgconfig -PKGCONFIG += x11 diff --git a/Dependencies/SoftGL/Src/SoftGL/StaticBuffer.h b/Dependencies/SoftGL/Src/SoftGL/StaticBuffer.h deleted file mode 100644 index 90e5de7..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/StaticBuffer.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef StaticBuffer_h__ -#define StaticBuffer_h__ - -#include "Buffer.h" - -template -struct static_buffer : public Buffer { - std::array data; - static_buffer() { - - //static_assert(init.size() == Size, "Incorrect number of parameters"); - } - static_buffer(const std::array& values):data(values){ - - //static_assert(init.size() == Size, "Incorrect number of parameters"); - } - - virtual void* GetPointer() override { - return &data[0]; - } - - virtual size_t Size() override { - return _Size * sizeof(T); - } - - virtual size_t ItemSize() override { - return sizeof(T); - } -}; - -#endif // StaticBuffer_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/StaticTexture.h b/Dependencies/SoftGL/Src/SoftGL/StaticTexture.h deleted file mode 100644 index e3b3c52..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/StaticTexture.h +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once - -#include "mip_utils.h" -#include "Texture.h" -#include -#include - -template -struct MipChain : MipChain<_BytesPerPixel, MipUtils::SmallerMipSize(_Width), MipUtils::SmallerMipSize(_Height), _MaxMip, CurrentMip + 1> { - static constexpr auto Width = _Width; - static constexpr auto Height = _Height; - static constexpr auto BytesPerPixel = _BytesPerPixel; - static_assert(MipUtils::IsValidMipSize(_Width), "Invalid MIP width, must be power of 2"); - static_assert(MipUtils::IsValidMipSize(_Height), "Invalid MIP height, must be power of 2"); - std::array data; -}; - -template -struct MipChain<_BytesPerPixel, _Width, _Height, _MaxMip, CurrentMip, true> { - void* GetPointer() { - return &data[0]; - } - const void* GetPointer() const { - return &data[0]; - } - - static constexpr size_t MipsCount = CurrentMip + 1; - static constexpr auto Width = _Width; - static constexpr auto Height = _Height; - static constexpr auto BytesPerPixel = _BytesPerPixel; - std::array data; -}; - - -struct DynamicMipChain { - DynamicMipChain(size_t width, size_t height, size_t bytesPerPixel, size_t maxMip){ - size_t pixelsCount = 0; - _mipsCount = 0; - while(_mipsCount <= maxMip && (width > 0) && (height > 0)){ - pixelsCount += width * height; - width >>= 1; - height >>= 1; - _mipsCount++; - } - _data.resize(pixelsCount * bytesPerPixel); - } - void* GetPointer() { - return &_data[0]; - } - const void* GetPointer() const { - return &_data[0]; - } - size_t Size() const{ - return _data.size(); - } - size_t MipsCount() const { - return _mipsCount; - } -private: - size_t _mipsCount; - std::vector _data; -}; - - -template::type>::value> -struct PointerUtils { - using raw_pointer = decltype(&(*std::declval<_Pointer>())); - static raw_pointer GetWritable(_Pointer ptr) { return (raw_pointer)ptr->GetPointer(); } -}; - -template -struct PointerUtils<_Pointer, true> { - using raw_pointer = decltype(&(*std::declval<_Pointer>())); - static typename std::remove_cv>::type* GetWritable(_Pointer ptr) { return nullptr; } -}; - - -template -class StaticTexture : public Texture { -public: - StaticTexture(_DataPointer data, const TextureDescription& description) : Texture(description), _data(data) {} - virtual void* LockWrite() override { return PointerUtils<_DataPointer>::GetWritable(_data); } - virtual const void* LockRead() override { return _data->GetPointer(); } -private: - _DataPointer _data; -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/Texture.h b/Dependencies/SoftGL/Src/SoftGL/Texture.h deleted file mode 100644 index 2c9f7a6..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Texture.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef Texture_h__ -#define Texture_h__ - -#include "dynamic_buffer.h" -#include "LString.h" -#include "Bitmap.h" -#include -#include "mip_utils.h" - -struct Color24{ - uint8_t b; - uint8_t g; - uint8_t r; - - void fromColor16(uint16_t value){ - b = (value & 0x1f) << 3; - g = (value & 0x7e0) >> 3; - r = (value & 0xf800) >> 8; - } - - uint16_t toColor16(){ - uint16_t result = b >> 3; - result |= ((uint16_t)g >> 2) << 5; - result |= ((uint16_t)r >> 3) << 11; - return result; - } - - static Color24 lerp(Color24 left, Color24 right, uint16_t val, uint16_t maxVal){ - Color24 result; - result.r = (int32_t)left.r + ((int32_t)(right.r - left.r) * (int32_t)val) / (int32_t)maxVal; - result.g = (int32_t)left.g + ((int32_t)(right.g - left.g) * (int32_t)val) / (int32_t)maxVal; - result.b = (int32_t)left.b + ((int32_t)(right.b - left.b) * (int32_t)val) / (int32_t)maxVal; - - return result; - } - -}; - -struct TextureDescription { - size_t Width; - size_t Height; - size_t Depth; - size_t BytesPerPixel; - size_t MipCount; -}; - -struct Texture { - Texture(const TextureDescription& description) : _description(description) { - _depthStride = 0; - size_t width = _description.Width; - size_t height = _description.Height; - for (size_t i = 0; i < _description.MipCount; ++i) { - _depthStride += _description.BytesPerPixel * width * height; - width = MipUtils::SmallerMipSize(width); - height = MipUtils::SmallerMipSize(height); - } - } - virtual void* LockWrite() = 0; - virtual const void* LockRead() = 0; - virtual ~Texture() = default; - const TextureDescription& Desc() const { - return _description; - } -private: - size_t _depthStride; - TextureDescription _description; -}; - -#endif // Texture_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/TextureSampler.h b/Dependencies/SoftGL/Src/SoftGL/TextureSampler.h deleted file mode 100644 index ab38698..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/TextureSampler.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef TEXTURESAMPLER_H -#define TEXTURESAMPLER_H - -#include "Texture.h" - -static inline uint32_t sample2D(Texture* tex, float tX, float tY) -{ - if(tex == nullptr) - { - return 0; - } - tX = lm::clamp(tX, 0.0f, 1.0f); - tY = lm::clamp(tY, 0.0f, 1.0f); - - tY = 1.0f - tY; - - - - int x = static_cast((tX * ((float)tex->Desc().Width - 1.0f))); - int y = static_cast((tY * ((float)tex->Desc().Height - 1.0f))); - auto ptr = reinterpret_cast(tex->LockRead()); - - - float pX = tX * (float)tex->Desc().Width; - float pY = tY * (float)tex->Desc().Height; - - uint32_t frX = (uint32_t)((pX - (float)((int)pX))* 255.0f); - uint32_t frY = (uint32_t)((pY - (float)((int)pY))* 255.0f); - - auto ptr2 = reinterpret_cast(tex->LockRead()); - - uint32_t color; - // if(tex->bpp < 4) - // { - uint32_t tl = 0xff000000; - /* uint32_t tr = 0xff000000; - uint32_t rl = 0xff000000; - uint32_t rr = 0xff000000;*/ - - memcpy(&tl, ptr+ (y*tex->Desc().Width + x)* tex->Desc().BytesPerPixel, tex->Desc().BytesPerPixel); - //memcpy(&tr, ptr+ (y*tex->width + x + 1)* tex->bpp, 3); - // memcpy(&rl, ptr+ ((y + 1)*tex->width + x)* tex->bpp, 3); - //memcpy(&rr, ptr+ ((y + 1)*tex->width + x + 1)* tex->bpp, 3); - - color = tl;// blendrgb ( blendrgb ( tl, tr, frX), blendrgb ( rl, rr, frX), frY); - - /* } - else - { - - int32 x1 = x; - int32 x2 = x + 1; - int32 x3 = x; - int32 x4 = x + 1; - - int32 y1 = y; - int32 y2 = y; - int32 y3 = (y + 1); - int32 y4 = (y + 1); - - x1 = clampInt(x1, 0, tex->width - 1); - x2 = clampInt(x2, 0, tex->width - 1); - x3 = clampInt(x3, 0, tex->width - 1); - x4 = clampInt(x4, 0, tex->width - 1); - - - y1 = clampInt(y1, 0, tex->height - 1); - y2 = clampInt(y2, 0, tex->height - 1); - y3 = clampInt(y3, 0, tex->height - 1); - y4 = clampInt(y4, 0, tex->height - 1); - - - - - uint32_t tl = ptr2[y1 * tex->width + x1]; - uint32_t tr = ptr2[y2 * tex->width + x2]; - uint32_t rl = ptr2[y3 * tex->width + x3]; - uint32_t rr = ptr2[y4 * tex->width + x4]; - - color = blendrgb ( blendrgb ( tl, tr, frX), blendrgb ( rl, rr, frX), frY); - }*/ - - return color; -} - -#endif // TEXTURESAMPLER_H diff --git a/Dependencies/SoftGL/Src/SoftGL/Tools.h b/Dependencies/SoftGL/Src/SoftGL/Tools.h deleted file mode 100644 index 1d55200..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Tools.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef Tools_h__ -#define Tools_h__ - -template -void PrintBits(const T& val) -{ - int countBytes = sizeof(T); - int countBits = countBytes * 8; - char* ptr = (char*)&val; - - for(int i = 0; i < countBytes; i++) - { - char b = *ptr; - for(int j = 7; j >= 0; j--) - { - char val = (b & (1 << j)) >> j; - printf("%i", val); - } - printf(" "); - ptr++; - } - printf("\n"); - -} -#endif // Tools_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/VSDefault.h b/Dependencies/SoftGL/Src/SoftGL/VSDefault.h deleted file mode 100644 index 234b569..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/VSDefault.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef VSDefault_h__ -#define VSDefault_h__ - -#include "VertexShader.h" - -class VSDefault : public VertexShader -{ -public: - float4x4 mWorld; - float4x4 mView; - float4x4 mProj; - - VSDefault(){ - //declare shader inputs - inputs.push_back(String("POSITION")); - inputs.push_back(String("TEXCOORD")); - inputs.push_back(String("NORMAL")); - } - int Execute(float4** input, float4* output) - { - float4x4 wv = lm::mul(mView, mWorld); - float4x4 wvp = lm::mul(mProj, wv); - - float4 position = *input[0]; - position.w() = 1.0f; - - float3x3 world; - world[0] = mWorld[0].xyz(); - world[1] = mWorld[1].xyz(); - world[2] = mWorld[2].xyz(); - - - output[0] = lm::mul(wvp, position); - output[1] = *input[1]; - output[2].xyz() = lm::mul(world, (*input[2]).xyz()); - output[3].xyz() = lm::mul(mWorld, position).xyz(); - return 4; - } -}; -#endif // VSDefault_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/VSScreenSpace.h b/Dependencies/SoftGL/Src/SoftGL/VSScreenSpace.h deleted file mode 100644 index 7d0c7a0..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/VSScreenSpace.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef VSScreenSpace_h__ -#define VSScreenSpace_h__ - - -#include "VertexShader.h" - -class VSScreenSpace : public VertexShader -{ -public: - //Matrix4x4 mWorld; - //Matrix4x4 mView; - //Matrix4x4 mProj; - float width; - float height; - - float pX; - float pY; - - float screenWidth; - float screenHeight; - - - VSScreenSpace() - { - //declare shader inputs - inputs.push_back(STR("POSITION")); - inputs.push_back(STR("COLOR")); - } - int Execute(float4** input, float4* output) - { - //Matrix4x4 wv = mWorld * mView; - //Matrix4x4 wvp = wv * mProj; - float xScale = width / screenWidth; - float yScale = height / screenHeight; - - float4 position = (*input)[0]; - position.W = 1.0f; - - position.X *= width; - position.Y *= height; - - position.X += pX; - position.Y += pY; - - position.X = position.X / screenWidth * 2.0f - 1.0f; - position.Y = position.Y / screenHeight * 2.0f - 1.0f; - - //Output.Position.xy = Output.Position.xy/float2(bbWidth, -bbHeight)*2.0f + float2(-1.0f,1.0f); - - - output[0] = position; - //Vec4Transform(position, wvp); - //output[0] = position; - - output[1] = (*input)[1]; - - return 2; - } -}; -#endif // VSScreenSpace_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/Vertex.h b/Dependencies/SoftGL/Src/SoftGL/Vertex.h deleted file mode 100644 index 030638a..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Vertex.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -struct Vertex { - lm::float4 Position; - lm::float3 Normal; - lm::float2 UV0; - - Vertex() { - - } - Vertex(const lm::float4& pos, const lm::float2& tc) { - Position = pos; - UV0 = tc; - } -}; diff --git a/Dependencies/SoftGL/Src/SoftGL/VertexShader.h b/Dependencies/SoftGL/Src/SoftGL/VertexShader.h deleted file mode 100644 index 614b8bf..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/VertexShader.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef VertexShader_h__ -#define VertexShader_h__ - -#include "IShader.h" - - - -class VertexShader : public IShader -{ -public: - virtual ~VertexShader() - { - - } - virtual int Execute(float4** input, float4* output) = 0; - -}; -#endif // VertexShader_h__ \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/Viewport.h b/Dependencies/SoftGL/Src/SoftGL/Viewport.h deleted file mode 100644 index ba85c4e..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/Viewport.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef Viewport_h__ -#define Viewport_h__ - -#include - -class Viewport { -public: - int32_t width; - int32_t height; - float minZ; - float maxZ; - - Viewport(int32_t _width, int32_t _height, float _minZ, float _maxZ) { - width = _width; - height = _height; - minZ = _minZ; - maxZ = _maxZ; - } - ~Viewport() { - - } -}; -#endif // Viewport_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/config.h b/Dependencies/SoftGL/Src/SoftGL/config.h deleted file mode 100644 index 51b4c77..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/config.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef config_h__ -#define config_h__ - -#if (_MSC_VER) -#include -#endif - -#if (_MSC_VER) -template -using Pointer = std::shared_ptr; -#else -template -using Pointer = T*; -#endif - - -#endif // config_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/dynamic_buffer.h b/Dependencies/SoftGL/Src/SoftGL/dynamic_buffer.h deleted file mode 100644 index 90c84c0..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/dynamic_buffer.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef dynamic_buffer_h__ -#define dynamic_buffer_h__ - -#include "Buffer.h" - -template -struct dynamic_buffer : public Buffer{ -public: - dynamic_buffer() : _size(0), _data(nullptr) { - - } - dynamic_buffer(size_t count) : _size(count * sizeof(T)){ - _data = new T[count]; - } - dynamic_buffer(const dynamic_buffer& v) { - _size = v._size; - _data = new T[_size / sizeof(T)]; - memcpy(&_data[0], &v._data[0], _size); - } - dynamic_buffer(dynamic_buffer&& v) { - _size = v._size; - _data = v._data; - - v._size = 0; - v._data = nullptr; - } - - dynamic_buffer& operator=(const dynamic_buffer& v) { - _size = v._size; - _data = new T[_size / sizeof(T)]; - memcpy(&_data[0], &v._data[0], _size); - return *this; - } - - dynamic_buffer& operator=(dynamic_buffer&& v) { - _size = v._size; - _data = v._data; - - v._size = 0; - v._data = nullptr; - return *this; - } - - ~dynamic_buffer(){ - if (_data != nullptr) { - delete[] _data; - } - } - - virtual void* GetPointer() override { - return _data; - } - - virtual size_t Size() override { - return _size; - } - - virtual size_t ItemSize() override { - return sizeof(T); - } - -private: - size_t _size; - T* _data; -}; -#endif // dynamic_buffer_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/mip_utils.h b/Dependencies/SoftGL/Src/SoftGL/mip_utils.h deleted file mode 100644 index 1a747fa..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/mip_utils.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef mip_utils_h__ -#define mip_utils_h__ - -struct MipUtils { - static constexpr size_t SmallerMipSize(size_t size) { - return size > 1 ? size / 2 : size; - } - - static constexpr bool IsValidMipSize(size_t size) { - return size == 0 ? false : (size == 1 ? true : (size % 2 == 0)); - } -}; - -#endif // mip_utils_h__ \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/softgl.vcxproj b/Dependencies/SoftGL/Src/SoftGL/softgl.vcxproj deleted file mode 100644 index 1d5f877..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/softgl.vcxproj +++ /dev/null @@ -1,207 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {C26A3393-5100-439B-8570-45FA48819037} - Win32Proj - softgl - 10.0.14393.0 - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions);_CRT_SECURE_NO_WARNINGS;_CRTDBG_MAP_ALLOC - true - D:\lmath\lmath;%(AdditionalIncludeDirectories) - MultiThreadedDebug - - - Console - true - - - - - - - Level3 - Disabled - _DEBUG;_CONSOLE;%(PreprocessorDefinitions);_CRT_SECURE_NO_WARNINGS;_CRTDBG_MAP_ALLOC - true - D:\lmath\lmath;%(AdditionalIncludeDirectories) - MultiThreadedDebug - - - Console - true - - - - - Level3 - - - Full - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions);_CRT_SECURE_NO_WARNINGS - true - D:\lmath\lmath;%(AdditionalIncludeDirectories) - MultiThreaded - - - Console - true - true - true - - - - - Level3 - - - MaxSpeed - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions);_CRT_SECURE_NO_WARNINGS - true - D:\lmath\lmath;%(AdditionalIncludeDirectories) - MultiThreaded - - - Console - true - true - true - - - - - - \ No newline at end of file diff --git a/Dependencies/SoftGL/Src/SoftGL/static_mip_chain.h b/Dependencies/SoftGL/Src/SoftGL/static_mip_chain.h deleted file mode 100644 index 198ba68..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/static_mip_chain.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef mip_static_buffer_h__ -#define mip_static_buffer_h__ - -#include - -struct MipUtils { - static constexpr size_t SmallerMipSize(size_t size){ - return size > 1 ? size / 2 : size; - } -}; - -template -struct StaticMipChain { -public: - static constexpr uint32_t ChildWidth = MipUtils::SmallerMipSize(Width); - static constexpr uint32_t ChildHeight = MipUtils::SmallerMipSize(Height); - std::array data; - - StaticMipChain<_BytesPerPixel, ChildWidth, ChildHeight, _MaxMip, CurrentMip + 1> child; -}; - -template -struct StaticMipChain<_BytesPerPixel, 1, 1, _MaxMip, CurrentMip> { - -}; - - -#endif // mip_static_buffer_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/static_vector.h b/Dependencies/SoftGL/Src/SoftGL/static_vector.h deleted file mode 100644 index ed62a86..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/static_vector.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef static_vector_h__ -#define static_vector_h__ - -#include -#include "Debug.h" - -template -class Static_vector { -public: - Static_vector():_size(0){ - - } - static constexpr size_t capacity(){ - return Capacity; - } - bool full() const { - return _size == Capacity; - } - bool empty() const { - return _size == 0; - } - void clear(){ - _size = 0; - } - bool push_back(const T& value){ - if(full()){ - assert(false && "Can't push"); - return false; - } - _buffer[_size++] = value; - return true; - } - void pop_back(){ - if(empty()){ - return; - } - --_size; - } - void remove(size_t id){ - if(id >= _size){ - return; - } - - _buffer[id] = _buffer[_size-1]; - --_size; - } - T& operator[](size_t id){ - SGL_ASSERT(id < _size, "Invalid index"); - return _buffer[id]; - } - const T& operator[](size_t id) const{ - SGL_ASSERT(id < _size, "Invalid index"); - return _buffer[id]; - } - size_t size() const { - return _size; - } -private: - T _buffer[Capacity]; - size_t _size; -}; -#endif // static_vector_h__ diff --git a/Dependencies/SoftGL/Src/SoftGL/texture_utils.h b/Dependencies/SoftGL/Src/SoftGL/texture_utils.h deleted file mode 100644 index eb11ae3..0000000 --- a/Dependencies/SoftGL/Src/SoftGL/texture_utils.h +++ /dev/null @@ -1,176 +0,0 @@ -#ifndef texture_utils_h__ -#define texture_utils_h__ - -#include - -#include "StaticTexture.h" -#include "Bitmap.h" -//#include -#include - -struct texture_utils { - - template - static bool copy(Texture* src, Texture* dst) { - auto srcDesc = src->Desc(); - auto dstDesc = dst->Desc(); - - if (srcDesc.Width != dstDesc.Width || (srcDesc.Height != dstDesc.Height)) { - return false; - } - - - auto* srcPtr = reinterpret_cast(src->LockRead()); - auto* dstPtr = reinterpret_cast(dst->LockWrite()); - - for (size_t y = 0; y < srcDesc.Height; ++y) { - for (size_t x = 0; x < srcDesc.Width; ++x) { - lm::float4 srcDataf = SrcAccessor::ConvertColor(srcPtr[x]); - auto dstColor = DstAccessor::ConvertColor(srcDataf); - dstPtr[x] = dstColor; - } - srcPtr += srcDesc.Width; - dstPtr += srcDesc.Width; - } - - return true; - } - - - template - static bool fill(Texture* tex, T pixel_value) { - if (tex == nullptr) { - return false; - } - - if (tex->Desc().BytesPerPixel != sizeof(T)) { - //throw std::exception("Invalid pixel value specified"); - return false; - } - - auto data = (T*)tex->LockWrite(); - - auto memsize = tex->Desc().Width * tex->Desc().Height * sizeof(pixel_value); - - if((8 % (sizeof(T))) == 0 && (memsize % 8) == 0) - { - alignas(8) uint64_t block_value; - T* blockPtr = (T*)&block_value; - for (size_t i = 0; i < (8 / sizeof(T)); ++i) { - blockPtr[i] = pixel_value; - } - - auto blockMem = (uint64_t*)data; - for(size_t i = 0; i < (memsize / sizeof(block_value)); ++i) - { - blockMem[i] = block_value; - } - } - - /*__m256i avxBlock; - - if ((sizeof(avxBlock) % (sizeof(T))) == 0 && (memsize % sizeof(avxBlock)) == 0) { - T* blockPtr = (T*)&avxBlock; - for (size_t i = 0; i < (sizeof(avxBlock) / sizeof(T)); ++i) { - blockPtr[i] = pixel_value; - } - - auto blockMem = (decltype(avxBlock)*)data; - if(((size_t)blockMem % sizeof(avxBlock)) != 0) - { - throw std::exception("Memory is not SSE aligned"); - } - const auto cnt = (memsize / sizeof(avxBlock)); - const auto last = blockMem + cnt; - while(blockMem != last){ - - _mm256_store_si256(blockMem++, avxBlock); - //_mm_store_si128(blockMem++, avxBlock); - } - }*/ - - - //generic assign - /*for (size_t i = 0; i < tex->Desc().Width * tex->Desc().Height; ++i) { - data[i] = pixel_value; - }*/ - return true; - } - - static Texture* LoadTexture(const std::string& path) { - FILE *filePtr; //our file pointer - BITMAPFILEHEADER bitmapFileHeader; //our bitmap file header - BITMAPINFOHEADER bitmapInfoHeader; - - //open filename in read binary mode - filePtr = fopen(path.c_str(), "rb"); - if (filePtr == NULL) - return nullptr; - - //read the bitmap file header - int read_cnt = fread(&bitmapFileHeader, 1, sizeof(BITMAPFILEHEADER), filePtr); - - if (read_cnt != sizeof(BITMAPFILEHEADER)) { - printf("EPIC FAIL!\n"); - } - - - //verify that this is a bmp file by check bitmap id - if (bitmapFileHeader.bfType != 0x4D42) { - fclose(filePtr); - return nullptr; - } - - //read the bitmap info header - fread(&bitmapInfoHeader, 1, sizeof(BITMAPINFOHEADER), filePtr); - - //move file point to the begging of bitmap data - fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET); - - auto width = bitmapInfoHeader.biWidth; - auto height = bitmapInfoHeader.biHeight; - auto bpp = bitmapInfoHeader.biBitCount / 8; - - auto mips = std::make_shared(width, height, bpp, -1); - - auto bytes_count = width * height * bpp; - - auto stride = width * bpp; - - auto padding = stride % 4 == 0 ? 0 : (4 - (stride % 4)); - - uint8_t* ptr = (uint8_t*)mips->GetPointer(); - - //read in the bitmap image data - for (size_t y = 0; y < height; ++y) { - auto dst_ptr = ptr + stride * (height - 1 - y); - auto result = fread(dst_ptr, 1, stride, filePtr); - if (padding != 0) { - fseek(filePtr, padding, SEEK_CUR); - } - } - - fclose(filePtr); - - - TextureDescription desc; - desc.Width = width; - desc.Height = height; - desc.BytesPerPixel = bpp; - desc.MipCount = mips->MipsCount(); - desc.Depth = 1; - - return new StaticTexture(mips, desc); - } - - /*auto bb = rasterizer.GetBackBuffer(); - uint32_t* pixels = (uint32_t*)bb->getBuffer()->getDataPtr(); - for (size_t y = 0; y < bb->height; ++y) { - for (size_t x = 0; x < bb->width; ++x) { - uint32_t xVal = (x * 0xff) / bb->width; - uint32_t yVal = (y * 0xff) / bb->height; - pixels[y * bb->width + x] = ((xVal & 0xff) << 16) | ((yVal & 0xff) << 8); - } - }*/ -}; -#endif // texture_utils_h__ diff --git a/Dependencies/SoftGL/softgl.pro b/Dependencies/SoftGL/softgl.pro deleted file mode 100644 index d373079..0000000 --- a/Dependencies/SoftGL/softgl.pro +++ /dev/null @@ -1,5 +0,0 @@ -TEMPLATE = subdirs - -SUBDIRS += \ - Demo_TexturedTriangle \ - SoftGL