Compare commits

..

No commits in common. "master" and "v2.1.3" have entirely different histories.

845 changed files with 256976 additions and 203643 deletions

View File

@ -1,47 +0,0 @@
version: '{build}'
image:
- Visual Studio 2017
build:
verbosity: detailed
configuration:
- Debug
- Release
platform:
- x64
- x86
environment:
matrix:
- STATIC: " "
- STATIC: "-static"
matrix:
fast_finish: true
install:
- set NINJA_URL="https://github.com/ninja-build/ninja/releases/download/v1.9.0/ninja-win.zip"
- appveyor DownloadFile %NINJA_URL% -FileName ninja.zip
- 7z x ninja.zip -oc:\projects\ninja > nul
- set PATH=c:\projects\ninja;%PATH%
- ninja --version
before_build:
- call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" %PLATFORM%
build_script:
- mkdir build
- cd build
- cmake .. -DVCPKG_TARGET_TRIPLET=%PLATFORM%-windows%STATIC% -DCMAKE_BUILD_TYPE=%CONFIGURATION% -DENABLE_SDL=TRUE -G Ninja
- ninja
# only debug builds are console mode apps, in them test --help
test_script:
- if not %CONFIGURATION%==Release .\visualboyadvance-m.exe --help
- ctest -V
cache:
- c:\vcpkg\installed

38
.drone.yml Normal file
View File

@ -0,0 +1,38 @@
# Build configuration for https://www.tea-ci.org
# Tea CI is a fork of Drone CI with Cygwin/Msys2 support
# Feel free to share Tea CI to more open source developers
# http://docs.tea-ci.org/usage/overview/
# Please add your project to https://github.com/TeaCI/tea-ci/wiki/Msys2-on-Wine#use-msys2-in-tea-ci
build:
image: teaci/msys$$arch
pull: true
shell: mingw$$arch
commands:
- if [ $$arch = 32 ]; then target=i686; fi
- if [ $$arch = 64 ]; then target=x86_64; fi
- pacman -S --needed --noconfirm --noprogressbar mingw-w64-${target}-cmake mingw-w64-${target}-ffmpeg mingw-w64-${target}-SDL2 mingw-w64-${target}-openal mingw-w64-${target}-sfml mingw-w64-${target}-extra-cmake-modules mingw-w64-${target}-cairo mingw-w64-${target}-zlib mingw-w64-${target}-libpng nasm mingw-w64-${target}-wxWidgets mingw-w64-${target}-crt-git mingw-w64-${target}-headers-git zip
- git submodule update --init --recursive
- cmake -DENABLE_FFMPEG=ON -DENABLE_SDL=ON -G "MSYS Makefiles"
- make
notify:
irc:
prefix: build
nick: vbam-ci
channel: #vba-m
server:
host: irc.freenode.net
port: 6667
matrix:
arch:
- 64
- 32
#publish:
# github_release:
# api_key: 4cd466723ff104154a6a206814ddaa159131f2ec
# files:
# - vbam.exe
# - visualboyadvance-m.exe
# checksum:
# - sha256

1
.github/FUNDING.yml vendored
View File

@ -1 +0,0 @@
github: rkitover

49
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,49 @@
### Please fill out this form:
### Expected behavior
### Actual behavior
### Steps to reproduce the behavior
### Crash bugs
If this is a crash bug, and you have the time and inclination, please provide a
symblic backtrace.
Instructions for doing so are
[here](https://github.com/visualboyadvance-m/visualboyadvance-m/blob/master/README.md#reporting-crash-bugs).
### ROM details
Which games are affected by the issue (please state if GBA or GB game):
Which games, if any, are NOT affected by the issue (please state if GBA or GB game):
Include screenshots of ROM Information (File > ROM Information):
If you are using a BIOS file, please say which one.
### Option details
Video driver (simple, opengl):
Sound driver (directsound, xaudio, openal, SDL):
### Build details
Operating System (Windows, Mac, Linux (state distribution), etc.):
If using Linux, specify if using xorg or Wayland:
Version of code (pre-built binary version, or commit ref, or just "master"):
### Hardware details:
If your joystick or gamepad isn't working in Linux, please try to troubleshoot
using the information on this page:
https://wiki.archlinux.org/index.php/Gamepad **BEFORE** filing an issue. We use
SDL for joystick support, any problems will generally be an issue with SDL and
**NOT** the emulator.
If relevant, the joystick you are using and the drivers you are using for it:

View File

@ -1,163 +0,0 @@
name: Bug Report
description: If you experience a bug in the Emulator, please open an issue here and fill out the template.
title: "[Bug]: "
labels: ["bug", "triage"]
assignees:
-
body:
- type: markdown
attributes:
value: "## BEFORE REPORTING AN ISSUE"
- type: markdown
attributes:
value: |
Please try the nightly build from: https://nightly.visualboyadvance-m.org and factory resetting the emulator from the Help menu.
On Linux build master from source or use the edge snap.
And last but not least, search for existing reports via the filters bar on the issues page.
- type: markdown
attributes:
value: "## If your joystick or gamepad isn't working in Linux"
- type: markdown
attributes:
value: |
Please try to troubleshoot using the information on this page: https://wiki.archlinux.org/index.php/Gamepad **BEFORE** filing an issue.
We use SDL for joystick support, any problems will generally be an issue with SDL and **NOT** the emulator.
If relevant, the joystick you are using and the drivers you are using for it:
- type: textarea
id: what-should-happen
attributes:
label: Expected behavior?
description: How was the emulator supposed to behave
placeholder: Tell us what you expect to see!; use screenshots if necessary.
value:
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: Actual behavior?
description: Describe the issue you encountered.
placeholder: Tell us what you see!; use screenshots if necessary.
value:
validations:
required: true
- type: textarea
id: repro
attributes:
label: Steps to reproduce the problem
description: "How do you trigger this bug? Please walk us through it step by step."
placeholder: |
1.
2.
3.
4.
5.
...
validations:
required: true
- type: textarea
id: error-messages
attributes:
label: Error messages?
description: Was there an error message?
placeholder: List any exception messages here!; use screenshots if necessary.
value: |
If this is a crash bug, and you have the time and inclination, please provide a symbolic backtrace.
Instructions for doing so are [here](https://github.com/visualboyadvance-m/visualboyadvance-m/blob/master/README.md#reporting-crash-bugs).
validations:
required: false
- type: textarea
id: Rom_Details
attributes:
label: What game were you playing
description: "What is the specific rom that you encountered an issue with"
value: |
<Some of this information can be provided with a screenshot of Rom Information, SAVE TYPE for GBA titles can be obtained from Options > Game Boy Advance > Config>
Title:
GB, GBC or GBA:
ROM CODE:
BIOS Used?: (Share crc hash)
SAVE TYPE: (Attach Battery or Savestate here)
Clean, Intro'd or Hacked?:(Attach Patch here)
validations:
required: false
- type: markdown
attributes:
value: "### Emulator Settings\nList the settings you are using."
- type: input
id: Video_Driver
attributes:
label: Video Driver
description: "Specify which video driver you're using (e.g., Simple, OpenGL)."
validations:
required: true
- type: input
id: Sound_Driver
attributes:
label: Sound Driver
description: "Specify which sound driver you're using (e.g., DirectSound, XAudio, OpenAL, SDL)."
validations:
required: true
- type: input
id: Scale_Filter
attributes:
label: Scale Filter
description: "Specify which scale filter you are using."
validations:
required: true
- type: markdown
attributes:
value: "### Specifications and Build Details\nList your system information, you can obtain this from MSINFO32 and the emulator's Titlebar."
- type: input
id: VBA-M
attributes:
label: VBA-M Version
description: "Include commit version number and whether you are using the 32-bit or 64-bit version."
validations:
required: true
- type: input
id: OS
attributes:
label: Operating System
description: "Include version and OS build number using WinVer if on Windows."
validations:
required: true
- type: dropdown
id: Linux_Display_Server
attributes:
label: Linux Display Server
description: "Specify whether using Xorg or Wayland."
options:
- Xorg
- Wayland
validations:
required: false
- type: input
id: CPU
attributes:
label: CPU Model
description: "Provide details of your CPU model."
validations:
required: true
- type: input
id: GPU
attributes:
label: GPU Model
description: "Provide details of your GPU model."
validations:
required: true
- type: input
id: RAM
attributes:
label: RAM Size
description: "Specify the amount of RAM installed."
validations:
required: true
- type: checkboxes
id: Copyright_Compliance
attributes:
label: Copyright Compliance
description: Please do not attach any files that infringe on the copyright of Nintendo or its partners.
options:
- label: There are no infringing files attached to this bug report.
required: true

View File

@ -1,9 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: VBA-M Forum
url: https://board.visualboyadvance-m.org/
about: For general questions and support please join our forum or our
- name: VBA-M IRC Channel
url: https://web.libera.chat/#vba-m
about: For realtime discussion and support

View File

@ -1,46 +0,0 @@
name: Feature request
description: >-
If you would like a new feature in Visual Boy Advance - M, please
open an issue here and fill out the template.
title: '[Feature request]: '
labels:
- enhancement
assignees:
- null
body:
- type: markdown
attributes:
value: "## BEFORE CREATING A FEATURE REQUEST"
- type: markdown
attributes:
value: |
Please try a nightly build from: https://nightly.visualboyadvance-m.org to see if your idea has already been implemented.
On Linux build master from source or use the edge snap.
And last but not least, search for existing requests via the filters bar on the issues page.
- type: textarea
id: feature-request
attributes:
label: Request box
description: What feature would you like to see added?
placeholder: Tell us what you would like to see added to Visual Boy Advance - M!
value: null
validations:
required: true
- type: textarea
id: reason-why
attributes:
label: Reason box
description: Provide reasoning for the new feature
placeholder: Tell us why you'd like to see this feature added
value: null
validations:
required: true
- type: textarea
id: Examples
attributes:
label: Examples
description: Provide examples of this feature
placeholder: Provide examples or screenshots of this feature in other software
value: null
validations:
required: true

View File

@ -1,34 +0,0 @@
name: Libretro Devkitpro
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
# target_name: [ngc, wii, wiiu, switch]
target_name: [ngc, wii, wiiu]
build_type: [release, debug]
include:
- libretro_build: 'DEBUG=0'
build_type: release
- libretro_build: 'DEBUG=1'
build_type: debug
- devkit_container: 'devkitpro/devkitppc:latest'
target_name: ngc
- devkit_container: 'devkitpro/devkitppc:latest'
target_name: wii
- devkit_container: 'devkitpro/devkitppc:latest'
target_name: wiiu
# - devkit_container: 'devkitpro/devkita64:latest'
# target_name: switch
runs-on: ubuntu-latest
container: ${{ matrix.devkit_container }}
steps:
- name: Checkout the code
uses: actions/checkout@v4
with:
submodules: recursive
# Libretro build
- name: Build libretro core
run: make -C src/libretro ${{ matrix.libretro_build }} platform=${{ matrix.target_name }}

View File

@ -1,63 +0,0 @@
name: macOS Latest
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
build_type: [release, debug]
build_options: [default, link_off, translations_only, libretro]
include:
- cmake_build: '-DCMAKE_BUILD_TYPE=Release'
build_type: release
- cmake_build: '-DCMAKE_BUILD_TYPE=Debug'
build_type: debug
- cmake_options: '-DENABLE_LINK=OFF'
build_options: link_off
- cmake_options: '-DTRANSLATIONS_ONLY=ON'
build_options: translations_only
- libretro_build: 'DEBUG=0'
build_type: release
build_options: libretro
- libretro_build: 'DEBUG=1'
build_type: debug
build_options: libretro
exclude:
# Exclude debug/translations_only build
- build_type: debug
build_options: translations_only
runs-on: macos-latest
env:
NIXPKGS_ALLOW_UNSUPPORTED_SYSTEM: 1
steps:
- name: Checkout the code
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install nix
uses: cachix/install-nix-action@v22
with:
nix_path: nixpkgs=channel:nixos-unstable
# Cmake build
- if: matrix.build_options != 'libretro'
name: Configure CMake
run: >-
nix-shell --command 'cmake -B build -G Ninja ${{ matrix.cmake_build }} -DENABLE_LTO=OFF ${{ matrix.cmake_options }}'
- if: matrix.build_options != 'libretro'
name: Build
run: >-
nix-shell --command 'ninja -C build'
# Libretro build
- if: matrix.build_options == 'libretro'
name: Build libretro core
run: >-
nix-shell --command 'make -C src/libretro ${{ matrix.libretro_build }}'
# Run tests
- if: matrix.build_options == 'default'
name: Run tests
run: >-
nix-shell --command 'cd build && ctest -j --output-on-failure'

View File

@ -1,64 +0,0 @@
name: MSYS2
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
build_type: [release, debug]
build_options: [default, link_off, translations_only, libretro]
include:
- cmake_build: '-DCMAKE_BUILD_TYPE=Release'
build_type: release
- cmake_build: '-DCMAKE_BUILD_TYPE=Debug'
build_type: debug
- cmake_options: '-DENABLE_LINK=OFF'
build_options: link_off
- cmake_options: '-DTRANSLATIONS_ONLY=ON'
build_options: translations_only
- libretro_build: 'DEBUG=0'
build_type: release
build_options: libretro
- libretro_build: 'DEBUG=1'
build_type: debug
build_options: libretro
exclude:
# Exclude debug/translations_only build
- build_type: debug
build_options: translations_only
runs-on: windows-latest
env:
MSYSTEM: CLANG64
defaults:
run:
shell: msys2 {0}
steps:
- name: Checkout the code
uses: actions/checkout@v4
with:
submodules: recursive
- name: Setup msys2
uses: msys2/setup-msys2@v2
with:
msystem: CLANG64
update: true
- name: Install deps
run: >-
bash installdeps
# CMake build
- if: matrix.build_options != 'libretro'
name: Configure CMake
run: cmake -B build -G Ninja ${{ matrix.cmake_build }} -DENABLE_LTO=OFF ${{ matrix.cmake_options }}
- if: matrix.build_options != 'libretro'
name: Build
run: ninja -C build
- if: matrix.build_options != 'libretro'
name: Install
run: ninja -C build install
# Libretro build
- if: matrix.build_options == 'libretro'
name: Build libretro core
run: make -C src/libretro ${{ matrix.libretro_build }} CC=clang CXX=clang++

View File

@ -1,77 +0,0 @@
name: Ubuntu Latest
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
build_compiler: [gcc, clang]
build_type: [release, debug]
# build_options: [default, link_off, translations_only, libretro]
build_options: [default, link_off, translations_only]
include:
- cmake_compiler: '-DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++'
build_compiler: gcc
- cmake_compiler: '-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++'
build_compiler: clang
- cmake_build: '-DCMAKE_BUILD_TYPE=Release'
build_type: release
- cmake_build: '-DCMAKE_BUILD_TYPE=Debug'
build_type: debug
- cmake_options: '-DENABLE_LINK=OFF'
build_options: link_off
- cmake_options: '-DTRANSLATIONS_ONLY=ON'
build_options: translations_only
# - libretro_build: 'DEBUG=0'
# build_type: release
# build_options: libretro
# - libretro_build: 'DEBUG=1'
# build_type: debug
# build_options: libretro
exclude:
# Exclude debug/translations_only build
- build_type: debug
build_options: translations_only
- build_type: release
build_options: translations_only
build_compiler: clang
runs-on: ubuntu-latest
steps:
- name: Checkout the code
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install Dependencies
run: |
sudo add-apt-repository ppa:hrzhu/sdl3-backport
sudo apt update
bash installdeps
if [ "${{ matrix.build_compiler }}" = clang ]; then
sudo apt -y install clang
fi
- name: Install xvfb
run: sudo apt -y install xvfb
# CMake build
- if: matrix.build_options != 'libretro'
name: Configure CMake
run: >-
cmake -B build -G Ninja ${{ matrix.cmake_compiler }} ${{ matrix.cmake_build }} ${{ matrix.cmake_options }}
- if: matrix.build_options != 'libretro'
name: Build
run: ninja -C build
- if: matrix.build_options != 'libretro'
name: Install
run: sudo ninja -C build install
# Libretro build
# - if: matrix.build_options == 'libretro'
# name: Build libretro core
# run: make -C src/libretro ${{ matrix.libretro_build }}
# Run tests
- if: matrix.build_options == 'default'
name: Run tests
run: cd build && xvfb-run ctest -j --output-on-failure

View File

@ -1,60 +0,0 @@
name: Visual Studio
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
msvc_arch: ['x64', 'amd64_x86', 'amd64_arm64']
# TODO: Re-add "Visual Studio 17 2022" once it's working.
cmake_generator: ['Ninja']
build_type: [release, debug]
build_options: [default, link_off, translations_only]
include:
- cmake_build: '-DCMAKE_BUILD_TYPE=Release'
build_type: release
- cmake_build: '-DCMAKE_BUILD_TYPE=Debug'
build_type: debug
- cmake_options: '-DENABLE_LINK=OFF'
build_options: link_off
- cmake_options: '-DTRANSLATIONS_ONLY=ON'
build_options: translations_only
- cmake_vcpkg_triplet: 'x64-windows-static'
msvc_arch: x64
- cmake_vcpkg_triplet: 'x86-windows-static'
msvc_arch: amd64_x86
- cmake_vcpkg_triplet: 'arm64-windows-static'
msvc_arch: amd64_arm64
exclude:
# Exclude debug/translations_only build
- build_type: debug
build_options: translations_only
- build_type: release
build_options: translations_only
msvc_arch: amd64_x86
- build_type: release
build_options: translations_only
msvc_arch: amd64_arm64
runs-on: windows-latest
steps:
- name: Checkout the code
uses: actions/checkout@v4
with:
submodules: recursive
- name: Prepare Visual Studio environment
uses: ilammy/msvc-dev-cmd@v1.13.0
with:
arch: ${{ matrix.msvc_arch }}
- name: Configure
run: >-
cmake -B build -G ${{ matrix.cmake_generator }} -DVCPKG_TARGET_TRIPLET=${{ matrix.cmake_vcpkg_triplet }} ${{ matrix.cmake_build }} ${{ matrix.cmake_options }}
- name: Build
run: cmake --build build
# Run tests
- if: matrix.build_options == 'default' && matrix.msvc_arch != 'amd64_arm64'
name: Run tests
run: cd build && ctest -j --output-on-failure

21
.gitignore vendored
View File

@ -1,15 +1,19 @@
/*build*/*
src/wx/builtin-over.h
src/wx/builtin-xrc.h
src/wx/cmd-evtable.h
src/wx/cmdhandlers.h
src/wx/cmdtab.cpp
src/wx/wxvbam.xrs
build/*
build32/*
vsbuild/*
dependencies/*
vcpkg/*
.vs/*
.idea
*.o
*.so
*.dll
*.exe
.vscode/
# clangd files
compile_commands.json
.cache/
# vim swap files
*.sw?
@ -17,6 +21,3 @@ compile_commands.json
# mac finder crap
*.DS_Store
# online updates header
src/wx/winsparkle-path.h

View File

@ -1,201 +0,0 @@
# DESCRIPTION: GitLab CI/CD for libRetro (NOT FOR GitLab-proper)
##############################################################################
################################# BOILERPLATE ################################
##############################################################################
# Core definitions
.core-defs:
variables:
GIT_SUBMODULE_STRATEGY: recursive
JNI_PATH: src/libretro
MAKEFILE_PATH: src/libretro
CORENAME: vbam
# Inclusion templates, required for the build to work
include:
################################## DESKTOPS ################################
# Windows 64-bit
- project: 'libretro-infrastructure/ci-templates'
file: '/windows-x64-mingw.yml'
# Windows 32-bit
- project: 'libretro-infrastructure/ci-templates'
file: '/windows-i686-mingw.yml'
# Linux 64-bit
- project: 'libretro-infrastructure/ci-templates'
file: '/linux-x64.yml'
# Linux 32-bit
- project: 'libretro-infrastructure/ci-templates'
file: '/linux-i686.yml'
# MacOS 64-bit
- project: 'libretro-infrastructure/ci-templates'
file: '/osx-x64.yml'
# MacOS ARM 64-bit
- project: 'libretro-infrastructure/ci-templates'
file: '/osx-arm64.yml'
################################## CELLULAR ################################
# Android
- project: 'libretro-infrastructure/ci-templates'
file: '/android-jni.yml'
# iOS
- project: 'libretro-infrastructure/ci-templates'
file: '/ios-arm64.yml'
# iOS (armv7)
- project: 'libretro-infrastructure/ci-templates'
file: '/ios9.yml'
################################## CONSOLES ################################
# PlayStation Vita
- project: 'libretro-infrastructure/ci-templates'
file: '/vita-static.yml'
# Nintendo GameCube
- project: 'libretro-infrastructure/ci-templates'
file: '/ngc-static.yml'
# Nintendo Wii
- project: 'libretro-infrastructure/ci-templates'
file: '/wii-static.yml'
# Nintendo WiiU
- project: 'libretro-infrastructure/ci-templates'
file: '/wiiu-static.yml'
# Nintendo Switch
- project: 'libretro-infrastructure/ci-templates'
file: '/libnx-static.yml'
# tvOS (AppleTV)
- project: 'libretro-infrastructure/ci-templates'
file: '/tvos-arm64.yml'
#################################### MISC ##################################
# Stages for building
stages:
- build-prepare
- build-shared
- build-static
##############################################################################
#################################### STAGES ##################################
##############################################################################
#
################################### DESKTOPS #################################
# Windows 64-bit
libretro-build-windows-x64:
extends:
- .libretro-windows-x64-mingw-make-default
- .core-defs
# Windows 32-bit
libretro-build-windows-i686:
extends:
- .libretro-windows-i686-mingw-make-default
- .core-defs
# Linux 64-bit
libretro-build-linux-x64:
extends:
- .libretro-linux-x64-make-default
- .core-defs
# Linux 32-bit
libretro-build-linux-i686:
extends:
- .libretro-linux-i686-make-default
- .core-defs
# MacOS 64-bit
libretro-build-osx-x64:
extends:
- .libretro-osx-x64-make-default
- .core-defs
# MacOS ARM 64-bit
libretro-build-osx-arm64:
extends:
- .libretro-osx-arm64-make-default
- .core-defs
################################### CELLULAR #################################
# Android ARMv7a
android-armeabi-v7a:
extends:
- .libretro-android-jni-armeabi-v7a
- .core-defs
# Android ARMv8a
android-arm64-v8a:
extends:
- .libretro-android-jni-arm64-v8a
- .core-defs
# Android 64-bit x86
android-x86_64:
extends:
- .libretro-android-jni-x86_64
- .core-defs
# Android 32-bit x86
android-x86:
extends:
- .libretro-android-jni-x86
- .core-defs
# iOS
libretro-build-ios-arm64:
extends:
- .libretro-ios-arm64-make-default
- .core-defs
# iOS (armv7) [iOS 9 and up]
libretro-build-ios9:
extends:
- .libretro-ios9-make-default
- .core-defs
# tvOS
libretro-build-tvos-arm64:
extends:
- .libretro-tvos-arm64-make-default
- .core-defs
################################### CONSOLES #################################
# PlayStation Vita
libretro-build-vita:
extends:
- .libretro-vita-static-retroarch-master
- .core-defs
# Nintendo GameCube
libretro-build-ngc:
extends:
- .libretro-ngc-static-retroarch-master
- .core-defs
# Nintendo Wii
libretro-build-wii:
extends:
- .libretro-wii-static-retroarch-master
- .core-defs
# Nintendo WiiU
libretro-build-wiiu:
extends:
- .libretro-wiiu-static-retroarch-master
- .core-defs
# Nintendo Switch
libretro-build-libnx-aarch64:
extends:
- .libretro-libnx-static-retroarch-master
- .core-defs

12
.gitmodules vendored
View File

@ -1,6 +1,6 @@
[submodule "win32-deps"]
path = win32-deps
url = https://github.com/visualboyadvance-m/win32-deps.git
[submodule "third_party/googletest"]
path = third_party/googletest
url = https://github.com/google/googletest.git
[submodule "dependencies"]
path = dependencies
url = https://github.com/visualboyadvance-m/dependencies.git
[submodule "vcpkg"]
path = vcpkg
url = https://github.com/Microsoft/vcpkg.git

View File

@ -1,96 +1,82 @@
---
cache: ccache
dist: xenial
language: cpp
services: xvfb
sudo: required
services:
- xvfb
matrix:
fast_finish: true
include:
- env: BUILD_ENV=ubuntu-bionic XVFB_RUN=1
dist: bionic
# - env: BUILD_ENV=utf8 XVFB_RUN=1
# dist: bionic
# - env: BUILD_ENV=nostl XVFB_RUN=1
# dist: bionic
- env: BUILD_ENV=ubuntu-xenial XVFB_RUN=1
- env: BUILD_ENV=ubuntu-xenial-minimal INSTALLDEPS_ARGS="--no-openal --no-ffmpeg" XVFB_RUN=1
- env: BUILD_ENV=ubuntu-xenial XVFB_RUN=1 CC=clang CXX=clang++
- env: BUILD_ENV=ubuntu
language: cpp
os: linux
dist: trusty
before_script:
- ./installdeps
script:
- mkdir build
- cd build
- cmake .. -DENABLE_SDL=ON -DENABLE_OPENAL=ON
- make -j2
- xvfb-run ./visualboyadvance-m --help
cache:
directories:
- "$HOME/.ccache"
- env: BUILD_ENV=mingw-w64
language: cpp
os: linux
dist: trusty
before_script:
- ./installdeps MinGW-w64-x86_64
script:
- mkdir build
- cd build
- /usr/lib/mxe/usr/bin/x86_64-w64-mingw32.static-cmake .. -DENABLE_SDL=ON -DENABLE_OPENAL=ON
- make -j2
cache:
directories:
- "$HOME/.ccache"
- env: BUILD_ENV=mingw-w32
language: cpp
os: linux
dist: trusty
before_script:
- ./installdeps MinGW-w64-i686
script:
- mkdir build
- cd build
- /usr/lib/mxe/usr/bin/i686-w64-mingw32.static-cmake .. -DENABLE_SDL=ON -DENABLE_OPENAL=ON
- make -j2
cache:
directories:
- "$HOME/.ccache"
- env: BUILD_ENV=libretro
- env: BUILD_ENV=libretro CC=clang CXX=clang++
language: cpp
os: linux
dist: trusty
before_install:
- sudo apt-get -qqy update
- sudo apt-get -qqy install build-essential ccache
script:
- cd src/libretro
- make -j2 CXX="ccache g++" CC="ccache gcc"
cache:
directories:
- "$HOME/.ccache"
- env: BUILD_ENV=mac
language: cpp
os: osx
osx_image: xcode12
install: export PATH="/usr/local/opt/ccache/libexec:$PATH"
before_install:
- |
case "$BUILD_ENV" in
mingw-w64 )
ARG=MinGW-w64-x86_64
CMAKE=/usr/lib/mxe/usr/bin/x86_64-w64-mingw32.static-cmake
PATH="$PATH:/usr/lib/mxe/usr/bin"
;;
mingw-w32 )
ARG=MinGW-w64-i686
CMAKE=/usr/lib/mxe/usr/bin/i686-w64-mingw32.static-cmake
PATH="$PATH:/usr/lib/mxe/usr/bin"
;;
* )
CMAKE=cmake
;;
esac
- |
if [ "$BUILD_ENV" != libretro ]; then
./installdeps $INSTALLDEPS_ARGS $ARG
DIR=build
else
DIR=src/libretro
fi
before_script:
- |
if [ -n "$ENABLE_SDL" ]; then
CMAKE_ARGS="$CMAKE_ARGS -DENABLE_SDL=ON"
fi
case "$BUILD_ENV" in
utf8|nostl)
sudo apt-get -y install stow libwxgtk3.0-gtk3-dev
(
cd /
sudo curl -LO 'http://cachemiss.com/files/wxWidgets-gtk3-'"$BUILD_ENV"'-3.0.5.tar.gz'
sudo tar zxvf wxWidgets-gtk3-"$BUILD_ENV"-3.0.5.tar.gz
cd /usr/local/stow
sudo stow wxWidgets-gtk3-"$BUILD_ENV"-3.0.5
)
export LD_LIBRARY_PATH=/usr/local/lib
CMAKE_ARGS="$CMAKE_ARGS -DwxWidgets_CONFIG_EXECUTABLE=/usr/local/bin/wx-config -DWXRC=/usr/local/bin/wxrc"
;;
esac
script:
- mkdir -p -- "$DIR"
- cd -- "$DIR"
- if [ "$BUILD_ENV" != libretro ]; then $CMAKE $CMAKE_ARGS ..; fi
- if [ "$BUILD_ENV" != libretro ]; then ninja; else make; fi
- if [ "$BUILD_ENV" != libretro ]; then DESTDIR=/tmp/VBAM ninja install; fi
- |
if [ "$BUILD_ENV" = mac ]; then
./$PRGNAM.app/Contents/MacOS/$PRGNAM --help
elif [ -n "$XVFB_RUN" ]; then
xvfb-run -a ./$PRGNAM --help
fi
ctest -V
env:
global:
- CMAKE_ARGS="-G Ninja"
- ENABLE_SDL=1
- MAKEFLAGS="-j2"
- PRGNAM=visualboyadvance-m
before_script:
- ./installdeps
script:
- mkdir build
- cd build
- cmake .. -DENABLE_SDL=ON -DENABLE_OPENAL=ON
- make -j2
- ./visualboyadvance-m.app/Contents/MacOS/visualboyadvance-m --help
cache:
directories:
- "$HOME/.ccache"
notifications:
webhooks:

11
.tx/config Executable file → Normal file
View File

@ -1,10 +1,9 @@
[main]
host = https://www.transifex.com
[o:bgk:p:vba-m:r:wxvbam]
file_filter = po/wxvbam/<lang>.po
source_file = po/wxvbam/wxvbam.pot
type = PO
source_lang = en
minimum_perc = 0
[vba-m.wxvbam]
file_filter = po/wxvbam/<lang>.po
source_file = po/wxvbam/wxvbam.pot
source_lang = en
type = PO

View File

@ -4,437 +4,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [2.1.11] - 2024-09-15
==========================
* 3eea90af - build: set BUILD_TESTING=OFF when not git checkout [rkitover]
* b3952d74 - build: fix ENABLE_LIRC=ON [rkitover]
* f264e7f8 - Fix Help -> Translations URL [rkitover]
* 61f427de - Write shortcuts in the proper section (#1335) [Steelskin]
* d619ee2b - build: fix installing GoogleTest [rkitover]
* 26207038 - Update WinSparkle to 0.8.1 and add ARM64 [rkitover]
## [2.1.10] - 2024-09-08
==========================
* 7f06428d - Disable dialog position save/restore on wxGTK (#1331) [Steelskin]
* e4ef4aa6 - Propagate key events (#1323) [Steelskin]
* e2cf6ecb - Add option to mute sound during speedup [rkitover]
* d516683a - build: fix for wx using GTK2 [rkitover]
* 834c7de8 - build: update macOS builder dists [rkitover]
* fc82e062 - build: do not build SDL bin on Windows or macOS [rkitover]
* d543784a - [UserInput] Filter key events globally [steelskin]
* 902c6c8e - [UserInput] Only process shortcut commands once [steelskin]
* b7765092 - [bindings] Set default shortcut for recent file 3 [steelskin]
* cc65ef28 - doc: add system requirements to README.md [danialhorton]
* 32627f6b - [Dialogs] Save and restore dialog positions [steelskin]
* 41952d06 - build: update macOS linker tool to 1.5 [rkitover]
* 0c39a5ba - build: override FindGettext to not update po files [rkitover]
* 1b77d659 - build: update macOS build to ffmpeg 7.0 [rkitover]
* 8d08223d - build: fix compatibility with older ffmpeg [rkitover]
* af6028a9 - build: fix build for nix on macOS [rkitover]
* b52edf52 - build: fix building on macOS with Homebrew [rkitover]
* 6766b9ca - build: fix ffmpeg 7.x compat [rkitover]
* 795f25bb - build: fix nix deps for OpenGL [rkitover]
* 647be137 - gba: set cpsr=spsr when switching to FIQ mode [40356555+Aikku93]
* 8abe3e79 - build: remove -lgcc from static link flags [rkitover]
* f4835674 - [Audio] Rework audio devices enumeration [steelskin]
* 775a571f - build: fix detecting Visual Studio default vcpkg [rkitover]
* 64abd3e8 - [Audio] Remove manual memory allocations [steelskin]
* 047ad277 - [Dialogs] Prevent viewers from causing a crash [steelskin]
* 045c98d8 - build: only use -Werror=lto-type-mismatch on gcc [rkitover]
* 3518dc6a - build: fix LTO on Linux [rkitover]
* cc9a03ce - Add toggle: SDL GameController mode for joysticks [rkitover]
* 8576733c - [Build] Remove lingering references to OpenAl [steelskin]
* 05561922 - build: fix MSYS2 check [rkitover]
* d9432ebb - build: fix build on MINGW{64,32}/UCRT64 on MSYS2 [rkitover]
* f57cad67 - build: fix static linking on MSYS2 CLANG64 [rkitover]
* 23e15734 - build: set wxWidgets_DIR with vcpkg [rkitover]
* 98b51910 - [Build] Remove ENABLE_NLS, fix TRANSLATIONS_ONLY [steelskin]
* a565cea8 - [Build] Remove the OpenGL check [steelskin]
* f96e42fe - build: cmake refactor and improvements [Steelskin]
* 07e49025 - Fix most remaining release warnings (#1243) [Steelskin]
* 18b97b43 - Fix various build warnings (#1242) [Steelskin]
* 13a16eb7 - Fix various warnings in filters and headers (#1241) [Steelskin]
* f46da1c5 - build: remove our version of FindSDL2.cmake [rkitover]
* 404e9a1a - build: add clang to ./installdeps for MSYS2 [rkitover]
* 613bd403 - Make menu more reasonably organized (#1230) [wwrustc]
* 215e3c5a - build: use find_program() to find powershell [rkitover]
* e5aa685f - build: don't use wx utils as UNIX cmds on Windows [rkitover]
* 9e4c8e17 - build: fix gentoo dependency namespaces [68k]
* 5f853b99 - Update metainfo.xml to new standards [jhonny.oliveira]
* e7d135db - Update links to new domain visualboyadvance-m.org [rkitover]
* 60fc096f - build: add libglu-devel for solus in installdeps [rkitover]
## [2.1.9] - 2024-02-03
=======================
* 84b0a3e3 - Remove SDL sound driver [rkitover]
* 2ad7dd1a - Fix wav audio recording [40356555+Aikku93]
* 23ef8ef0 - Dialog appearance improvements + link warning [zachbacon]
* a0452701 - build: don't fseeko64()/ftello64() on musl libc [rkitover]
* 9e9fe812 - visualboyadvance-m.metainfo.xml: add screenshots to the metainfo [zachbacon]
## [2.1.8] - 2023-12-13
========================
* beab0881 - Store the PC register at the appropriate offset [steelskin]
* bf2452aa - Resize GameArea after MainFrame initialization [steelskin]
* 71ca0fb2 - Properly hide the status bar at startup [steelskin]
* 7e1afcd3 - Fix reading joystick hat config values [rkitover]
* 32581966 - Link: Fix menu not refreshing correctly [74248064+nuive]
## [2.1.7] - 11.09.2023
=========================
* aca206a7 - Launch on xwayland under Wayland if no EGL [rkitover]
* 93a24bee - Disable mirroring for ROMs > 32MB [rkitover]
* 0f4ec575 - [Build] Fix the NO_LINK build [steelskin]
* 803ab352 - [GB] Save MBC7 EEPROM data to `gbRam` [steelskin]
* 24b6ac5a - [GBA] Implement missing Thumb instruction [steelskin]
* 14a4b6f8 - [dialogs] Move JoypadConfig to its own class. [steelskin]
## [2.1.6] - 09.07.2023
=========================
* 7561ca97 - Fix Discord streaming for OpenGL [danialhorton]
* e26f8073 - [bios] Fix lz77 and add BIOS_SndDriverVsyncOn [steelskin]
* d1f65000 - Refactor accelerator / global shortcuts handling [steelskin]
* fda429fc - [GBA] Do not draw BG tiles from outside of BG VRAM [steelskin]
* 5aa3ea92 - Properly initialize wxAcceleratorTable [steelskin]
* 0e29be87 - Support multiple RAM sizes for MBC7 [steelskin]
* 75b79d91 - Change MBC7 reported RAM size to 512 bytes [steelskin]
* 36e88faf - Fix dsound looping when moving/resizing window [rkitover]
* 019fcda9 - Sanitize and improve the GB header parsing (#1109) [Steelskin]
* 7005b928 - Sanitize allocations in the Game Boy emulator (#1105) [Steelskin]
* 3cef52b7 - Fix pause/next-frame [rkitover]
* d3f8cc17 - Option to suspend the X11 screensaver when running [2306079+multiSnow]
* df819598 - builder: update macOS build to 10.10, Wx 3.2.2.1 [rkitover]
* 1ab46f70 - Update SIOCNT when the link driver is disconnected [steelskin]
* 1d7e8ae4 - build: fix build with new OpenAL [rkitover]
* a9284b3d - workaround for Stuart Little 2 crashing when set to none [danialhorton]
* 166299cd - Implements Read/Writes for HUC3 [danialhorton]
* 640ce453 - Change SOUND_CLOCK_TICKS to 280896 cycles - ~1074 samples per frame [reallibretroretroarch]
* f1d3f631 - Fix automatic dynamic frame skipping [steelskin]
* d756f671 - translations: fix some source strings [stanley.udr.kid]
* 91873254 - Add INI file versioning [steelskin]
* 7d9cb2b5 - Default GBA LCD filter to off. [rkitover]
* be1e5ca1 - Check for wx < 3.2.2 for EGL move fix backport [rkitover]
* 1fb18b32 - Rename appdata to metainfo [polynomial-c]
* ca7ae336 - Fix regression in bios, port DMA fix from libretro [danialhorton]
* b34448c9 - Fix record/play dialogs for native recordings [danialhorton]
* 6307348c - build: support MSVC arm64 cross build on x86 [rkitover]
* 87bdc93e - Revert "translations: use %% instead of percent" [rkitover]
* ab4ae96e - Clarify/set condition: wayland && !wayland_egl [rkitover]
* 8e4acfc9 - Fix build w/wxUSE_GLCANVAS_EGL=0, on Fedora [rkitover]
* 3c41b68d - Fix the Windows ARM64 build [steelskin]
* 22578d02 - Increase MAX_CART_SIZE from 32MiB to 128MiB [rkitover]
## [2.1.5] - 2022-12-15
=======================
* ea2a929f - Backport 800d6ed69b from wx to fix Wayland EGL pos [rkitover]
* c40a1417 - Write vsync toggle msg to debug log not OSD [rkitover]
* 5d2dd01e - Call Layout() after DrawingPanel OnSize event [rkitover]
* da686a48 - Reinit panel on vsync toggle. [rkitover]
* ec27885c - Support EGL VSync on Wayland. [rkitover]
* c27d384a - Enable GL on Wayland for wx 3.2+, no vsync. [rkitover]
* c249115b - build: set -mtune=generic [rkitover]
* 297d7c06 - [hidpi] Use wxWidgets 3.2 on Windows [steelskin]
* 0d86432a - [hidpi] Implement full HiDPI support [steelskin]
* 69d24fb5 - [build][msvc] Fix debug information and set hidpi support [steelskin]
* 90fc3e12 - Default CTRL+I to change interframe blender [rkitover]
* a57d81e1 - Show name of interframe blender not num in OSD [rkitover]
* 13c558ac - Disable wireless link type [rkitover]
* 639003a8 - Show pixel filter name not number on cycle [rkitover]
* 236cffb4 - Make another adjustment to glXQueryExtensions [rkitover]
* 643ec0f7 - Pass DefaultScreen(display) to glXQueryExtensions [rkitover]
* 60d7ead5 - Fix menu state after playing a movie [laqieer]
* d2fee771 - Add VBA Movie Version 2 [laqieer]
* 3f2d3c13 - Remove manual joystick polling [steelskin]
* 7726d26f - Enable full optimizations and fix x86 builds [danialhorton]
* 73223445 - MSVC opt /fp:fast /Oi, intrinsic sqrt() w/ XBRZ. [rkitover]
* 972f1513 - Enable GB colorization hack support in GUI. [danialhorton]
* 1741fa32 - Fix autosaveloadcheat and rename pref [danialhorton]
* a31a7a30 - in Wx, the Option is Enable MMX, make the variable also enableMMX and set its default to on. [danialhorton]
* 983ea451 - Flash : Erased memory is FFh-filled [negativeExponent]
* 18e387d1 - Fix Flash chip's erase operation: erased memory is FFh-filled, not zero-filled. [laqieer]
* c05056ab - HuC3: Update [negativeExponent]
* 93084990 - HuC3: Refactoring to avoid breaking savestates [negativeExponent]
* 05a046e7 - HuC3: Enable battery save, update RTC support [negativeExponent]
* 70477dcd - GBA:Fix serial emulation if compiled with NO_LINK [negativeExponent]
* 15bcad13 - GB:Fix serial emulation when compiled with NO_LINK [negativeExponent]
* 025f3079 - GBA:Fix a few memory read/write issues [negativeExponent]
* 210e79bb - Add descriptions for the 'Interframe Blending' and 'LCD Color Filter' options [jrb22x]
* 8a3456f8 - Default to not change battery on state load. [rkitover]
* b50ff858 - add a missing break in half word reads [danialhorton]
* 064fa7b0 - Fix SDL audio delay [Clownacy]
* 7db3c817 - Fixed SDL audio using the wrong audio specification [Clownacy]
* cb0933bf - Stop changing plane ptrs in rec. audio frames. [rkitover]
* 80634683 - Force a panel update when configuring bilinear. [briansrls]
* 6a714281 - Differentiate between SDL joy index/instance_id. [rkitover]
* 11693d83 - Clean up GB MBC30 check. [rkitover]
* 020daad8 - Fix joy accels when emulation is paused. [rkitover]
* def5d3e4 - Stop timer when game is loaded again. [rkitover]
* e0816b0e - Fix weird input/buttons memory leak. [edenisfa]
* 7031c1d1 - [LINUX,WINDOWS] Key/Joy background input. [edenisfa]
* 84f3e8ce - Allow joystick background input. [edenisfa]
* 40741580 - Add GUI cmd line option for config file. (#724) [Steelskin]
* c169420f - Turbo/throttle config and DirectSound fixes. [rkitover]
* 378c9493 - Fix joystick config when game is loaded. [rkitover]
* 95213a6d - GB: Only use mapperLastTime to see if RTC data was loaded [negativeExponent]
* 86fcffef - GB: Add support for 4MB MBC30 [negativeExponent]
* 2f9933ae - GBA BIOS: ArcTan/ArcTan2 fixes for HLE bios [negativeExponent]
* d9732f68 - Fix clock cycle count for MUL, MLA instructions... (https://github.com/libretro/vba-next/commit/b91f39c787cc99ace97546cb94985f3b658c8b57) - backport Fix clock cycle count for some arm/thumb instructions (https://github.com/libretro/vba-next/commit/5243b2d8064dd2145888ced7cbfe127594ecf6db) - backport Fix base cycle count for MUL, MLA series (https://github.com/libretro/vba-next/commit/b91f39c787cc99ace97546cb94985f3b658c8b57) [negativeExponent]
* c07d5b65 - Fix vram 16/32 bit unaligned reads(backport https://github.com/libretro/vba-next/commit/7f18771165dd4a6d71a598c51d91668920572eaa) [negativeExponent]
* 18c2ea61 - Further fixing Multi Buffer formatting. [briansrls]
* 1e569300 - Addressing audio plugin crash [briansrls]
* 9c314a15 - Use proper string `"wglGetExtensionsStringEXT"`. [edenisfa]
* 3ba05295 - Improve BIOS Math tests score from 425 to 625. [edenisfa]
* 6f2e320d - Improve clock cycle count for THUMB operations. [edenisfa]
* 9e537a8f - Improve cycle count for MUL, MLA. [edenisfa]
* 306f92f5 - Check game kbd input with wxGetKeyState() again. [rkitover]
* 6b257d52 - Avoid override of variable `throttle` for turbo. [edenisfa]
* bd2483ca - Allow changing connection type without restart. [edenisfa]
* d379a076 - Decrease mouse sensitivity for menu hiding. [rkitover]
* 0c5ee994 - Fix PNG capture screen. [edenisfa]
* 1347026d - Turbo config refactor followup. [rkitover]
* 1bced474 - Codesign fix for mac. [rkitover]
* 07064c87 - [Windows,MacOS] Auto-updater refactoring. (#639) [denisfa]
* 09e8da43 - Joystick refactor pt. Deux: Support Joysticks. [rkitover]
* 504ca08b - Hide menubar + minor UI refactor. [rkitover]
* 2868c1b7 - Fix changing aspect ratio option. [rkitover]
* 045e95ab - GB: Support 4MiB MBC30 ROM bank select. [rkitover]
* 0b14e9f8 - [WINDOWS] Add function to open unicode files. (#644) [denisfa]
* 8e3978b3 - Speedup/Turbo/Throttle fixes. [rkitover]
* 166cf446 - Disable menu LCD filter unless playing GB or GBA. [edenisfa]
* 06001069 - Init systemColorMaps after output module init. [edenisfa]
* cd029ae6 - Fix video recording with frame skip enabled. [edenisfa]
* 008aecde - [LINUX] Fix display of `RGB` values on viewers. [edenisfa]
* 834d1537 - Fix accel shortcuts when using some menu options. [edenisfa]
* 994726dd - Do not pause while opening configuration windows. [edenisfa]
* 54335dc6 - [WINDOWS] Fix weird WX errors messages. [edenisfa]
* 7bac34ed - Remove duplicate variable `winFlashSize`. [edenisfa]
* 8d62a790 - Change default options for GB. [edenisfa]
* 99b66e13 - Expose LCD filter for GBA and GB color saturation. [edenisfa]
* c789020e - Fix `Save` button on OAM Viewer for GB and GBA. [edenisfa]
* dcaa1b9a - Fix `Save` button on Tile Viewer for GB and GBA. [edenisfa]
* d05e8fc1 - Make AGBPrint output to our Logging. [edenisfa]
* abb82341 - Allow binding specific server IP. (#633) [rkitover]
* 6c64db07 - cmake: Windows codesigning refactor. [rkitover]
* 4f1a351d - Try to configure vsync for multiple options. [edenisfa]
* ed8a9af2 - Use proper functions and checks for OpenGL VSYNC. [edenisfa]
* 6092082e - Fix Save Failed error for Super Monkey Ball Jr. [54053706+negativeExponent]
* f1099a21 - Check return value of soundInit(). [rkitover]
* 410ede54 - Check for null pointer in soundReset(). [alexjnewt]
* 9d1d707c - Limit ROM size to 32 MiB. [negativeExponent]
* fd319d21 - GB: Check header for a valid ROM file. [negativeExponent]
* 513af13d - Replace `libpng` code for `stb_image` one. [edenisfa]
* 8f48c1f0 - Fix weird `wxWidgets>=3.0` error message. [edenisfa]
* 2f065382 - Enable XAudio2 for Windows vcpkg build. [rkitover]
* a3203770 - Fix: a issue with loading e-Reader dot code (#608) [sony.pcv.s520]
* 83614290 - Turn on winsparkle update checking support. [rkitover]
* 4aab08c4 - Set link timeout default to 500ms, fix prev. dflt. [rkitover]
* 136c094f - Add option to set link network port. [rkitover]
* f69febfd - Add `.wav` support for sound recording. [edenisfa]
* 6a8a9e62 - Fix integer overflow in cheatsImportGSACodeFile length check. [zack.ref]
* b50d4845 - GBA: Fix crash when new size is larger than rom size after soft-patching [negativeExponent]
* 9e1a63af - support for patches in BPS format [ArtiiP]
* 72d0725b - Allow game window to resize on-the-fly when enabling/disabling borders [negativeExponent]
* 225e4dc9 - Remove top border black line when using filters. [edenisfa]
* 0535d5c7 - Optimize CRC32. [mudlord]
* 4bc9bb84 - Implement joystick rumble. #522 [rkitover]
* 384f4487 - Fix key accel overriding menus and dialogs. [edenisfa]
* af0de1c4 - xbrz: fix inline asm check [rkitover]
## [2.1.4]
=======================
* c93e017d - builder: minor changes to support mac 32 bit (4 days ago)
* c1636d1b - builder: fixes for ffmpeg + misc. (4 days ago)
* aec23e35 - builder: re-enable ffmpeg, update dists (2 weeks ago)
* 806dd7da - Fix circular `--config` for SDL port. (7 days ago)
* 1aa8afb4 - Drop dead code entirely. (7 days ago)
* 531172c4 - Fix displaying of link menu when `ENABLE_LINK=NO`. (2 weeks ago)
* 07107096 - [Windows] Fix crash when setting weekly updates. (2 weeks ago)
* efa09bdb - Add faster sqrt code for xBRZ filters. (2 weeks ago)
* 10f5576e - Fix config file when removing system accels. (3 weeks ago)
* 1c6b0168 - [Windows] Fix remaining UTF-8 issues. (3 weeks ago)
* a2f3126e - transifex pull (3 weeks ago)
* 1e9d1675 - builder: pause before codesigning for win targets (3 weeks ago)
* 0af5965e - builder: work on linux static binary (3 weeks ago)
* 33c43e3a - add -p:BuildInParallel=true to appveyor.yml (3 weeks ago)
* 61141ebd - add -p:BuildInParallel=true to VS instructions (3 weeks ago)
* 9ee6b54a - cmake: remove invalid opt /std:c++11 for MSVC (3 weeks ago)
* 0f2c8cab - win: check APPDATA if LOCALAPPDATA is not found (3 weeks ago)
* 32fbfec4 - transifex pull (3 weeks ago)
* cc516229 - transifex push/pull (4 weeks ago)
* 528c37f9 - Allow "Browse" to be translated. (4 weeks ago)
* d8c981fb - Fix toggles for video/audio layer options on menu. (4 weeks ago)
* c0f96425 - Show all commands available on menu. (4 weeks ago)
* 51fa150f - Adjust MMX menu variable and position. (4 weeks ago)
* 27b038b3 - Show messages about operations of state slot. (4 weeks ago)
* 2e248457 - Allow translation of the words `Open` and `Quit`. (4 weeks ago)
* 54991c5b - Add extra keys default input when using GUI. (4 weeks ago)
* b358c051 - Fix compilation issue when `ENABLE_DEBUGGER=Off`. (4 months ago)
* 2a2be953 - builder: msys2 fixes (4 weeks ago)
* f1438e0f - Check ASAN support when `ENABLE_ASAN=ON`. (4 weeks ago)
* ade64db7 - transifex pull (4 weeks ago)
* 8b347050 - cmake: check for ffmpeg >= 4.0.4 (4 weeks ago)
* 0b9c7710 - travis: more ubuntu dists, fix mac cache (5 weeks ago)
* d9e4a087 - build fixes: ffmpeg, xbrz, travis, C++ version (5 weeks ago)
* 23224fba - update factory reset instructions in README.md (5 weeks ago)
* 381a7bfe - /std:c++latest for MSVC, fix bool flip, warn opts (5 weeks ago)
* 234f1e9b - Update to xBRZ `1.7`. (6 weeks ago)
* 290012d1 - transifex pull (6 weeks ago)
* 06a9d786 - Allow UPS patch for GBA games. (6 weeks ago)
* 1949cdb3 - transifex push/pull (6 weeks ago)
* 03121c69 - Add support for autohold buttons. (6 weeks ago)
* e87213e3 - Fix indentation. (6 weeks ago)
* cf47942f - Fix Autofire {L,R}. (6 weeks ago)
* 4993cb88 - remove tea-ci .drone.yml and installer.nsi (6 weeks ago)
* d9a7e0c9 - cmake: auto-detect sfml, ffmpeg and openal (6 weeks ago)
* c64dd259 - Update README.md (6 weeks ago)
* 8ceef90f - fix appveyor visual studio build (6 weeks ago)
* a8b7b72d - transifex pull (6 weeks ago)
* f5eabb35 - builder: disable LTO on 64 bit mingw (6 weeks ago)
* fc2eb38f - Fix behaviour of `Tools` > `Memory Viewer` (#486) (6 weeks ago)
* 2958af01 - builder: mingw improvements + misc. (6 weeks ago)
* 3923b28f - transifex pull/push (6 weeks ago)
* 51f61a3a - Merge remote-tracking branch 'vbam-libretro/master' (6 weeks ago)
* 6bdd6d1b - Merge pull request #77 from negativeExponent/fix_cheat_search (7 weeks ago)
* dc8d36a0 - minor fix for stl wx builds (7 weeks ago)
* 51a4f74b - Merge remote-tracking branch 'vbam-libretro/master' (7 weeks ago)
* 9ccdeac3 - Add missing break; lines for switch statements (7 weeks ago)
* b8afa8c5 - Merge pull request #76 from RobLoach/intl (7 weeks ago)
* a17eb471 - Merge branch 'master' of github.com:fpscan/vbam-libretro into intl (7 weeks ago)
* 9b043daa - libretro: Update core options API (7 weeks ago)
* 6b18c1f9 - Fix warning about frames left in queue. (8 weeks ago)
* f5b19475 - [IDEA] Fix recording when using `speedup/turbo`. (8 weeks ago)
* 738494a2 - Support all sample rate available on GUI. (8 weeks ago)
* aa3ecaf7 - Add new output formats for recording audio/video. (9 weeks ago)
* 5848feae - Fix video/audio recording. (2 months ago)
* 9e3c2615 - Update libretro_core_options.h (7 weeks ago)
* 6c60ac33 - Turkish Language option (7 weeks ago)
* d92ca688 - Merge pull request #74 from retro-wertz/update (7 weeks ago)
* ad43b32b - Fix "index out of bounds" runtime error (7 weeks ago)
* 36f3a739 - Merge pull request #73 from retro-wertz/libretro_cleanup (8 weeks ago)
* 82e723a5 - MBC3: Update mapper to check if RTC is present before running RTC functions (8 weeks ago)
* 03184dd5 - libretro: Use GB RTC data when available (8 weeks ago)
* b3744b3b - Simplify GB border core option (8 weeks ago)
* 9757a880 - Core options cleanup and a few readability-related updates (8 weeks ago)
* cfb03d8b - Set default keybinding when key does not exist. (9 weeks ago)
* 1ef09126 - Merge pull request #72 from retro-wertz/enable_rtc (8 weeks ago)
* 496b372d - Allow enabling GBA RTC regardless of rom types (8 weeks ago)
* 4dbdf87d - Merge pull request #71 from retro-wertz/patch-3 (8 weeks ago)
* bb109544 - Update Makefile (8 weeks ago)
* 3e640443 - Merge pull request #70 from retro-wertz/update_makefiles (8 weeks ago)
* 98313652 - Update Makefile (8 weeks ago)
* 34de0579 - Merge pull request #67 from retro-wertz/update_makefiles (8 weeks ago)
* 71e4b7b3 - Merge pull request #69 from retro-wertz/master (8 weeks ago)
* d9f8396c - Cleanup (8 weeks ago)
* 9a134497 - Update Makefiles (8 weeks ago)
* 38b7613e - Setting up basic appveyor (9 weeks ago)
* 408cab71 - Merge pull request #66 from retro-wertz/libretro (9 weeks ago)
* d8982881 - Automatically hide some core options depending on rom image type (9 weeks ago)
* c3edd6d4 - Merge pull request #65 from retro-wertz/libretro (9 weeks ago)
* 2084a63e - Update GB/GBC memory maps (retro_memory_descriptors) (9 weeks ago)
* 90b051ee - Update libretro_core_options.h (9 weeks ago)
* a727e222 - GB: Rename this variable to isolate from a global variable of the same name (10 weeks ago)
* 0d423b98 - Cleanup GB palette struct and update retro_get_memory_data/size (10 weeks ago)
* bc80ecdb - UtilRetro.cpp: Cleanup (10 weeks ago)
* 855db11d - Fix wxWidgets assertion error on `Logging...` menu. (10 weeks ago)
* c886b6a1 - remove wrong and unnecessary #define (10 weeks ago)
* 38561b57 - Merge remote-tracking branch 'vbam-libretro/master' (2 months ago)
* 770b9c1c - Add left analog bind to D-PAD for joystick. (2 months ago)
* 6de45d4e - Set default binding for keyboard. (3 months ago)
* 78bbe148 - Add individual clear buttons for input config. (3 months ago)
* 53002e54 - Use hats from joystick as default D-PAD. (3 months ago)
* 57b7ddf5 - Fix small memory leak. (3 months ago)
* 060da968 - [LINUX] Add option to disable the online updater. (3 months ago)
* dbb5914f - Show which BIOS file is currently selected. (3 months ago)
* 76756ef9 - Fix key shortcuts for toggle menu actions. (3 months ago)
* 4622f1b8 - Whitespace fix. (3 months ago)
* 3dc738b5 - Set default keys for input on first run. (3 months ago)
* 9bc8f33c - Disable using volume {+,-} actions in main menu. (3 months ago)
* d1fcffc8 - Merge pull request #63 from retro-wertz/fix_gba_siocnt (2 months ago)
* 7df7b190 - Merge pull request #64 from retro-wertz/patch-2 (2 months ago)
* 7f105da3 - Update README.md (2 months ago)
* 53ce6fb0 - libretro: add SIO Control register (GBA) (2 months ago)
* 2e96f59e - Merge pull request #62 from retro-wertz/gb_timing_updates (2 months ago)
* e50812dc - GB: input, audio, video timing updates (2 months ago)
* 1532f555 - GB: Reduce input lag by 1 frame, video and audio timing updates... (2 months ago)
* f09a9aa9 - builder: add python3 to msys2 deps (2 months ago)
* 2fcad3f8 - joysticks: hack to better support 360 triggers (3 months ago)
* 352eb149 - Merge remote-tracking branch 'vbam-libretro/master' (3 months ago)
* 2e97b27f - Use --config option to load configuration file. (3 months ago)
* bdd43868 - Merge pull request #61 from retro-wertz/gb (3 months ago)
* bd5ba431 - Cleanup: Remove previous core option struct and unused variables etc (3 months ago)
* aac30c72 - Add GB Color Correction core option (3 months ago)
* 02a7a48b - GB: Fix selected palette not applied when loading content... (3 months ago)
* 8462ca76 - Merge pull request #59 from retro-wertz/gb (3 months ago)
* 1fa78e69 - Fix android build (3 months ago)
* 6dcf016d - GB: Allow support for colorizer patched games - a new core option is provided since enabling this support means allowing invalid access to vram and palette - works in GBC/GBA hardware mode only (3 months ago)
* 85bd86cf - GB: Send LCD interrupt only if there is no INT 48h signal (3 months ago)
* b147e912 - Merge pull request #57 from retro-wertz/sync (3 months ago)
* d808297b - Fix crash caused by incorrect variable index for analog sticks (3 months ago)
* 7e882898 - libretro: Add core option sublabels (3 months ago)
* ce11403b - builder: updates for mingw (3 months ago)
* c5e6a340 - Libretro: Update GBC memory map (3 months ago)
* fa45ccdf - builder: fix command(), update c2man url (3 months ago)
* e64b9904 - builder: fix msys2 (3 months ago)
* 58022078 - builder: make zip + sig on win + minor changes (3 months ago)
* 296255d4 - handle SDL joystick query errors #451 (3 months ago)
* 95658f57 - transifex sync (3 months ago)
* 86c4dc7d - transifex sync (3 months ago)
* bcc8b540 - transifex sync (3 months ago)
* 7569242f - Fix pause behaviour with `Pause when inactive`. (3 months ago)
* 030740ee - Fix some memory leak. (3 months ago)
* 8ea607e1 - remove translation from joystick keys (3 months ago)
* cec32a61 - travis: mac: disable --help check, it segfaults (3 months ago)
* f54dd25b - travis: fix gettext on mac + brew (3 months ago)
* e2f06210 - update Visual Studio support (3 months ago)
* 91501bec - Fix small memory leak. (3 months ago)
* c366907f - Temporary fix for #65. (3 months ago)
* d585a610 - followup on kbd trans issues fix in 30b92724 (3 months ago)
* eaf1ad24 - Merge remote-tracking branch 'vbam-libretro/master' (3 months ago)
* 30b92724 - hopefully fix kbd control translation issues (3 months ago)
* 90b3f354 - Add hotkeys for changing sizes (1x ... 6x). (3 months ago)
* fa77010f - Fix pause toggle keybinding when unmuting. (3 months ago)
* 8cb42003 - Merge pull request #56 from webgeek1234/master (3 months ago)
* 8b8efa1b - fix key shortcuts for save/load states (3 months ago)
* 9fa20b49 - joystick cleanups #444 (3 months ago)
* 684b1bb7 - fix mem error for config global `homeDir` (3 months ago)
* ccc91fa0 - quick fix for unicode filenames on windows (3 months ago)
* dfa4fec3 - Fix missing shortcuts from key bindings. (4 months ago)
* 69b581f7 - Handle key{bindings,shortcuts} correctly on frame. (4 months ago)
* cec1dbfd - Split configuration for default keys. (4 months ago)
* d655031a - Fix removing multiple system keys shortcuts. (4 months ago)
* 996d5b9d - Do not set these options on `MainMenu.xrc`. (4 months ago)
* 019ab5a7 - Fix "Joybus host invalid; disabling" warning. (3 months ago)
* f6bfe676 - Have better support for maximized window. (4 months ago)
* dcc0afa0 - Fix window size when {en,dis}abling status bar. (4 months ago)
* bf6f2d4a - Change where the config dir is created. (4 months ago)
* 3490620e - travis: use Mac OS 10.14 and Xcode 10.2.1 (4 months ago)
* b0ec8469 - fix stuck keys on ubuntu and on focus loss #142 (4 months ago)
* 3d57750c - Follow-up work on #142. (4 months ago)
* 055b7c4d - libretro: jni: Switch to clang compiler in preparation for ndk r20 (4 months ago)
* 2e1333e1 - regparm is an x86 only attribute, only define it there (4 months ago)
* 500506cb - travis: disable link/SFML for mac (4 months ago)
* 22307de6 - Fix continuous sprinting when using a modifier key as a mapping key (#142). (4 months ago)
* 50459712 - wx: only rename config if new file doesn't exist (5 months ago)
* 0a95486f - Sound.cpp: Update (5 months ago)
* a4eae802 - cmake: use LEGACY OpenGL on FreeBSD only 2fedaa63 (5 months ago)
* 240257a0 - wx: Change max volume from 400 to 200 (5 months ago)
* 57ed465e - builder: better mac automation (5 months ago)
* 15f040f3 - cmake: missing space in wx util function (5 months ago)
* 2fedaa63 - support FreeBSD (5 months ago)
* a0c375b6 - Merge remote-tracking branch 'vbam-libretro/master' (6 months ago)
* c013d499 - Merge pull request #55 from Classicmods/master (6 months ago)
* a8b38681 - remove some old visual studio project files (6 months ago)
* b6bb24e0 - Merge pull request #1 from libretro/master (6 months ago)
* 5012969a - Bump version to 2.1.1 (7 months ago)
* 755f4767 - Fix #52 (8 months ago)
* f87e0850 - added a8a35 (7 months ago)
* 286c8ff4 - Fix #52 (8 months ago)
## [2.1.3] Windows Geometry Fix
=======================
* ac35e37c - fix game geometry on windows (4 hours ago)

File diff suppressed because it is too large Load Diff

View File

@ -1,95 +1,53 @@
{
"configurations": [
{
"name": "x64-static-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"inheritEnvironments": [
"msvc_x64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=x64-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "x64-static-Release",
"generator": "Ninja",
"configurationType": "Release",
"inheritEnvironments": [
"msvc_x64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=x64-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "x64-static-RelWithDebInfo",
"generator": "Ninja",
"configurationType": "RelWithDebInfo",
"inheritEnvironments": [
"msvc_x64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=x64-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "x86-static-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"inheritEnvironments": [
"msvc_x86"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=x86-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "x86-static-Release",
"generator": "Ninja",
"configurationType": "Release",
"inheritEnvironments": [
"msvc_x86"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=x86-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "x86-static-RelWithDebInfo",
"generator": "Ninja",
"configurationType": "RelWithDebInfo",
"inheritEnvironments": [
"msvc_x86"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=x86-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "arm64-static-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"inheritEnvironments": [
"msvc_arm64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=arm64-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "arm64-static-Release",
"generator": "Ninja",
"configurationType": "Release",
"inheritEnvironments": [
"msvc_arm64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=arm64-windows-static -DENABLE_SDL=TRUE"
}, {
"name": "arm64-static-RelWithDebInfo",
"generator": "Ninja",
"configurationType": "RelWithDebInfo",
"inheritEnvironments": [
"msvc_arm64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "-DVCPKG_TARGET_TRIPLET=arm64-windows-static -DENABLE_SDL=TRUE"
}
]
}
{
"configurations": [
{
"name": "x64-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"inheritEnvironments": [
"msvc_x64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "-v",
"ctestCommandArgs": ""
}, {
"name": "x64-Release",
"generator": "Ninja",
"configurationType": "Release",
"inheritEnvironments": [
"msvc_x64"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "-v",
"ctestCommandArgs": ""
}, {
"name": "x86-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"inheritEnvironments": [
"msvc_x86"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "-v",
"ctestCommandArgs": ""
}, {
"name": "x86-Release",
"generator": "Ninja",
"configurationType": "Release",
"inheritEnvironments": [
"msvc_x86"
],
"buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
"installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "-v",
"ctestCommandArgs": ""
}
]
}

View File

@ -1,482 +0,0 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [visualboyadvance-m Developer Manual](#visualboyadvance-m-developer-manual)
- [Issues Policies](#issues-policies)
- [Processing New Issues](#processing-new-issues)
- [Resolving Issues](#resolving-issues)
- [Pull Request and Commit Policies](#pull-request-and-commit-policies)
- [Commit Message](#commit-message)
- [Collaboration on a Branch](#collaboration-on-a-branch)
- [Commits from Maintainers](#commits-from-maintainers)
- [Miscellaneous](#miscellaneous)
- [Debug Messages](#debug-messages)
- [Release Process](#release-process)
- [Certificates](#certificates)
- [Release Commit and Tag](#release-commit-and-tag)
- [64-bit Windows Binary](#64-bit-windows-binary)
- [32-bit Windows Binary](#32-bit-windows-binary)
- [ARM64 Windows Binary](#arm64-windows-binary)
- [macOS Binary](#macos-binary)
- [Final steps](#final-steps)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## visualboyadvance-m Developer Manual
Here we will keep notes about our development process, policies and environment
setup guides.
### Issues Policies
#### Processing New Issues
Follow the following steps to process newly submitted issues:
- Edit the user's post to remove any links to illegal content such as ROM files.
- Edit the user's post to remove unused template sections etc.. Rephrase the
issue title if it needs to be clarified.
- Label the issue as a question, bug or enhancement. This label can be changed
later upon clarification if necessary.
- Add any other relevant labels, for example for the code subsystem.
- If it is strongly related to a work by a developer that you know of, assign
them to the issue. If this is not the case, they can be unassigned.
- Ask the user for clarification of any details if needed.
#### Resolving Issues
- An issue is resolved by closing it in GitHub. A commit that fixes the issue
should have the following line near the end of the body of the commit message:
```
Fix #999.
```
This will automatically close the issue and assign the closing commit in the
GitHub metadata when it is merged to master. The issue can be reopened if
needed.
- A commit that is work towards resolving an issue, should have the issue number
preceded by a pound sign either at the end of a commit message title, if it is
of primary relevance to the issue, or the body otherwise.
### Pull Request and Commit Policies
#### Commit Message
Follow these guidelines always:
https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
, the description of your work should be in the **commit message NOT the pull
request description**.
The title line must be no more than 50 characters and the description must be
wrapped at 72 characters. Most commit message editor interfaces will help you
with this. The title line must not end with a period.
Write everything in the imperative mood, e.g. change, fix, **NOT** changes,
changed, fixed, fixes etc..
A commit message must always have a title and a description, the description
must be independent of the title line, if necessary repeat the information in
the title line in the description.
The commit message must **ALL** changes, unless it's a minor refactor or
white space change or something and is not important.
The commit title line should be prefixed with an area, unless it involves the
wxWidgets GUI app, in which case it should **NOT** have a prefix.
If the commit is a user-facing functionality change or enhancement, the title
line of the commit must be a non-technical description of this change. For
example "Mute on speedup" because this will go into the changelog.
The text after the area prefix should not be capitalized.
Please use one of these area prefixes for non-main-GUI-app commits:
- doc: documentation, README.md etc..
- build: CMake, installdeps, preprocessor compatibility defines, compatibility
headers, macOS build system etc..
- gb: the GameBoy emulator core or changes related to it.
- gba: the GameBoy Advance emulator core or changes related to it.
- libretro: the libretro core glue and build.
- sdl: anything for the SDL port, but **NOT** SDL functionality in the wxWidgets
GUI app.
- translations: anything related to translations.
. Add other areas here if needed.
If a commit fixes a regression, use a title line such as:
```console
Fix regression <PROBLEM> in <SHORT-SHA>
```
, you can get the short SHA from `git log --oneline -100` or similar.
The commit description for a regression must refer to the breaking change in
reference format, which you can get from e.g. `git log --format=reference -20`.
#### Working on Pull Requests
When opening a pull request, push your branch to our repository if you were
given access, or a branch in your fork if you have not yet been given access. Do
**NOT** use `master`, use a specific branch.
If you are using a fork, set up your workflow like this:
```bash
git clone git@github.com:visualboyadvance-m/visualboyadvance-m
git remote add fork git@github.com:<your-GitHub-user>/visualboyadvance-m
git fetch --all --prune
git checkout -b your-work-branch-name
git commit -a --verbose --signoff -S
```
.
The `-S` flags tells Git to sign your commit with GnuPG. If you do not have a
GnuPG key, you will need to create one and upload it to a keyserver. I recommend
removing the password on your private key to not deal with `gpg-agent` and all
of this stuff.
All of this works fine on Windows, just install `GnuPG.GnuPG` from WinGet.
Your first push will then be:
```bash
git push -u fork HEAD
```
.
Subsequent commits will then be:
```bash
git commit -a --verbose --amend --reset-author --signoff -S
git push -f
```
. If you are a project member, then the workflow will be roughly:
```bash
git clone git@github.com:visualboyadvance-m/visualboyadvance-m
git fetch --all --prune
git checkout -b your-work-branch-name
git commit -a --verbose --signoff -S
```
. Your first push will be:
```bash
git push -u origin HEAD
```
. And subsequent pushes will be:
```bash
git commit -a --verbose --signoff -S --amend --reset-author
git push -f
```
. Please push frequently so that we can track your progress and review it.
Make sure the git history in your branch is clean and logical, edit when
necessary with `rebase -i`. In most cases a single commit with all of the
changes will be good. Sometimes you may want to split it up into multiple
logical commits for a large work, but a single commit is also fine if the title
line encapsulates all of the work for the changelog.
See the previous section on how to write commit messages.
If you are using Windows as your development environment, I recommend reading my
manual on Windows development environments
[here](https://github.com/rkitover/windows-dev-guide).
#### Collaboration on a Branch
To update when multiple people are working on a git branch, keep a couple of
things in mind:
- Always `push -f` unless you're adding a commit on top. And it's almost always
better to edit the history than to add more commits. Never add commits fixing
previous commits, only improving or adding to them.
- To update when someone else updated the branch with a `git push -f`:
```bash
git status # should be clean, with your work having been already pushed
git fetch --all --prune
git reset --hard origin/<work-branch-name>
```
.
- While actively working on a branch, keep it rebased on top of master, like
this:
```bash
git fetch --all --prune
git rebase origin/master
git push -f
```
. You may sometimes need to fix conflicts, follow the instructions.
#### Commits from Admins
Maintainers and project members have the power to commit directly to master.
This power must be used responsibly.
Make your best attempt to follow these general guidelines:
- Things that are a minor fix or improvement that does not require discussion
can be committed directly, keeping the following guidelines in mind.
- Bigger new features, code refactors and changes in architecture should go
through the PR process.
- Absolutely **NEVER** `git push -f` on `master`. If you make a mistake, revert
or push a fix commit.
- Push code changes to a branch first, so they can run through the CI. When you
open the commit in GitHub there is a little icon in the upper left corner that
shows the CI status for this commit. Differences in what different compilers
allow is a problem that comes up **VERY** frequently. As well as
incompatibilities between different configurations for both the C++ code and
any supporting code. Once the CI is clear, you can merge your branch like
this:
```bash
git push -f
git checkout master
git merge --ff-only <your-work-branch-name>
git push
git branch -D <your-work-branch-name>
git push origin ':refs/heads/your-work-branch-nbame'
```
. The last line there deletes the branch in our repository.
### Miscellaneous
#### Debug Messages
We have an override for `wxLogDebug()` to make it work even in non-debug builds
of wxWidgets and on windows, even in mintty.
It works like `printf()`, e.g.:
```cpp
int foo = 42;
wxLogDebug(wxT("the value of foo = %d"), foo);
```
From the core etc. the usual:
```cpp
fprintf(stderr, "...", ...);
```
, will work fine.
You need a debug build for this to work or to even have a console on Windows.
Pass `-DCMAKE_BUILD_TYPE=Debug` to CMake.
### Release Process
#### GnuPG Key
You will need to create a GnuPG key for signing your commits and release tags,
and upload it to a keyserver.
Make sure to install GnuPG on all environments where you will be making commits
and tags.
#### Certificates
Make sure you have set up a Windows code signing certificate with the right
password and a Mac 'Developer ID Application' certificate.
Put the Windows certificate into `~/.codesign/windows_comodo.pkcs12` as a PKCS12
file that is password protected, and put the password for it into
`~/.codesign/windows_comodo.pkcs12.password`.
#### Release Commit and Tag
Once you are sure you're ready to release, and you are in a git clone on master
with a clean working tree, use the cmake script to make the release commit and
tag:
```bash
mkdir build && cd build
cmake .. -DTAG_RELEASE=TRUE
```
, follow the instructions to edit the `CHANGELOG.md` and then push the release:
To reiterate, **make sure you edit the `CHANGELOG.md`** to remove any
non-user-facing changes before you make the release commit.
```bash
git push
git push --tags
```
If you don't want to push the release, to back out the change do:
```bash
cmake .. -DTAG_RELEASE=UNDO
```
#### 64-bit Windows Binary
For this you will preferably need the PowerShell environment setup described
[here](https://github.com/rkitover/windows-dev-guide), or by starting the `x64
Native Tools Command Prompt` from your Start Menu.
```powershell
mkdir build-msvc64
cd build-msvc64
cmake .. -DCMAKE_BUILD_TYPE=Release -DUPSTREAM_RELEASE=TRUE -G Ninja
ninja
```
Collect the following files for the release:
- `visualboyadvance-m-Win-x86_64.zip`
- `translations.zip`
Repeat the process for the debug build, with `-DCMAKE_BUILD_TYPE=Debug` and
collect this file:
- `visualboyadvance-m-Win-x86_64-debug.zip`
.
#### 32-bit Windows Binary
The 32-bit build is a legacy build for Windows XP compatibility. You will need
the MinGW toolchain to build it. The easiest method is to use the MINGW32 MSYS2
environment.
Make sure the Visual Studio `signtool.exe` is in your path, you can start MSYS2
with an inherited `PATH` from a Visual Studio enabled environment or add it to
your shell configuration.
First install dependencies with:
```bash
./installdeps
```
. Then build the 32-bit binary as follows:
```bash
mkdir build-mingw32
cd build-mingw32
cmake .. -DCMAKE_BUILD_TYPE=Release -DUPSTREAM_RELEASE=TRUE -G Ninja
ninja
```
. Collect this file for the release:
- `visualboyadvance-m-Win-x86_32.zip`
. Then repeat the process for the debug build with `-DCMAKE_BUILD_TYPE=Debug`,
and collect this file:
- `visualboyadvance-m-Win-x86_32-debug.zip`
.
#### ARM64 Windows Binary
You will need the MSVC ARM64 cross toolchain to build this binary, if you used
the install script from [here](https://github.com/rkitover/windows-dev-guide)
you will have it installed, otherwise run Visual Studio Installer and install
the component.
To enter the ARM64 cross environment, edit the PowerShell profile described
[here](https://github.com/rkitover/windows-dev-guide) or use the `vcvarsall.bat`
script with the `amd64_arm64` argument as described
[here](https://learn.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-170).
From there the process is the same as for the 64-bit build, collect the
following files for the release:
- `visualboyadvance-m-Win-arm64.zip`
- 'visualboyadvance-m-Win-arm64-debug.zip'
.
#### macOS Binary
Install the latest Xcode for your OS.
You will need bash from Homebrew/nix/MacPorts/whatever to run the build script.
You will need a codesigning certificate from Apple, which you will be able to
generate once you join their developer program from XCode. This is the
certificate of the type 'Developer ID Application' stored in your login
keychain.
If you are not using a GUI session, you will need to use a method to unlock your
login keychain before building so that your codesigning certificate can be used.
Adding the certificate and key to the System keychain is also a method that some
people use.
To unlock your keychain on login, you can add something like this to your
`~/.zshrc`:
```bash
security unlock-keychain -p "$(cat ~/.login-keychain-password)" login.keychain
```
, with your login password in that file.
For notarization to work, you will need to create an app-specific password on
https://appleid.apple.com , get your Team ID from your Apple Developer account,
and store them with this command:
```bash
xcrun notarytool store-credentials AC_PASSWORD \
--apple-id you@domain.com \
--team-id <DeveloperTeamID> \
--password <secret_app_specific_2FA_password>
```
. Once all of this is set up, run:
```bash
tools/osx/builder
```
, this will take a while because it builds all of the dependencies.
Collect the following files from `~/vbam-build-mac-64bit/project`:
- `visualboyadvance-m-Mac-x86_64.zip`
- `visualboyadvance-m-Mac-x86_64-debug.zip`
.
#### Final steps
Go to the github releases tab, and make a release for the tag you pushed
earlier.
Put any notes to users and distro maintainers into the description as well as
the generated entries from `CHANGELOG.md` you edited earlier.
Upload all files collected during the earlier builds, the complete list is:
- `translations.zip`
- `visualboyadvance-m-Win-x86_64.zip`
- `visualboyadvance-m-Win-x86_64-debug.zip`
- `visualboyadvance-m-Win-x86_32.zip`
- `visualboyadvance-m-Win-x86_32-debug.zip`
- `visualboyadvance-m-Win-arm64.zip`
- 'visualboyadvance-m-Win-arm64-debug.zip'
- `visualboyadvance-m-Mac-x86_64.zip`
- `visualboyadvance-m-Mac-x86_64-debug.zip`
Update the winsparkle `appcast.xml` by running this cmake command:
```bash
cmake .. -DUPDATE_APPCAST=TRUE
```
, follow the instructions to push the change to the web data repo.
Announce the release on reddit r/emulation and the forum.

288
README.md
View File

@ -3,12 +3,7 @@
- [Visual Boy Advance - M](#visual-boy-advance---m)
- [System Requirements](#system-requirements)
- [Building](#building)
- [Building a Libretro core](#building-a-libretro-core)
- [Visual Studio Support](#visual-studio-support)
- [Visual Studio Code Support](#visual-studio-code-support)
- [Dependencies](#dependencies)
- [Cross compiling for 32 bit on a 64 bit host](#cross-compiling-for-32-bit-on-a-64-bit-host)
- [Cross Compiling for Win32](#cross-compiling-for-win32)
- [CMake Options](#cmake-options)
@ -19,137 +14,69 @@
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
Our bridged Discord server is [Here](https://discord.gg/EpfxEuGMKH).
We are also on *`#vba-m`* on [Libera IRC](https://libera.chat/) which has a [Web
Chat](https://web.libera.chat/).
[![Get it from flathub](https://dl.flathub.org/assets/badges/flathub-badge-en.svg)](https://flathub.org/apps/com.vba_m.visualboyadvance-m)
[![Get it from the Snap Store](https://snapcraft.io/static/images/badges/en/snap-store-black.svg)](https://snapcraft.io/visualboyadvance-m)
***Want to know where you can install visualboyadvance-m in your linux distribution?***
[![Packaging status](https://repology.org/badge/vertical-allrepos/visualboyadvance-m.svg)](https://repology.org/project/visualboyadvance-m/versions)
[![Join the chat at https://gitter.im/visualboyadvance-m/Lobby](https://badges.gitter.im/visualboyadvance-m/Lobby.svg)](https://gitter.im/visualboyadvance-m/Lobby)
[![Build Status](https://travis-ci.org/visualboyadvance-m/visualboyadvance-m.svg?branch=master)](https://travis-ci.org/visualboyadvance-m/visualboyadvance-m)
[![Coverity Scan Build Status](https://scan.coverity.com/projects/16096/badge.svg)](https://scan.coverity.com/projects/visualboyadvance-m-visualboyadvance-m)
# Visual Boy Advance - M
Game Boy and Game Boy Advance Emulator
Game Boy Advance Emulator
The forums are [here](https://board.visualboyadvance-m.org/).
Homepage and Forum: http://vba-m.com
Windows and Mac builds are in the [releases tab](https://github.com/visualboyadvance-m/visualboyadvance-m/releases).
Nightly builds for Windows and macOS are at [https://nightly.visualboyadvance-m.org/](https://nightly.visualboyadvance-m.org/).
Daily Ubuntu packages here: https://code.launchpad.net/~sergio-br2/+archive/ubuntu/vbam-trunk
**PLEASE TEST THE NIGHTLY OR MASTER WITH A FACTORY RESET BEFORE REPORTING
ISSUES**
Your distribution may have packages available as well, search for
`visualboyadvance-m` or `vbam`.
Your distribution may have packages available as well, search for "vbam" or "visualboyadvance-m".
It is also generally very easy to build from source, see below.
If you are using the windows binary release and you need localization, unzip
the `translations.zip` to the same directory as the executable.
If you are having issues, try resetting the config file first, go to `Help ->
Factory Reset`.
## Note for Windows Users
## System Requirements
If you are having issues, try resetting your config file first.
Windows XP, Vista, 7, 8.1 or 10/11, Linux distros or macOS.
2Ghz x86 (or x86-64) Intel Core 2 or AMD Athlon processor with SSE, Snapdragon 835
or newer CPU compatible with Arm for Windows.
- Just a guideline, lower clock speeds and Celeron processors may be able to run at full
speed on lower settings, and Linux based ARM Operating systems have wider CPU support.
DirectX June 2010 Redist
[Full](https://www.microsoft.com/en-au/download/details.aspx?id=8109) /
[Websetup](https://www.microsoft.com/en-au/download/details.aspx?id=35) for
Xaudio (Remember to uncheck Bing on the websetup.)
- open file explorer
- in the location bar, type `%USERPROFILE%\AppData\Local` and press enter
- delete the directory called `visualboyadvance-m`
## Building
The basic formula to build vba-m is:
```bash
```shell
cd ~ && mkdir src && cd src
git clone https://github.com/visualboyadvance-m/visualboyadvance-m.git
cd visualboyadvance-m
./installdeps
./installdeps # On Linux or macOS
# ./installdeps will give you build instructions, which will be similar to:
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -G Ninja
ninja
```
`./installdeps` is supported on MSYS2, Linux (Debian/Ubuntu, Fedora, Arch,
Solus, OpenSUSE, Gentoo and RHEL/CentOS) and Mac OS X (homebrew, MacPorts or
Fink.)
## Building a Libretro core
Clone this repo and then,
```bash
cd src/libretro
mkdir build && cd build
cmake ..
make -j`nproc`
```
Copy `vbam_libretro.so` to your RetroArch cores directory.
`./installdeps` is supported on MSys2, Linux (Debian/Ubuntu, Fedora, Arch,
Solus and RHEL/CentOS) and Mac OS X (homebrew, macports or fink.)
## Visual Studio Support
The Ninja cmake generator is also now supported, including on msys2 and Visual Studio.
### Visual Studio Support
For visual studio, dependency management is handled automatically with vcpkg,
From the Visual Studio GUI, just clone the repository with git and build with
the cmake configurations provided.
If the GUI does not detect cmake, go to `File -> Open -> CMake` and open the
`CMakeLists.txt`.
If you are using 2017, make sure you have all the latest updates, some issues
with cmake projects in the GUI have been fixed.
You can also build from the developer command prompt or powershell with the
environment loaded.
just clone the repository with git and build with cmake. You can do this from
the developer command line as well. 2019 will not work yet for building
dependencies, but you can build the dependencies in 2017 and then use the
project from 2019.
Using your own user-wide installation of vcpkg is supported, just make sure the
environment variable `VCPKG_ROOT` is set.
To build in the Visual Studio `x64 Native Tools Command Prompt`, use something
like this:
```
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -G Ninja
ninja
```
.
## Visual Studio Code Support
Make sure the
[C/C++](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools)
and [CMake
Tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cmake-tools)
extensions are installed.
Add the following to your `settings.json`:
```json
{
"cmake.configureOnOpen": true,
"cmake.preferredGenerators": [ "Ninja" ]
}
```
.
## Dependencies
### Dependencies
If your OS is not supported, you will need the following:
@ -157,20 +84,22 @@ If your OS is not supported, you will need the following:
- [make](https://en.wikipedia.org/wiki/Make_(software))
- [CMake](https://cmake.org/)
- [git](https://git-scm.com/)
- [nasm](https://www.nasm.us/) (optional, for 32 bit builds)
- nasm (optional, for 32 bit builds)
And the following development libraries:
- [zlib](https://zlib.net/) (required)
- [mesa](https://mesa3d.org/) (if using X11 or any OpenGL otherwise)
- [ffmpeg](https://ffmpeg.org/) (optional, at least version `4.0.4`, for game recording)
- [gettext](https://www.gnu.org/software/gettext/) and gettext-tools
- [SDL2](https://www.libsdl.org/) (required)
- [openal-soft](https://kcat.strangesoft.net/openal.html) (optional, a sound interface)
- [wxWidgets](https://wxwidgets.org/) (required for GUI, 2.8 and non-stl builds are no longer supported)
- ffmpeg (optional, for game recording)
- gettext and gettext tools (optional, with ENABLE_NLS)
- png (required)
- [SDL](https://www.libsdl.org/)2 (required)
- [SFML](https://www.sfml-dev.org/) (optional, for link)
- OpenAL (optional, a sound interface)
- [wxWidgets](https://wxwidgets.org/) (required, 2.8 is still supported, --enable-stl is supported)
On Linux and similar, you also need the version of GTK your wxWidgets is linked
to (usually 2 or 3) and the xorg development libraries.
to (usually 2 or 3).
Support for more OSes/distributions for `./installdeps` is planned.
@ -184,57 +113,104 @@ This is supported on Fedora, Arch, Solus and MSYS2.
`./installdeps` takes one optional parameter for cross-compiling target, which
may be `win32` which is an alias for `mingw-w64-i686` to target 32 bit Windows,
or `mingw-w64-x86_64` for 64 bit Windows targets.
or `mingw-gw64-x86_64` for 64 bit Windows targets.
The target is implicit on MSYS2 depending on which MINGW shell you started (the
value of `$MSYSTEM`.)
The target is implicit on MSys2 depending on which MINGW shell you started (the
value of `$MSYSTEM`.) It will not run in the MSys shell.
On Debian/Ubuntu this uses the MXE apt repository and works quite well.
On Debian/Ubuntu this uses the MXE apt repository and works really well.
On Fedora it can build using the Fedora MinGW packages, albeit with wx 2.8, no
OpenGL support, and no Link support for lack of SFML.
On Arch it currently doesn't work at all because the AUR stuff is completely
broken, I will at some point redo the arch stuff to use MXE as well.
## CMake Options
The CMake code tries to guess reasonable defaults for options, but you can
override them, for example:
override them on the cmake command with e.g.:
```shell
cmake .. -DCMAKE_BUILD_TYPE=Release -DENABLE_LINK=NO -G Ninja
cmake .. -DENABLE_LINK=NO
```
. Here is the complete list:
Of particular interest is making **RELEASE** or **DEBUG** builds, the default
mode is **RELEASE**, to make a **DEBUG** build use something like:
```shell
cmake .. -DCMAKE_BUILD_TYPE=Debug
```
Here is the complete list:
| **CMake Option** | **What it Does** | **Defaults** |
|-----------------------|----------------------------------------------------------------------|-----------------------|
| `ENABLE_SDL` | Build the SDL port | OFF |
| `ENABLE_WX` | Build the wxWidgets port | ON |
| `ENABLE_DEBUGGER` | Enable the debugger | ON |
| `ENABLE_ASM_CORE` | Enable x86 ASM CPU cores (**BUGGY AND DANGEROUS**) | OFF |
| `ENABLE_ASM` | Enable the following two ASM options | ON for 32 bit builds |
| `ENABLE_ASM_SCALERS` | Enable x86 ASM graphic filters | ON for 32 bit builds |
| `ENABLE_MMX` | Enable MMX | ON for 32 bit builds |
| `ENABLE_LINK` | Enable GBA linking functionality | AUTO |
| `ENABLE_LIRC` | Enable LIRC support | OFF |
| `ENABLE_FFMPEG` | Enable ffmpeg A/V recording | AUTO |
| `ENABLE_ONLINEUPDATES` | Enable online update checks | ON |
| `ENABLE_LTO` | Compile with Link Time Optimization (gcc and clang only) | ON for release build |
| `ENABLE_GBA_LOGGING` | Enable extended GBA logging | ON |
| `ENABLE_OPENAL` | Enable openal-soft sound output for wxWidgets | ON, not 32 bit Win |
| `ENABLE_XAUDIO2` | Enable xaudio2 sound output for wxWidgets (Windows only) | ON |
| `ENABLE_FAUDIO` | Enable faudio sound output for wxWidgets, | ON, not 32 bit Win |
| `ENABLE_ASAN` | Enable libasan sanitizers (by default address, only in debug mode) | OFF |
| `UPSTREAM_RELEASE` | Do some release tasks, like codesigning, making zip and gpg sigs. | OFF |
| `BUILD_TESTING` | Build the tests and enable ctest support. | ON |
| `VBAM_STATIC` | Try link all libs statically (the following are set to ON if ON) | OFF |
| `SDL2_STATIC` | Try to link static SDL2 libraries | OFF |
| `FFMPEG_STATIC` | Try to link static ffmpeg libraries | OFF |
| `OPENAL_STATIC` | Try to link static OpenAL libraries | OFF |
| `TRANSLATIONS_ONLY` | Build only the translations.zip and nothing else | OFF |
| ENABLE_SDL | Build the SDL port | OFF |
| ENABLE_WX | Build the wxWidgets port | ON |
| ENABLE_DEBUGGER | Enable the debugger | ON |
| ENABLE_NLS | Enable translations | ON |
| ENABLE_ASM_CORE | Enable x86 ASM CPU cores (**BUGGY AND DANGEROUS**) | OFF |
| ENABLE_ASM | Enable the following two ASM options | ON for 32 bit builds |
| ENABLE_ASM_SCALERS | Enable x86 ASM graphic filters | ON for 32 bit builds |
| ENABLE_MMX | Enable MMX | ON for 32 bit builds |
| ENABLE_LINK | Enable GBA linking functionality (requires SFML) | ON |
| ENABLE_LIRC | Enable LIRC support | OFF |
| ENABLE_FFMPEG | Enable ffmpeg A/V recording | OFF |
| ENABLE_LTO | Compile with Link Time Optimization (gcc and clang only) | ON for release build |
| ENABLE_GBA_LOGGING | Enable extended GBA logging | ON |
| ENABLE_DIRECT3D | Direct3D rendering for wxWidgets (Windows, **NOT IMPLEMENTED!!!**) | ON |
| ENABLE_XAUDIO2 | Enable xaudio2 sound output for wxWidgets (Windows only) | ON |
| ENABLE_OPENAL | Enable OpenAL for the wxWidgets port | OFF |
| ENABLE_SSP | Enable gcc stack protector support (gcc only) | OFF |
| ENABLE_ASAN | Enable libasan sanitizers (by default address, only in debug mode) | OFF |
| VBAM_STATIC | Try link all libs statically (the following are set to ON if ON) | OFF |
| SDL2_STATIC | Try to link static SDL2 libraries | OFF |
| SFML_STATIC_LIBRARIES | Try to link static SFML libraries | OFF |
| FFMPEG_STATIC | Try to link static ffmpeg libraries | OFF |
| SSP_STATIC | Try to link static gcc stack protector library (gcc only) | OFF except Win32 |
| OPENAL_STATIC | Try to link static OpenAL libraries | OFF |
| SSP_STATIC | Link gcc stack protecter libssp statically (gcc, with ENABLE_SSP) | OFF |
Note for distro packagers, we use the CMake module
[GNUInstallDirs](https://cmake.org/cmake/help/v2.8.12/cmake.html#module:GNUInstallDirs)
to configure installation directories.
On Unix to use a different version of wxWidgets, set
`wxWidgets_CONFIG_EXECUTABLE` to the path to the `wx-config` script you want to
use.
## MSys2 Notes
To run the resulting binary, you can simply type:
```shell
./visualboyadvance-m
```
in the shell where you built it.
If you built with `-DCMAKE_BUILD_TYPE=Debug`, you will get a console app and
will see debug messages, even in mintty.
If you want to start the binary from e.g. a shortcut or Explorer, you will need
to put `c:\msys64\mingw32\bin` for 32 bit builds and `c:\msys64\mingw64\bin`
for 64 bit builds in your PATH (to edit system PATH, go to Control Panel ->
System -> Advanced system settings -> Environment Variables.)
If you want to package the binary, you will need to include the MinGW DLLs it
depends on, they can install to the same directory as the binary.
For our own builds, we use MXE to make static builds.
## Debug Messages
We have an override for `wxLogDebug()` to make it work even in non-debug builds
of wx and on windows, even in mintty. Using this function for console debug
messages is recommended.
It works like `printf()`, e.g.:
```cpp
int foo = 42;
wxLogDebug(wxT("the value of foo = %d"), foo);
```
## Reporting Crash Bugs
@ -254,26 +230,40 @@ do something such as:
```shell
ulimit -c unlimited
```
, in your shell to enable core files.
in your shell to enable coredump files.
[This
post](https://ask.fedoraproject.org/en/question/98776/where-is-core-dump-located/?answer=98779#post-id-98779)
explains how to retrieve core dump on some distributions, when they are managed
by systemd.
explains how to retrieve core dump on Fedora Linux (and possibly other
distributions.)
Once you have the core file, open it with `gdb`, for example:
Once you have the core dump file, open it with `gdb`, for example:
```shell
gdb -c core ./visualboyadvance-m
```
. In the `gdb` shell, to start the process and print the backtrace, type:
In the `gdb` shell, to print the backtrace, type:
```
run
bt
```
. This may be a bit of a hassle, but it helps us out immensely.
This may be a bit of a hassle, but it helps us out immensely.
## Contributing
See the [Developer Manual](/DEVELOPER-MANUAL.md).
Please keep in mind that this app needs to run on Windows, Linux and macOS at
the very least, so code should be portable and/or use the appropriate `#ifdef`s
and the like when needed.
Please try to craft a good commit message, this post by the great tpope explains
how to do so:
http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
If you have multiple small commits for a change, please try to use `git rebase
-i` (interactive rebase) to squash them into one or a few logical commits (with
good commit messages!) See:
https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History if you are new to
this.

View File

@ -1,52 +0,0 @@
buildType:
default: debug
choices:
debug:
short: Debug
long: Emit debug information
buildType: Debug
release:
short: Release
long: Optimize generated code
buildType: Release
linkage:
default: static
choices:
static:
short: Static
long: Create static libraries
linkage: static
shared:
short: Shared
long: Create shared libraries/DLLs
linkage: shared
useLink:
default: withlink
choices:
withlink:
short: WithLink
long: Enable the Link feature
settings:
ENABLE_LINK: ON
nolink:
short: NoLink
long: Disable the Link feature
settings:
ENABLE_LINK: OFF
useDebugger:
default: withdebugger
choices:
withdebugger:
short: WithDebugger
long: Enable the Debugger feature
settings:
ENABLE_DEBUGGER: ON
nodebugger:
short: NoDebugger
long: Disable the Debugger feature
settings:
ENABLE_DEBUGGER: OFF
ENABLE_SDL: OFF

View File

@ -1,7 +1,3 @@
if(TRANSLATIONS_ONLY)
return()
endif()
if(NOT CMAKE_SYSTEM_PROCESSOR)
if(NOT CMAKE_TOOLCHAIN_FILE AND CMAKE_HOST_SYSTEM_PROCESSOR)
set(CMAKE_SYSTEM_PROCESSOR ${CMAKE_HOST_SYSTEM_PROCESSOR})
@ -11,66 +7,18 @@ if(NOT CMAKE_SYSTEM_PROCESSOR)
else()
set(CMAKE_SYSTEM_PROCESSOR x86_64)
endif()
elseif(CROSS_ARCH STREQUAL x86_64)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
elseif(CROSS_ARCH STREQUAL i686)
set(CMAKE_SYSTEM_PROCESSOR i686)
endif()
endif()
# The processor may not be set, but set BITS regardless.
if(CMAKE_C_SIZEOF_DATA_PTR EQUAL 4)
set(BITS 32)
elseif(CMAKE_C_SIZEOF_DATA_PTR EQUAL 8)
set(BITS 64)
endif()
if(VCPKG_TARGET_TRIPLET MATCHES "^[aA][rR][mM]64")
set(CMAKE_SYSTEM_PROCESSOR ARM64)
elseif(VCPKG_TARGET_TRIPLET MATCHES "^[aA][rR][mM]-")
set(CMAKE_SYSTEM_PROCESSOR ARM)
endif()
# Turn asm on by default on 32bit x86 and set WINARCH for windows stuff.
# turn asm on by default on 32bit x86
# and set WINARCH for windows stuff
if(CMAKE_SYSTEM_PROCESSOR MATCHES "[xX]86|i[3-9]86|[aA][mM][dD]64")
if(CMAKE_C_SIZEOF_DATA_PTR EQUAL 4) # 32 bit
set(ASM_DEFAULT ON)
set(X86_32 ON)
set(X86 ON)
set(WINARCH x86)
set(ARCH_NAME x86_32)
elseif(CMAKE_C_SIZEOF_DATA_PTR EQUAL 8)
set(AMD64 ON)
set(X64 ON)
set(X86_64 ON)
set(WINARCH x64)
set(ARCH_NAME x86_64)
endif()
if(DEFINED VCPKG_TARGET_TRIPLET)
string(REGEX MATCH "^x[86][64]" target_arch ${VCPKG_TARGET_TRIPLET})
if(NOT WINARCH STREQUAL target_arch)
message(FATAL_ERROR "Wrong build environment architecture for VCPKG_TARGET_TRIPLET, you specified ${target_arch} but your compiler is for ${WINARCH}")
if(NOT (MSVC AND CMAKE_TOOLCHAIN_FILE MATCHES vcpkg))
set(ASM_DEFAULT ON)
endif()
endif()
elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "[aA][aA][rR][cC][hH]|[aA][rR][mM]")
if(CMAKE_C_SIZEOF_DATA_PTR EQUAL 4) # 32 bit
set(ARM32 ON)
set(ARCH_NAME ARM32)
set(WINARCH arm)
elseif(CMAKE_C_SIZEOF_DATA_PTR EQUAL 8)
set(ARM64 ON)
set(ARCH_NAME ARM64)
set(WINARCH arm64)
endif()
if(NOT CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "[aA][aA][rR][cC][hH]|[aA][rR][mM]")
set(CMAKE_CROSSCOMPILING TRUE)
set(X86_32 ON)
else()
set(AMD64 ON)
endif()
endif()
# We do not support amd64 asm yet
if(X86_64 AND (ENABLE_ASM_CORE OR ENABLE_ASM_SCALERS OR ENABLE_MMX))
message(FATAL_ERROR "The options ASM_CORE, ASM_SCALERS and MMX are not supported on X86_64 yet.")
endif()

View File

@ -0,0 +1,54 @@
#=============================================================================
# Copyright 2010 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
# support for the nasm assembler
set(CMAKE_ASM_NASM_SOURCE_FILE_EXTENSIONS nasm asm)
if(NOT CMAKE_ASM_NASM_OBJECT_FORMAT)
if(WIN32)
if(CMAKE_C_SIZEOF_DATA_PTR EQUAL 8)
SET(CMAKE_ASM_NASM_OBJECT_FORMAT win64)
else()
SET(CMAKE_ASM_NASM_OBJECT_FORMAT win32)
endif()
elseif(APPLE)
EXECUTE_PROCESS(COMMAND ${CMAKE_ASM_NASM_COMPILER} -v COMMAND awk "{print \$3}" OUTPUT_VARIABLE NASM_VERSION)
IF(NASM_VERSION VERSION_LESS 2.0)
IF(CMAKE_C_SIZEOF_DATA_PTR EQUAL 8)
MESSAGE(FATAL_ERROR "Your nasm is too old to support AMD64, please install nasm from Homebrew or MacPorts.")
ENDIF()
SET(CMAKE_ASM_NAMS_OBJECT_FORMAT macho)
ELSE()
if(CMAKE_C_SIZEOF_DATA_PTR EQUAL 8)
SET(CMAKE_ASM_NASM_OBJECT_FORMAT macho64)
else()
SET(CMAKE_ASM_NASM_OBJECT_FORMAT macho32)
endif()
ENDIF()
else()
if(CMAKE_C_SIZEOF_DATA_PTR EQUAL 8)
SET(CMAKE_ASM_NASM_OBJECT_FORMAT elf64)
else()
SET(CMAKE_ASM_NASM_OBJECT_FORMAT elf32)
endif()
endif()
endif()
set(CMAKE_ASM_NASM_COMPILE_OBJECT "<CMAKE_ASM_NASM_COMPILER> <DEFINES> <FLAGS> -f ${CMAKE_ASM_NASM_OBJECT_FORMAT} -o <OBJECT> <SOURCE>")
# Load the generic ASMInformation file:
set(ASM_DIALECT "_NASM")
include(CMakeASMInformation)
set(ASM_DIALECT)

View File

@ -0,0 +1,27 @@
#=============================================================================
# Copyright 2010 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
# Find the nasm assembler. yasm (http://www.tortall.net/projects/yasm/) is nasm compatible
SET(CMAKE_ASM_NASM_COMPILER_INIT nasm yasm)
IF(NOT CMAKE_ASM_NASM_COMPILER)
FIND_PROGRAM(CMAKE_ASM_NASM_COMPILER nasm
"$ENV{ProgramFiles}/NASM")
ENDIF(NOT CMAKE_ASM_NASM_COMPILER)
# Load the generic DetermineASM compiler file with the DIALECT set properly:
SET(ASM_DIALECT "_NASM")
INCLUDE(CMakeDetermineASMCompiler)
SET(ASM_DIALECT)

View File

@ -1,85 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file LICENCE.txt or https://cmake.org/licensing for details.
# CMakeDetermine(LANG)Compiler.cmake -> this should find the compiler for LANG and configure CMake(LANG)Compiler.cmake.in
include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
if(NOT CMAKE_Metal_COMPILER_NAMES)
set(CMAKE_Metal_COMPILER_NAMES metal)
endif()
if("${CMAKE_GENERATOR}" STREQUAL "Xcode")
set(CMAKE_Metal_COMPILER_XCODE_TYPE sourcecode.metal)
execute_process(COMMAND xcrun --find metal
OUTPUT_VARIABLE _xcrun_out OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_VARIABLE _xcrun_err RESULT_VARIABLE _xcrun_result
)
if(_xcrun_result EQUAL 0 AND EXISTS "${_xcrun_out}")
set(CMAKE_Metal_COMPILER "${_xcrun_out}")
else()
_cmake_find_compiler_path(Metal)
endif()
else()
if(CMAKE_Metal_COMPILER)
_cmake_find_compiler_path(Metal)
else()
set(CMAKE_Metal_COMPILER_INIT NOTFOUND)
if(NOT $ENV{METALC} STREQUAL "")
get_filename_component(CMAKE_Metal_COMPILER_INIT $ENV{METALC} PROGRAM PROGRAM_ARGS CMAKE_Metal_FLAGS_ENV_INIT)
if(CMAKE_Metal_FLAGS_ENV_INIT)
set(CMAKE_Metal_COMPILER_ARG1 "${CMAKE_Metal_FLAGS_ENV_INIT}" CACHE STRING "Arguments to the Metal compiler")
endif()
if(NOT EXISTS ${CMAKE_Metal_COMPILER_INIT})
message(FATAL_ERROR "Could not find compiler set in environment variable METALC\n$ENV{METALC}.\n${CMAKE_Metal_COMPILER_INIT}")
endif()
endif()
if(NOT CMAKE_Metal_COMPILER_INIT)
set(CMAKE_Metal_COMPILER_LIST metal ${_CMAKE_TOOLCHAIN_PREFIX}metal)
endif()
_cmake_find_compiler(Metal)
endif()
mark_as_advanced(CMAKE_Metal_COMPILER)
endif()
# For Metal we need to explicitly query the version.
if(CMAKE_Metal_COMPILER AND NOT CMAKE_Metal_COMPILER_VERSION)
execute_process(
COMMAND "${CMAKE_Metal_COMPILER}" --version
OUTPUT_VARIABLE output ERROR_VARIABLE output
RESULT_VARIABLE result
TIMEOUT 10
)
message(CONFIGURE_LOG
"Running the Metal compiler: \"${CMAKE_Metal_COMPILER}\" --version\n"
"${output}\n"
)
if(output MATCHES [[metal version ([0-9]+\.[0-9]+(\.[0-9]+)?)]])
set(CMAKE_Metal_COMPILER_VERSION "${CMAKE_MATCH_1}")
if(NOT CMAKE_Metal_COMPILER_ID)
set(CMAKE_Metal_COMPILER_ID "Apple")
endif()
endif()
endif()
if(NOT _CMAKE_TOOLCHAIN_LOCATION)
get_filename_component(_CMAKE_TOOLCHAIN_LOCATION "${CMAKE_Metal_COMPILER}" PATH)
endif ()
set(_CMAKE_PROCESSING_LANGUAGE "Metal")
include(CMakeFindBinUtils)
unset(_CMAKE_PROCESSING_LANGUAGE)
configure_file(
${CMAKE_CURRENT_LIST_DIR}/CMakeMetalCompiler.cmake.in
${CMAKE_PLATFORM_INFO_DIR}/CMakeMetalCompiler.cmake
)
set(CMAKE_Metal_COMPILER_ENV_VAR "METALC")

View File

@ -1,27 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file LICENCE.txt or https://cmake.org/licensing for details.
# CMake(LANG)Compiler.cmake.in -> used by CMakeDetermine(LANG)Compiler.cmake
# This file is used to store compiler information and is copied down into try
# compile directories so that try compiles do not need to re-determine and test
# the LANG
set(CMAKE_Metal_COMPILER "@CMAKE_Metal_COMPILER@")
set(CMAKE_Metal_COMPILER_ID "@CMAKE_Metal_COMPILER_ID@")
set(CMAKE_Metal_COMPILER_VERSION "@CMAKE_Metal_COMPILER_VERSION@")
set(CMAKE_Metal_COMPILER_LOADED 1)
set(CMAKE_Metal_COMPILER_WORKS "@CMAKE_Metal_COMPILER_WORKS@")
set(CMAKE_Metal_COMPILER_ENV_VAR "METALC")
set(CMAKE_Metal_COMPILER_ID_RUN "@CMAKE_Metal_COMPILER_ID_RUN@")
set(CMAKE_Metal_SOURCE_FILE_EXTENSIONS metal)
set(CMAKE_Metal_OUTPUT_EXTENSION ".air")
set(CMAKE_STATIC_LIBRARY_PREFIX_Metal "")
set(CMAKE_STATIC_LIBRARY_SUFFIX_Metal ".metal-ar")
set(CMAKE_SHARED_LIBRARY_PREFIX_Metal "")
set(CMAKE_SHARED_LIBRARY_SUFFIX_Metal ".metallib")
set(CMAKE_SHARED_MODULE_PREFIX_Metal "")
set(CMAKE_SHARED_MODULE_SUFFIX_Metal ".metallib")
set(CMAKE_EXECUTABLE_SUFFIX_Metal ".metallib")

View File

@ -1,85 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file LICENCE.txt or https://cmake.org/licensing for details.
# CMake(LANG)Information.cmake -> set up rule variables for LANG :
# CMAKE_(LANG)_CREATE_SHARED_LIBRARY
# CMAKE_(LANG)_CREATE_SHARED_MODULE
# CMAKE_(LANG)_CREATE_STATIC_LIBRARY
# CMAKE_(LANG)_COMPILE_OBJECT
# CMAKE_(LANG)_LINK_EXECUTABLE
include(CMakeCommonLanguageInclude)
set(CMAKE_Metal_FLAGS_INIT "-ffast-math")
set(CMAKE_Metal_FLAGS_DEBUG_INIT "-gline-tables-only -frecord-sources")
set(CMAKE_Metal_FLAGS_RELWITHDEBINFO_INIT "-gline-tables-only -frecord-sources")
cmake_initialize_per_config_variable(CMAKE_Metal_FLAGS "Flags used by the Metal compiler")
set(CMAKE_INCLUDE_FLAG_Metal "-I ")
set(CMAKE_Metal_COMPILER_ARG1 "")
set(CMAKE_Metal_DEFINE_FLAG -D)
set(CMAKE_Metal_FRAMEWORK_SEARCH_FLAG "-F ")
set(CMAKE_Metal_LIBRARY_PATH_FLAG "-L ")
set(CMAKE_Metal_SYSROOT_FLAG "-isysroot")
set(CMAKE_Metal_COMPILE_OPTIONS_TARGET "-target ")
set(CMAKE_DEPFILE_FLAGS_Metal "-MMD -MT dependencies -MF <DEP_FILE>")
if(CMAKE_GENERATOR MATCHES "Makefiles")
set(CMAKE_Metal_DEPFILE_FORMAT gcc)
set(CMAKE_Metal_DEPENDS_USE_COMPILER TRUE)
endif()
set(CMAKE_Metal_COMPILER_PREDEFINES_COMMAND "${CMAKE_Metal_COMPILER}")
if(CMAKE_Metal_COMPILER_TARGET)
list(APPEND CMAKE_Metal_COMPILER_PREDEFINES_COMMAND "-target" "${CMAKE_Metal_COMPILER_TARGET}")
endif()
# now define the following rule variables
# CMAKE_Metal_CREATE_SHARED_LIBRARY
# CMAKE_Metal_CREATE_SHARED_MODULE
# CMAKE_Metal_COMPILE_OBJECT
# CMAKE_Metal_LINK_EXECUTABLE
# variables supplied by the generator at use time
# <TARGET>
# <TARGET_BASE> the target without the suffix
# <OBJECTS>
# <OBJECT>
# <LINK_LIBRARIES>
# <FLAGS>
# <LINK_FLAGS>
# Metal compiler information
# <CMAKE_Metal_COMPILER>
# <CMAKE_SHARED_LIBRARY_CREATE_Metal_FLAGS>
# <CMAKE_SHARED_MODULE_CREATE_Metal_FLAGS>
# <CMAKE_Metal_LINK_FLAGS>
if(NOT CMAKE_Metal_COMPILE_OBJECT)
set(CMAKE_Metal_COMPILE_OBJECT
"<CMAKE_Metal_COMPILER> -c <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT> <SOURCE>"
)
endif()
if(NOT CMAKE_Metal_CREATE_SHARED_LIBRARY)
set(CMAKE_Metal_CREATE_SHARED_LIBRARY
"<CMAKE_Metal_COMPILER> <CMAKE_SHARED_LIBRARY_Metal_FLAGS> <LANGUAGE_COMPILE_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_Metal_FLAGS> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>"
)
endif()
if(NOT CMAKE_Metal_CREATE_SHARED_MODULE)
set(CMAKE_Metal_CREATE_SHARED_MODULE
"${CMAKE_Metal_CREATE_SHARED_LIBRARY}"
)
endif()
if(NOT CMAKE_Metal_LINK_EXECUTABLE)
# Metal shaders don't really have "executables", but we need this for the try_compile to work properly, so we'll just have it output a metallib file
set(CMAKE_Metal_LINK_EXECUTABLE
"<CMAKE_Metal_COMPILER> <FLAGS> <CMAKE_Metal_LINK_FLAGS> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>"
)
endif()
set(CMAKE_Metal_INFORMATION_LOADED 1)

View File

@ -0,0 +1,23 @@
#=============================================================================
# Copyright 2010 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
# This file is used by EnableLanguage in cmGlobalGenerator to
# determine that the selected ASM_NASM "compiler" works.
# For assembler this can only check whether the compiler has been found,
# because otherwise there would have to be a separate assembler source file
# for each assembler on every architecture.
SET(ASM_DIALECT "_NASM")
INCLUDE(CMakeTestASMCompiler)
SET(ASM_DIALECT)

View File

@ -1,78 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file LICENCE.txt or https://cmake.org/licensing for details.
# CMakeTest(LANG)Compiler.cmake -> test the compiler and set:
# SET(CMAKE_(LANG)_COMPILER_WORKS 1 CACHE INTERNAL "")
if(CMAKE_Metal_COMPILER_FORCED)
# The compiler configuration was forced by the user.
# Assume the user has configured all compiler information.
set(CMAKE_Metal_COMPILER_WORKS TRUE)
return()
endif()
include(CMakeTestCompilerCommon)
if("${CMAKE_GENERATOR}" STREQUAL "Xcode")
if(XCODE_VERSION VERSION_GREATER 7.0)
set(CMAKE_Metal_COMPILER_WORKS 1)
endif()
endif()
# This file is used by EnableLanguage in cmGlobalGenerator to
# determine that that selected Metal compiler can actually compile
# and link the most basic of programs. If not, a fatal error
# is set and cmake stops processing commands and will not generate
# any makefiles or projects.
if(NOT CMAKE_Metal_COMPILER_WORKS)
PrintTestCompilerStatus("Metal")
__TestCompiler_setTryCompileTargetType()
string(CONCAT __TestCompiler_testMetalCompilerSource
"#ifndef __METAL_VERSION__\n"
"# error \"The CMAKE_Metal_COMPILER is not a Metal compiler\"\n"
"#endif\n"
"#import <metal_stdlib>\n"
"using namespace metal;\n"
)
# Clear result from normal variable.
unset(CMAKE_Metal_COMPILER_WORKS)
# Puts test result in cache variable.
try_compile(CMAKE_Metal_COMPILER_WORKS
SOURCE_FROM_VAR testMetalCompiler.metal __TestCompiler_testMetalCompilerSource
OUTPUT_VARIABLE __CMAKE_Metal_COMPILER_OUTPUT
)
unset(__TestCompiler_testMetalCompilerSource)
# Move result from cache to normal variable.
set(CMAKE_Metal_COMPILER_WORKS ${CMAKE_Metal_COMPILER_WORKS})
unset(CMAKE_Metal_COMPILER_WORKS CACHE)
__TestCompiler_restoreTryCompileTargetType()
set(METAL_TEST_WAS_RUN 1)
endif()
if(NOT CMAKE_Metal_COMPILER_WORKS)
PrintTestCompilerResult(CHECK_FAIL "broken")
string(REPLACE "\n" "\n " _output "${__CMAKE_Metal_COMPILER_OUTPUT}")
message(FATAL_ERROR "The Metal compiler\n \"${CMAKE_Metal_COMPILER}\"\n"
"is not able to compile a simple test program.\nIt fails "
"with the following output:\n ${_output}\n\n"
"CMake will not be able to correctly generate this project."
)
else()
if(METAL_TEST_WAS_RUN)
PrintTestCompilerResult(CHECK_PASS "works")
endif()
# Re-configure to save learned information.
configure_file(
${CMAKE_CURRENT_LIST_DIR}/CMakeMetalCompiler.cmake.in
${CMAKE_PLATFORM_INFO_DIR}/CMakeMetalCompiler.cmake
@ONLY
)
include(${CMAKE_PLATFORM_INFO_DIR}/CMakeMetalCompiler.cmake)
endif()
unset(__CMAKE_Metal_COMPILER_OUTPUT)

View File

@ -9,7 +9,7 @@ function(changelog_version version revision version_release)
return()
endif()
string(REGEX MATCH "\n## +\\[([0-9.]+)(-([^] ]+))?\\] *.* *[0-9][0-9]?/" match_out "${changelog_file}")
string(REGEX MATCH "\n## +\\[([0-9.]+)(-([^] ]+))?\\] +.* +[0-9][0-9]?/" match_out "${changelog_file}")
set(changelog_version "${CMAKE_MATCH_1}")

View File

@ -1,169 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file LICENCE.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
CheckLanguage
-------------
Check whether a language can be enabled by the :command:`enable_language`
or :command:`project` commands:
.. command:: check_language
.. code-block:: cmake
check_language(<lang>)
Try enabling language ``<lang>`` in a test project and record results
in the cache:
:variable:`CMAKE_<LANG>_COMPILER`
If the language can be enabled, this variable is set to the compiler
that was found. If the language cannot be enabled, this variable is
set to ``NOTFOUND``.
If this variable is already set, either explicitly or cached by
a previous call, the check is skipped.
:variable:`CMAKE_<LANG>_HOST_COMPILER`
This variable is set when ``<lang>`` is ``CUDA`` or ``HIP``.
If the check detects an explicit host compiler that is required for
compilation, this variable will be set to that compiler.
If the check detects that no explicit host compiler is needed,
this variable will be cleared.
If this variable is already set, its value is preserved only if
:variable:`CMAKE_<LANG>_COMPILER` is also set.
Otherwise, the check runs and overwrites
:variable:`CMAKE_<LANG>_HOST_COMPILER` with a new result.
Note that :variable:`CMAKE_<LANG>_HOST_COMPILER` documents it should
not be set without also setting
:variable:`CMAKE_<LANG>_COMPILER` to a NVCC compiler.
:variable:`CMAKE_<LANG>_PLATFORM <CMAKE_HIP_PLATFORM>`
This variable is set to the detected GPU platform when ``<lang>`` is ``HIP``.
If the variable is already set its value is always preserved. Only compatible values
will be considered for :variable:`CMAKE_<LANG>_COMPILER`.
For example:
.. code-block:: cmake
check_language(Fortran)
if(CMAKE_Fortran_COMPILER)
enable_language(Fortran)
else()
message(STATUS "No Fortran support")
endif()
#]=======================================================================]
# This file has been modified to take into account the CMAKE_MODULES path when trying to build the test project
# Ref https://gitlab.kitware.com/cmake/cmake/-/issues/26020
# This was merged in to CMake 3.30.0, so we only need this for older versions
if(${CMAKE_VERSION} VERSION_GREATER_EQUAL 3.30)
include(${CMAKE_ROOT}/Modules/CheckLanguage.cmake)
else()
include_guard(GLOBAL)
block(SCOPE_FOR POLICIES)
cmake_policy(SET CMP0126 NEW)
macro(check_language lang)
if(NOT DEFINED CMAKE_${lang}_COMPILER)
set(_desc "Looking for a ${lang} compiler")
message(CHECK_START "${_desc}")
file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Check${lang})
set(extra_compiler_variables)
if("${lang}" MATCHES "^(CUDA|HIP)$" AND NOT CMAKE_GENERATOR MATCHES "Visual Studio")
set(extra_compiler_variables "set(CMAKE_${lang}_HOST_COMPILER \\\"\${CMAKE_${lang}_HOST_COMPILER}\\\")")
endif()
if("${lang}" STREQUAL "HIP")
list(APPEND extra_compiler_variables "set(CMAKE_${lang}_PLATFORM \\\"\${CMAKE_${lang}_PLATFORM}\\\")")
endif()
list(TRANSFORM extra_compiler_variables PREPEND "\"")
list(TRANSFORM extra_compiler_variables APPEND "\\n\"")
list(JOIN extra_compiler_variables "\n " extra_compiler_variables)
set(_cl_content
"cmake_minimum_required(VERSION ${CMAKE_VERSION})
set(CMAKE_MODULE_PATH \"${CMAKE_MODULE_PATH}\")
project(Check${lang} ${lang})
file(WRITE \"\${CMAKE_CURRENT_BINARY_DIR}/result.cmake\"
\"set(CMAKE_${lang}_COMPILER \\\"\${CMAKE_${lang}_COMPILER}\\\")\\n\"
${extra_compiler_variables}
)"
)
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Check${lang}/CMakeLists.txt"
"${_cl_content}")
if(CMAKE_GENERATOR_INSTANCE)
set(_D_CMAKE_GENERATOR_INSTANCE "-DCMAKE_GENERATOR_INSTANCE:INTERNAL=${CMAKE_GENERATOR_INSTANCE}")
else()
set(_D_CMAKE_GENERATOR_INSTANCE "")
endif()
if(CMAKE_GENERATOR MATCHES "^(Xcode$|Green Hills MULTI$|Visual Studio)")
set(_D_CMAKE_MAKE_PROGRAM "")
else()
set(_D_CMAKE_MAKE_PROGRAM "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
endif()
if(CMAKE_TOOLCHAIN_FILE)
set(_D_CMAKE_TOOLCHAIN_FILE "-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${CMAKE_TOOLCHAIN_FILE}")
else()
set(_D_CMAKE_TOOLCHAIN_FILE "")
endif()
if(CMAKE_${lang}_PLATFORM)
set(_D_CMAKE_LANG_PLATFORM "-DCMAKE_${lang}_PLATFORM:STRING=${CMAKE_${lang}_PLATFORM}")
else()
set(_D_CMAKE_LANG_PLATFORM "")
endif()
execute_process(
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Check${lang}
COMMAND ${CMAKE_COMMAND} . -G ${CMAKE_GENERATOR}
-A "${CMAKE_GENERATOR_PLATFORM}"
-T "${CMAKE_GENERATOR_TOOLSET}"
${_D_CMAKE_GENERATOR_INSTANCE}
${_D_CMAKE_MAKE_PROGRAM}
${_D_CMAKE_TOOLCHAIN_FILE}
${_D_CMAKE_LANG_PLATFORM}
OUTPUT_VARIABLE _cl_output
ERROR_VARIABLE _cl_output
RESULT_VARIABLE _cl_result
)
include(${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Check${lang}/result.cmake OPTIONAL)
if(CMAKE_${lang}_COMPILER AND "${_cl_result}" STREQUAL "0")
message(CONFIGURE_LOG
"${_desc} passed with the following output:\n"
"${_cl_output}\n")
set(_CHECK_COMPILER_STATUS CHECK_PASS)
else()
set(CMAKE_${lang}_COMPILER NOTFOUND)
set(_CHECK_COMPILER_STATUS CHECK_FAIL)
message(CONFIGURE_LOG
"${_desc} failed with the following output:\n"
"${_cl_output}\n")
endif()
message(${_CHECK_COMPILER_STATUS} "${CMAKE_${lang}_COMPILER}")
set(CMAKE_${lang}_COMPILER "${CMAKE_${lang}_COMPILER}" CACHE FILEPATH "${lang} compiler")
mark_as_advanced(CMAKE_${lang}_COMPILER)
if(CMAKE_${lang}_HOST_COMPILER)
message(STATUS "Looking for a ${lang} host compiler - ${CMAKE_${lang}_HOST_COMPILER}")
set(CMAKE_${lang}_HOST_COMPILER "${CMAKE_${lang}_HOST_COMPILER}" CACHE FILEPATH "${lang} host compiler")
mark_as_advanced(CMAKE_${lang}_HOST_COMPILER)
endif()
if(CMAKE_${lang}_PLATFORM)
set(CMAKE_${lang}_PLATFORM "${CMAKE_${lang}_PLATFORM}" CACHE STRING "${lang} platform")
mark_as_advanced(CMAKE_${lang}_PLATFORM)
endif()
endif()
endmacro()
endblock()
endif()

View File

@ -1,142 +0,0 @@
if(TRANSLATIONS_ONLY)
return()
endif()
# Look for some dependencies using CMake scripts
find_package(ZLIB REQUIRED)
set(OpenGL_GL_PREFERENCE GLVND)
if(CMAKE_SYSTEM_NAME STREQUAL FreeBSD)
set(OpenGL_GL_PREFERENCE LEGACY)
endif()
if(NOT DISABLE_OPENGL)
find_package(OpenGL)
if(NOT OpenGL_FOUND)
set(CMAKE_C_FLAGS "-DNO_OPENGL -DNO_OGL ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-DNO_OPENGL -DNO_OGL ${CMAKE_CXX_FLAGS}")
endif()
endif()
# Add libsamplerate to SDL2 with vcpkg
unset(SDL_LIBRARY_TEMP)
if((NOT ENABLE_SDL3) AND CMAKE_TOOLCHAIN_FILE MATCHES "vcpkg")
if(WIN32)
unset(arch_suffix)
unset(path_prefix)
if(VCPKG_TARGET_TRIPLET MATCHES -static)
set(arch_suffix -static)
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(path_prefix debug)
endif()
set(samplerate_lib_name samplerate)
set(installed_prefix ${_VCPKG_INSTALLED_DIR}/${WINARCH}-windows${arch_suffix}/${path_prefix})
if(MINGW)
set(installed_prefix ${_VCPKG_INSTALLED_DIR}/${WINARCH}-mingw${arch_suffix}/${path_prefix})
set(samplerate_lib_name lib${samplerate_lib_name})
endif()
SET(SDL_LIBRARY_TEMP ${SDL_LIBRARY_TEMP} "${installed_prefix}/lib/${samplerate_lib_name}${CMAKE_STATIC_LIBRARY_SUFFIX}")
else()
SET(SDL_LIBRARY_TEMP ${SDL_LIBRARY_TEMP} -lsamplerate)
endif()
endif()
if(ENABLE_SDL3)
if(VBAM_STATIC)
set(VBAM_SDL_LIBS SDL3::SDL3-static ${SDL_LIBRARY_TEMP})
else()
set(VBAM_SDL_LIBS SDL3::SDL3 ${SDL_LIBRARY_TEMP})
endif()
else()
if(VBAM_STATIC)
set(VBAM_SDL_LIBS SDL2::SDL2-static ${SDL_LIBRARY_TEMP})
else()
set(VBAM_SDL_LIBS SDL2::SDL2 ${SDL_LIBRARY_TEMP})
endif()
endif()
if(ENABLE_FFMPEG)
if(NOT FFMPEG_LIBRARIES)
message(FATAL_ERROR "ENABLE_FFMPEG was specified, but required versions of ffmpeg libraries cannot be found!")
endif()
if(APPLE)
list(APPEND FFMPEG_LDFLAGS "SHELL:-framework CoreText" "SHELL:-framework ApplicationServices")
if(UPSTREAM_RELEASE)
list(APPEND FFMPEG_LDFLAGS -lbz2 -ltiff "SHELL:-framework DiskArbitration" -lfreetype -lfontconfig -llzma -lxml2 -lharfbuzz)
endif()
elseif(WIN32)
set(WIN32_MEDIA_FOUNDATION_LIBS dxva2 evr mf mfplat mfplay mfreadwrite mfuuid amstrmid)
list(APPEND FFMPEG_LIBRARIES secur32 bcrypt ${WIN32_MEDIA_FOUNDATION_LIBS})
if(MSYS AND VBAM_STATIC)
foreach(lib tiff jbig lzma)
cygpath(lib "$ENV{MSYSTEM_PREFIX}/lib/lib${lib}.a")
list(APPEND FFMPEG_LIBRARIES "${lib}")
endforeach()
endif()
endif()
else()
add_compile_definitions(NO_FFMPEG)
endif()
if(ENABLE_LINK)
# IPC linking code needs sem_timedwait which can be either in librt or pthreads
if(NOT WIN32)
find_library(RT_LIB rt)
if(RT_LIB)
set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${RT_LIB})
set(VBAMCORE_LIBS ${VBAMCORE_LIBS} ${RT_LIB})
endif()
endif()
include(CheckFunctionExists)
check_function_exists(sem_timedwait SEM_TIMEDWAIT)
if(SEM_TIMEDWAIT)
add_compile_definitions(HAVE_SEM_TIMEDWAIT)
endif()
else()
add_compile_definitions(NO_LINK)
endif()
# for now, only GBALink.cpp uses gettext() directly
if(APPLE)
# use Homebrew gettext if available
if(EXISTS "/usr/local/opt/gettext")
set(CMAKE_INCLUDE_PATH "${CMAKE_INCLUDE_PATH};/usr/local/opt/gettext/include")
set(CMAKE_LIBRARY_PATH "${CMAKE_LIBRARY_PATH};/usr/local/opt/gettext/lib")
set(CMAKE_PROGRAM_PATH "${CMAKE_PROGRAM_PATH};/usr/local/opt/gettext/bin")
endif()
endif()
if(ENABLE_LINK OR ENABLE_WX)
find_path(LIBINTL_INC libintl.h)
find_library(LIBINTL_LIB NAMES libintl intl)
find_library(LIBICONV_LIB NAMES libiconv iconv)
find_library(LIBCHARSET_LIB NAMES libcharset charset)
if(LIBINTL_LIB)
list(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBINTL_LIB})
list(APPEND NLS_LIBS ${LIBINTL_LIB})
endif()
if(LIBICONV_LIB)
list(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBICONV_LIB})
list(APPEND NLS_LIBS ${LIBICONV_LIB})
endif()
if(LIBCHARSET_LIB)
list(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBCHARSET_LIB})
list(APPEND NLS_LIBS ${LIBCHARSET_LIB})
endif()
include(CheckFunctionExists)
check_function_exists(gettext GETTEXT_FN)
if(NOT (LIBINTL_INC OR GETTEXT_FN))
message(FATAL_ERROR "NLS requires libintl/gettext")
endif()
endif()

View File

@ -1,44 +0,0 @@
# Interface for iterating over a text file by line.
#
# Example usage:
#
# fi_open_file(${some_file})
#
# while(NOT fi_done)
# fi_get_next_line()
#
# message(STATUS "read line: ${fi_line}")
# endwhile()
macro(fi_check_done)
string(LENGTH "${fi_file_contents}" len)
set(fi_done FALSE PARENT_SCOPE)
if(len EQUAL 0)
set(fi_done TRUE PARENT_SCOPE)
endif()
endmacro()
function(fi_open_file file)
file(READ "${file}" fi_file_contents)
set(fi_file_contents "${fi_file_contents}" PARENT_SCOPE)
fi_check_done()
endfunction()
function(fi_get_next_line)
string(FIND "${fi_file_contents}" "\n" pos)
string(SUBSTRING "${fi_file_contents}" 0 ${pos} fi_line)
math(EXPR pos "${pos} + 1")
string(SUBSTRING "${fi_file_contents}" ${pos} -1 fi_file_contents)
fi_check_done()
set(fi_line "${fi_line}" PARENT_SCOPE)
set(fi_file_contents "${fi_file_contents}" PARENT_SCOPE)
endfunction()

View File

@ -1,153 +0,0 @@
# vim: ts=2 sw=2
# - Try to find the required ffmpeg components(default: AVFORMAT, AVUTIL, AVCODEC)
#
# Once done this will define
# FFMPEG_FOUND - System has the all required components.
# FFMPEG_INCLUDE_DIRS - Include directory necessary for using the required components headers.
# FFMPEG_LIBRARIES - Link these to use the required ffmpeg components.
# FFMPEG_DEFINITIONS - Compiler switches required for using the required ffmpeg components.
#
# For each of the components it will additionally set.
# - AVCODEC
# - AVDEVICE
# - AVFORMAT
# - AVFILTER
# - AVUTIL
# - POSTPROC
# - SWSCALE
# the following variables will be defined
# <component>_FOUND - System has <component>
# <component>_INCLUDE_DIRS - Include directory necessary for using the <component> headers
# <component>_LIBRARIES - Link these to use <component>
# <component>_DEFINITIONS - Compiler switches required for using <component>
# <component>_VERSION - The components version
#
# Copyright (c) 2006, Matthias Kretz, <kretz@kde.org>
# Copyright (c) 2008, Alexander Neundorf, <neundorf@kde.org>
# Copyright (c) 2011, Michael Jansen, <kde@michael-jansen.biz>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
include(FindPackageHandleStandardArgs)
# The default components were taken from a survey over other FindFFMPEG.cmake files
if (NOT FFmpeg_FIND_COMPONENTS)
set(FFmpeg_FIND_COMPONENTS AVCODEC AVFORMAT AVUTIL SWSCALE SWRESAMPLE X264 X265)
endif ()
#
### Macro: set_component_found
#
# Marks the given component as found if both *_LIBRARIES AND *_INCLUDE_DIRS is present.
#
macro(set_component_found _component )
if (${_component}_LIBRARIES AND ${_component}_INCLUDE_DIRS)
# message(STATUS " - ${_component} found.")
set(${_component}_FOUND TRUE)
else ()
# message(STATUS " - ${_component} not found.")
endif ()
endmacro()
#
### Macro: find_component
#
# Checks for the given component by invoking pkgconfig and then looking up the libraries and
# include directories.
#
macro(find_component _component _pkgconfig _library _header)
if (NOT WIN32)
# use pkg-config to get the directories and then use these values
# in the FIND_PATH() and FIND_LIBRARY() calls
find_package(PkgConfig)
if (PKG_CONFIG_FOUND)
pkg_check_modules(PC_${_component} ${_pkgconfig})
endif ()
endif (NOT WIN32)
find_path(${_component}_INCLUDE_DIRS ${_header}
HINTS
${PC_${_component}_INCLUDEDIR}
${PC_${_component}_INCLUDE_DIRS}
PATH_SUFFIXES
ffmpeg
)
find_library(${_component}_LIBRARIES NAMES ${_library}
HINTS
${PC_${_component}_LIBDIR}
${PC_${_component}_LIBRARY_DIRS}
)
set(${_component}_DEFINITIONS ${PC_${_component}_CFLAGS_OTHER} CACHE STRING "The ${_component} CFLAGS.")
set(${_component}_VERSION ${PC_${_component}_VERSION} CACHE STRING "The ${_component} version number.")
set_component_found(${_component})
mark_as_advanced(
${_component}_INCLUDE_DIRS
${_component}_LIBRARIES
${_component}_DEFINITIONS
${_component}_VERSION)
endmacro()
# Check for cached results. If there are skip the costly part.
if (NOT FFMPEG_LIBRARIES)
# Check for all possible component.
find_component(AVCODEC libavcodec avcodec libavcodec/avcodec.h)
find_component(AVFORMAT libavformat avformat libavformat/avformat.h)
find_component(AVDEVICE libavdevice avdevice libavdevice/avdevice.h)
find_component(AVUTIL libavutil avutil libavutil/avutil.h)
find_component(AVFILTER libavfilter avfilter libavfilter/avfilter.h)
find_component(SWSCALE libswscale swscale libswscale/swscale.h)
find_component(POSTPROC libpostproc postproc libpostproc/postprocess.h)
find_component(SWRESAMPLE libswresample swresample libswresample/swresample.h)
find_component(X264 x264 x264 x264.h)
find_component(X265 x265 x265 x265.h)
# Check if the required components were found and add their stuff to the FFMPEG_* vars.
foreach (_component ${FFmpeg_FIND_COMPONENTS})
if (${_component}_FOUND)
# message(STATUS "Required component ${_component} present.")
set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} ${${_component}_LIBRARIES})
set(FFMPEG_DEFINITIONS ${FFMPEG_DEFINITIONS} ${${_component}_DEFINITIONS})
list(APPEND FFMPEG_INCLUDE_DIRS ${${_component}_INCLUDE_DIRS})
else ()
# message(STATUS "Required component ${_component} missing.")
endif ()
endforeach ()
# Build the include path with duplicates removed.
if (FFMPEG_INCLUDE_DIRS)
list(REMOVE_DUPLICATES FFMPEG_INCLUDE_DIRS)
endif ()
# cache the vars.
set(FFMPEG_INCLUDE_DIRS ${FFMPEG_INCLUDE_DIRS} CACHE STRING "The FFmpeg include directories." FORCE)
set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} CACHE STRING "The FFmpeg libraries." FORCE)
set(FFMPEG_DEFINITIONS ${FFMPEG_DEFINITIONS} CACHE STRING "The FFmpeg cflags." FORCE)
mark_as_advanced(FFMPEG_INCLUDE_DIRS
FFMPEG_LIBRARIES
FFMPEG_DEFINITIONS)
endif ()
# Now set the noncached _FOUND vars for the components.
foreach (_component AVCODEC AVDEVICE AVFORMAT AVUTIL POSTPROCESS SWSCALE)
set_component_found(${_component})
endforeach ()
# Compile the list of required vars
set(_FFmpeg_REQUIRED_VARS FFMPEG_LIBRARIES FFMPEG_INCLUDE_DIRS)
foreach (_component ${FFmpeg_FIND_COMPONENTS})
list(APPEND _FFmpeg_REQUIRED_VARS ${_component}_LIBRARIES ${_component}_INCLUDE_DIRS)
endforeach ()
# Give a nice error message if some of the required vars are missing.
find_package_handle_standard_args(FFmpeg DEFAULT_MSG ${_FFmpeg_REQUIRED_VARS})

View File

@ -1,232 +1,231 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
FindGettext
-----------
Find GNU gettext tools
This module looks for the GNU gettext tools. This module defines the
following values:
::
GETTEXT_MSGMERGE_EXECUTABLE: the full path to the msgmerge tool.
GETTEXT_MSGFMT_EXECUTABLE: the full path to the msgfmt tool.
GETTEXT_FOUND: True if gettext has been found.
GETTEXT_VERSION_STRING: the version of gettext found (since CMake 2.8.8)
Additionally it provides the following macros:
GETTEXT_CREATE_TRANSLATIONS ( outputFile [ALL] file1 ... fileN )
::
This will create a target "translations" which will convert the
given input po files into the binary output mo file. If the
ALL option is used, the translations will also be created when
building the default target.
GETTEXT_PROCESS_POT_FILE( <potfile> [ALL] [INSTALL_DESTINATION <destdir>]
LANGUAGES <lang1> <lang2> ... )
::
Process the given pot file to mo files.
If INSTALL_DESTINATION is given then automatically install rules will
be created, the language subdirectory will be taken into account
(by default use share/locale/).
If ALL is specified, the pot file is processed when building the all target.
It creates a custom target "potfile".
GETTEXT_PROCESS_PO_FILES( <lang> [ALL] [INSTALL_DESTINATION <dir>]
PO_FILES <po1> <po2> ... )
::
Process the given po files to mo files for the given language.
If INSTALL_DESTINATION is given then automatically install rules will
be created, the language subdirectory will be taken into account
(by default use share/locale/).
If ALL is specified, the po files are processed when building the all target.
It creates a custom target "pofiles".
.. versionadded:: 3.2
If you wish to use the Gettext library (libintl), use :module:`FindIntl`.
#]=======================================================================]
#.rst:
# FindGettext
# -----------
#
# Find GNU gettext tools
#
# This module looks for the GNU gettext tools. This module defines the
# following values:
#
# ::
#
# GETTEXT_MSGMERGE_EXECUTABLE: the full path to the msgmerge tool.
# GETTEXT_MSGFMT_EXECUTABLE: the full path to the msgfmt tool.
# GETTEXT_FOUND: True if gettext has been found.
# GETTEXT_VERSION_STRING: the version of gettext found (since CMake 2.8.8)
#
#
#
# Additionally it provides the following macros:
#
# GETTEXT_CREATE_TRANSLATIONS ( outputFile [ALL] file1 ... fileN )
#
# ::
#
# This will create a target "translations" which will convert the
# given input po files into the binary output mo file. If the
# ALL option is used, the translations will also be created when
# building the default target.
#
# GETTEXT_PROCESS_POT_FILE( <potfile> [ALL] [INSTALL_DESTINATION <destdir>]
# LANGUAGES <lang1> <lang2> ... )
#
# ::
#
# Process the given pot file to mo files.
# If INSTALL_DESTINATION is given then automatically install rules will
# be created, the language subdirectory will be taken into account
# (by default use share/locale/).
# If ALL is specified, the pot file is processed when building the all traget.
# It creates a custom target "potfile".
#
# GETTEXT_PROCESS_PO_FILES( <lang> [ALL] [INSTALL_DESTINATION <dir>]
# PO_FILES <po1> <po2> ... )
#
# ::
#
# Process the given po files to mo files for the given language.
# If INSTALL_DESTINATION is given then automatically install rules will
# be created, the language subdirectory will be taken into account
# (by default use share/locale/).
# If ALL is specified, the po files are processed when building the all traget.
# It creates a custom target "pofiles".
#
# .. note::
# If you wish to use the Gettext library (libintl), use :module:`FindIntl`.
find_program(GETTEXT_MSGMERGE_EXECUTABLE msgmerge)
find_program(GETTEXT_MSGFMT_EXECUTABLE msgfmt)
if(GETTEXT_MSGMERGE_EXECUTABLE)
execute_process(COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --version
execute_process(COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --version
OUTPUT_VARIABLE gettext_version
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
get_filename_component(msgmerge_name ${GETTEXT_MSGMERGE_EXECUTABLE} NAME)
get_filename_component(msgmerge_namewe ${GETTEXT_MSGMERGE_EXECUTABLE} NAME_WE)
if (gettext_version MATCHES "^(${msgmerge_name}|${msgmerge_namewe}) \\([^\\)]*\\) ([0-9\\.]+[^ \n]*)")
set(GETTEXT_VERSION_STRING "${CMAKE_MATCH_2}")
endif()
unset(gettext_version)
unset(msgmerge_name)
unset(msgmerge_namewe)
get_filename_component(msgmerge_name ${GETTEXT_MSGMERGE_EXECUTABLE} NAME)
get_filename_component(msgmerge_namewe ${GETTEXT_MSGMERGE_EXECUTABLE} NAME_WE)
if (gettext_version MATCHES "^(${msgmerge_name}|${msgmerge_namewe}) \\([^\\)]*\\) ([0-9\\.]+[^ \n]*)")
set(GETTEXT_VERSION_STRING "${CMAKE_MATCH_2}")
endif()
unset(gettext_version)
unset(msgmerge_name)
unset(msgmerge_namewe)
endif()
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Gettext
REQUIRED_VARS GETTEXT_MSGMERGE_EXECUTABLE GETTEXT_MSGFMT_EXECUTABLE
VERSION_VAR GETTEXT_VERSION_STRING)
function(_GETTEXT_GET_UNIQUE_TARGET_NAME _name _unique_name)
set(propertyName "_GETTEXT_UNIQUE_COUNTER_${_name}")
get_property(currentCounter GLOBAL PROPERTY "${propertyName}")
if(NOT currentCounter)
set(currentCounter 1)
endif()
set(${_unique_name} "${_name}_${currentCounter}" PARENT_SCOPE)
math(EXPR currentCounter "${currentCounter} + 1")
set_property(GLOBAL PROPERTY ${propertyName} ${currentCounter} )
set(propertyName "_GETTEXT_UNIQUE_COUNTER_${_name}")
get_property(currentCounter GLOBAL PROPERTY "${propertyName}")
if(NOT currentCounter)
set(currentCounter 1)
endif()
set(${_unique_name} "${_name}_${currentCounter}" PARENT_SCOPE)
math(EXPR currentCounter "${currentCounter} + 1")
set_property(GLOBAL PROPERTY ${propertyName} ${currentCounter} )
endfunction()
macro(GETTEXT_CREATE_TRANSLATIONS _potFile _firstPoFileArg)
# make it a real variable, so we can modify it here
set(_firstPoFile "${_firstPoFileArg}")
# make it a real variable, so we can modify it here
set(_firstPoFile "${_firstPoFileArg}")
set(_gmoFiles)
get_filename_component(_potName ${_potFile} NAME)
string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _potBasename ${_potName})
get_filename_component(_absPotFile ${_potFile} ABSOLUTE)
set(_gmoFiles)
get_filename_component(_potName ${_potFile} NAME)
string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _potBasename ${_potName})
get_filename_component(_absPotFile ${_potFile} ABSOLUTE)
set(_addToAll)
if(${_firstPoFile} STREQUAL "ALL")
set(_addToAll "ALL")
set(_firstPoFile)
endif()
set(_addToAll)
if(${_firstPoFile} STREQUAL "ALL")
set(_addToAll "ALL")
set(_firstPoFile)
endif()
foreach (_currentPoFile ${_firstPoFile} ${ARGN})
get_filename_component(_absFile ${_currentPoFile} ABSOLUTE)
get_filename_component(_abs_PATH ${_absFile} PATH)
get_filename_component(_lang ${_absFile} NAME_WE)
set(_gmoFile ${CMAKE_CURRENT_BINARY_DIR}/${_lang}.gmo)
foreach (_currentPoFile ${_firstPoFile} ${ARGN})
get_filename_component(_absFile ${_currentPoFile} ABSOLUTE)
get_filename_component(_abs_PATH ${_absFile} PATH)
string(REGEX REPLACE "^.*/([^/]+)(\\.[^.]+)$" "\\1" _lang ${_absFile})
set(_gmoFile ${CMAKE_CURRENT_BINARY_DIR}/${_lang}.gmo)
add_custom_command(
OUTPUT ${_gmoFile}
# COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --quiet --update --backup=none -s ${_absFile} ${_absPotFile}
COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_absFile}
DEPENDS ${_absPotFile} ${_absFile}
)
add_custom_command(
OUTPUT ${_gmoFile}
#COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --quiet --update --backup=none -s ${_absFile} ${_absPotFile}
COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_absFile}
DEPENDS ${_absPotFile} ${_absFile}
)
install(FILES ${_gmoFile} DESTINATION share/locale/${_lang}/LC_MESSAGES RENAME ${_potBasename}.mo)
set(_gmoFiles ${_gmoFiles} ${_gmoFile})
install(FILES ${_gmoFile} DESTINATION share/locale/${_lang}/LC_MESSAGES RENAME ${_potBasename}.mo)
set(_gmoFiles ${_gmoFiles} ${_gmoFile})
endforeach ()
endforeach ()
if(NOT TARGET translations)
add_custom_target(translations)
endif()
if(NOT TARGET translations)
add_custom_target(translations)
endif()
_GETTEXT_GET_UNIQUE_TARGET_NAME(translations uniqueTargetName)
add_custom_target(${uniqueTargetName} ${_addToAll} DEPENDS ${_gmoFiles})
add_dependencies(translations ${uniqueTargetName})
add_custom_target(${uniqueTargetName} ${_addToAll} DEPENDS ${_gmoFiles})
add_dependencies(translations ${uniqueTargetName})
endmacro()
function(GETTEXT_PROCESS_POT_FILE _potFile)
set(_gmoFiles)
set(_options ALL)
set(_oneValueArgs INSTALL_DESTINATION)
set(_multiValueArgs LANGUAGES)
set(_gmoFiles)
set(_options ALL)
set(_oneValueArgs INSTALL_DESTINATION)
set(_multiValueArgs LANGUAGES)
CMAKE_PARSE_ARGUMENTS(_parsedArguments "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
CMAKE_PARSE_ARGUMENTS(_parsedArguments "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
get_filename_component(_potName ${_potFile} NAME)
string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _potBasename ${_potName})
get_filename_component(_absPotFile ${_potFile} ABSOLUTE)
get_filename_component(_potName ${_potFile} NAME)
string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _potBasename ${_potName})
get_filename_component(_absPotFile ${_potFile} ABSOLUTE)
foreach (_lang ${_parsedArguments_LANGUAGES})
set(_poFile "${CMAKE_CURRENT_BINARY_DIR}/${_lang}.po")
set(_gmoFile "${CMAKE_CURRENT_BINARY_DIR}/${_lang}.gmo")
foreach (_lang ${_parsedArguments_LANGUAGES})
set(_poFile "${CMAKE_CURRENT_BINARY_DIR}/${_lang}.po")
set(_gmoFile "${CMAKE_CURRENT_BINARY_DIR}/${_lang}.gmo")
add_custom_command(
OUTPUT "${_poFile}"
COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --quiet --update --backup=none -s ${_poFile} ${_absPotFile}
DEPENDS ${_absPotFile}
)
add_custom_command(
OUTPUT "${_poFile}"
COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --quiet --update --backup=none -s ${_poFile} ${_absPotFile}
DEPENDS ${_absPotFile}
)
add_custom_command(
OUTPUT "${_gmoFile}"
COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_poFile}
DEPENDS ${_absPotFile} ${_poFile}
)
add_custom_command(
OUTPUT "${_gmoFile}"
COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_poFile}
DEPENDS ${_absPotFile} ${_poFile}
)
if(_parsedArguments_INSTALL_DESTINATION)
install(FILES ${_gmoFile} DESTINATION ${_parsedArguments_INSTALL_DESTINATION}/${_lang}/LC_MESSAGES RENAME ${_potBasename}.mo)
endif()
list(APPEND _gmoFiles ${_gmoFile})
endforeach ()
if(_parsedArguments_INSTALL_DESTINATION)
install(FILES ${_gmoFile} DESTINATION ${_parsedArguments_INSTALL_DESTINATION}/${_lang}/LC_MESSAGES RENAME ${_potBasename}.mo)
endif()
list(APPEND _gmoFiles ${_gmoFile})
endforeach ()
if(NOT TARGET potfiles)
add_custom_target(potfiles)
add_custom_target(potfiles)
endif()
_GETTEXT_GET_UNIQUE_TARGET_NAME( potfiles uniqueTargetName)
if(_parsedArguments_ALL)
add_custom_target(${uniqueTargetName} ALL DEPENDS ${_gmoFiles})
else()
add_custom_target(${uniqueTargetName} DEPENDS ${_gmoFiles})
endif()
if(_parsedArguments_ALL)
add_custom_target(${uniqueTargetName} ALL DEPENDS ${_gmoFiles})
else()
add_custom_target(${uniqueTargetName} DEPENDS ${_gmoFiles})
endif()
add_dependencies(potfiles ${uniqueTargetName})
add_dependencies(potfiles ${uniqueTargetName})
endfunction()
function(GETTEXT_PROCESS_PO_FILES _lang)
set(_options ALL)
set(_oneValueArgs INSTALL_DESTINATION)
set(_multiValueArgs PO_FILES)
set(_gmoFiles)
set(_options ALL)
set(_oneValueArgs INSTALL_DESTINATION)
set(_multiValueArgs PO_FILES)
set(_gmoFiles)
CMAKE_PARSE_ARGUMENTS(_parsedArguments "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
CMAKE_PARSE_ARGUMENTS(_parsedArguments "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
foreach(_current_PO_FILE ${_parsedArguments_PO_FILES})
get_filename_component(_name ${_current_PO_FILE} NAME)
string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _basename ${_name})
set(_gmoFile ${CMAKE_CURRENT_BINARY_DIR}/${_basename}.gmo)
add_custom_command(OUTPUT ${_gmoFile}
COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_current_PO_FILE}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
DEPENDS ${_current_PO_FILE}
)
foreach(_current_PO_FILE ${_parsedArguments_PO_FILES})
get_filename_component(_name ${_current_PO_FILE} NAME)
string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _basename ${_name})
set(_gmoFile ${CMAKE_CURRENT_BINARY_DIR}/${_basename}.gmo)
add_custom_command(OUTPUT ${_gmoFile}
COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_current_PO_FILE}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
DEPENDS ${_current_PO_FILE}
)
if(_parsedArguments_INSTALL_DESTINATION)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${_basename}.gmo DESTINATION ${_parsedArguments_INSTALL_DESTINATION}/${_lang}/LC_MESSAGES/ RENAME ${_basename}.mo)
endif()
list(APPEND _gmoFiles ${_gmoFile})
endforeach()
if(_parsedArguments_INSTALL_DESTINATION)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${_basename}.gmo DESTINATION ${_parsedArguments_INSTALL_DESTINATION}/${_lang}/LC_MESSAGES/ RENAME ${_basename}.mo)
endif()
list(APPEND _gmoFiles ${_gmoFile})
endforeach()
if(NOT TARGET pofiles)
add_custom_target(pofiles)
add_custom_target(pofiles)
endif()
_GETTEXT_GET_UNIQUE_TARGET_NAME( pofiles uniqueTargetName)
if(_parsedArguments_ALL)
add_custom_target(${uniqueTargetName} ALL DEPENDS ${_gmoFiles})
else()
add_custom_target(${uniqueTargetName} DEPENDS ${_gmoFiles})
endif()
if(_parsedArguments_ALL)
add_custom_target(${uniqueTargetName} ALL DEPENDS ${_gmoFiles})
else()
add_custom_target(${uniqueTargetName} DEPENDS ${_gmoFiles})
endif()
add_dependencies(pofiles ${uniqueTargetName})
add_dependencies(pofiles ${uniqueTargetName})
endfunction()

110
cmake/FindOpenAL.cmake Normal file
View File

@ -0,0 +1,110 @@
#.rst:
# FindOpenAL
# ----------
#
#
#
# Locate OpenAL This module defines OPENAL_LIBRARY OPENAL_FOUND, if
# false, do not try to link to OpenAL OPENAL_INCLUDE_DIR, where to find
# the headers
#
# $OPENALDIR is an environment variable that would correspond to the
# ./configure --prefix=$OPENALDIR used in building OpenAL.
#
# Created by Eric Wing. This was influenced by the FindSDL.cmake
# module.
#=============================================================================
# Copyright 2005-2009 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
# This makes the presumption that you are include al.h like
# #include "al.h"
# and not
# #include <AL/al.h>
# The reason for this is that the latter is not entirely portable.
# Windows/Creative Labs does not by default put their headers in AL/ and
# OS X uses the convention <OpenAL/al.h>.
#
# For Windows, Creative Labs seems to have added a registry key for their
# OpenAL 1.1 installer. I have added that key to the list of search paths,
# however, the key looks like it could be a little fragile depending on
# if they decide to change the 1.00.0000 number for bug fix releases.
# Also, they seem to have laid down groundwork for multiple library platforms
# which puts the library in an extra subdirectory. Currently there is only
# Win32 and I have hardcoded that here. This may need to be adjusted as
# platforms are introduced.
# The OpenAL 1.0 installer doesn't seem to have a useful key I can use.
# I do not know if the Nvidia OpenAL SDK has a registry key.
#
# For OS X, remember that OpenAL was added by Apple in 10.4 (Tiger).
# To support the framework, I originally wrote special framework detection
# code in this module which I have now removed with CMake's introduction
# of native support for frameworks.
# In addition, OpenAL is open source, and it is possible to compile on Panther.
# Furthermore, due to bugs in the initial OpenAL release, and the
# transition to OpenAL 1.1, it is common to need to override the built-in
# framework.
# Per my request, CMake should search for frameworks first in
# the following order:
# ~/Library/Frameworks/OpenAL.framework/Headers
# /Library/Frameworks/OpenAL.framework/Headers
# /System/Library/Frameworks/OpenAL.framework/Headers
#
# On OS X, this will prefer the Framework version (if found) over others.
# People will have to manually change the cache values of
# OPENAL_LIBRARY to override this selection or set the CMake environment
# CMAKE_INCLUDE_PATH to modify the search paths.
find_path(OPENAL_INCLUDE_DIR al.h
HINTS
ENV OPENALDIR
PATH_SUFFIXES AL OpenAL
PATHS
~/Library/Frameworks
/Library/Frameworks
/sw # Fink
/opt/local # DarwinPorts
/opt/csw # Blastwave
/opt
[HKEY_LOCAL_MACHINE\\SOFTWARE\\Creative\ Labs\\OpenAL\ 1.1\ Software\ Development\ Kit\\1.00.0000;InstallDir]
)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(_OpenAL_ARCH_DIR libs/Win64)
else()
set(_OpenAL_ARCH_DIR libs/Win32)
endif()
find_library(OPENAL_LIBRARY
NAMES OpenAL al openal OpenAL32
HINTS
ENV OPENALDIR
PATH_SUFFIXES lib64 lib libs64 libs ${_OpenAL_ARCH_DIR}
PATHS
~/Library/Frameworks
/Library/Frameworks
/sw
/opt/local
/opt/csw
/opt
[HKEY_LOCAL_MACHINE\\SOFTWARE\\Creative\ Labs\\OpenAL\ 1.1\ Software\ Development\ Kit\\1.00.0000;InstallDir]
)
unset(_OpenAL_ARCH_DIR)
# handle the QUIETLY and REQUIRED arguments and set OPENAL_FOUND to TRUE if
# all listed variables are TRUE
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenAL DEFAULT_MSG OPENAL_LIBRARY OPENAL_INCLUDE_DIR)
mark_as_advanced(OPENAL_LIBRARY OPENAL_INCLUDE_DIR)

226
cmake/FindSDL2.cmake Normal file
View File

@ -0,0 +1,226 @@
# This module defines
# SDL2_LIBRARY, the name of the library to link against
# SDL2_FOUND, if false, do not try to link to SDL2
# SDL2_INCLUDE_DIR, where to find SDL.h
#
# If you have pkg-config, these extra variables are also defined:
# SDL2_DEFINITIONS, extra CFLAGS
# SDL2_EXTRA_LIBS, extra link libs
# SDL2_LINKER_FLAGS, extra link flags
#
# The latter two are automatically added to SDL2_LIBRARY
#
# To use them, add code such as:
#
# # SET(SDL2_STATIC ON) # if you want to link SDL2 statically
# FIND_PACKAGE(SDL2 REQUIRED)
# ADD_DEFINITIONS(${SDL2_DEFINITIONS})
# TARGET_LINK_LIBRARIES(your-executable-target ${SDL2_LIBRARY} ...)
#
# This module responds to the the flag:
# SDL2_BUILDING_LIBRARY
# If this is defined, then no SDL2main will be linked in because
# only applications need main().
# Otherwise, it is assumed you are building an application and this
# module will attempt to locate and set the the proper link flags
# as part of the returned SDL2_LIBRARY variable.
#
# If you want to link SDL2 statically, set SDL2_STATIC to ON.
#
# Don't forget to include SDLmain.h and SDLmain.m your project for the
# OS X framework based version. (Other versions link to -lSDL2main which
# this module will try to find on your behalf.) Also for OS X, this
# module will automatically add the -framework Cocoa on your behalf.
#
#
# Additional Note: If you see an empty SDL2_LIBRARY_TEMP in your configuration
# and no SDL2_LIBRARY, it means CMake did not find your SDL2 library
# (SDL2.dll, libsdl2.so, SDL2.framework, etc).
# Set SDL2_LIBRARY_TEMP to point to your SDL2 library, and configure again.
# Similarly, if you see an empty SDL2MAIN_LIBRARY, you should set this value
# as appropriate. These values are used to generate the final SDL2_LIBRARY
# variable, but when these values are unset, SDL2_LIBRARY does not get created.
#
#
# $SDL2DIR is an environment variable that would
# correspond to the ./configure --prefix=$SDL2DIR
# used in building SDL2.
# l.e.galup 9-20-02
#
# Modified by Eric Wing.
# Added code to assist with automated building by using environmental variables
# and providing a more controlled/consistent search behavior.
# Added new modifications to recognize OS X frameworks and
# additional Unix paths (FreeBSD, etc).
# Also corrected the header search path to follow "proper" SDL guidelines.
# Added a search for SDL2main which is needed by some platforms.
# Added a search for threads which is needed by some platforms.
# Added needed compile switches for MinGW.
#
# On OSX, this will prefer the Framework version (if found) over others.
# People will have to manually change the cache values of
# SDL2_LIBRARY to override this selection or set the CMake environment
# CMAKE_INCLUDE_PATH to modify the search paths.
#
# Note that the header path has changed from SDL3/SDL.h to just SDL.h
# This needed to change because "proper" SDL convention
# is #include "SDL.h", not <SDL2/SDL.h>. This is done for portability
# reasons because not all systems place things in SDL2/ (see FreeBSD).
#=============================================================================
# Copyright 2003-2009 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
SET(SDL2_SEARCH_PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local # Mac Homebrew and local installs
/usr
/sw # Fink
/opt/local # MacPorts
/opt/csw # OpenCSW (Solaris)
/opt
${SDL2_PATH}/include
${SDL2_PATH}/lib
)
FIND_PATH(SDL2_INCLUDE_DIR SDL.h
HINTS $ENV{SDL2DIR}
PATH_SUFFIXES SDL2
PATHS ${SDL2_SEARCH_PATHS}
)
SET(CURRENT_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
IF(SDL2_STATIC)
IF(WIN32)
SET(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a)
ELSE(WIN32)
SET(CMAKE_FIND_LIBRARY_SUFFIXES .a)
ENDIF(WIN32)
ENDIF(SDL2_STATIC)
FIND_LIBRARY(SDL2_LIBRARY_TEMP
NAMES SDL2
HINTS $ENV{SDL2DIR}
PATH_SUFFIXES lib64 lib lib/x64 lib/x86
PATHS ${SDL2_SEARCH_PATHS}
)
IF(NOT SDL2_BUILDING_LIBRARY)
IF(NOT ${SDL2_INCLUDE_DIR} MATCHES ".framework")
# Non-OS X framework versions expect you to also dynamically link to
# SDL2main. This is mainly for Windows and OS X. Other (Unix) platforms
# seem to provide SDL2main for compatibility even though they don't
# necessarily need it.
FIND_LIBRARY(SDL2MAIN_LIBRARY
NAMES SDL2main
HINTS
$ENV{SDL2DIR}
PATH_SUFFIXES lib64 lib lib/x64 lib/x86
PATHS ${SDL2_SEARCH_PATHS}
)
ENDIF(NOT ${SDL2_INCLUDE_DIR} MATCHES ".framework")
ENDIF(NOT SDL2_BUILDING_LIBRARY)
SET(CMAKE_FIND_LIBRARY_SUFFIXES ${CURRENT_FIND_LIBRARY_SUFFIXES})
UNSET(CURRENT_FIND_LIBRARY_SUFFIXES)
# SDL2 may require threads on your system.
# The Apple build may not need an explicit flag because one of the
# frameworks may already provide it.
# But for non-OSX systems, I will use the CMake Threads package.
IF(NOT APPLE)
FIND_PACKAGE(Threads)
ENDIF(NOT APPLE)
# MinGW needs an additional link flag, -mwindows (to make a GUI app)
# but we only add it when not making a Debug build.
# It's total link flags should look like -lmingw32 -lSDL2main -lSDL2 -mwindows
IF(MINGW)
SET(MINGW32_LIBRARY -lmingw32 CACHE STRING "MinGW library")
IF(NOT CMAKE_BUILD_TYPE STREQUAL Debug)
SET(MINGW32_LIBRARY ${MINGW32_LIBRARY} -mwindows)
ENDIF()
ENDIF(MINGW)
IF(SDL2_LIBRARY_TEMP)
# For SDL2main
IF(NOT SDL2_BUILDING_LIBRARY)
IF(SDL2MAIN_LIBRARY)
SET(SDL2_LIBRARY_TEMP ${SDL2MAIN_LIBRARY} ${SDL2_LIBRARY_TEMP})
ENDIF(SDL2MAIN_LIBRARY)
ENDIF(NOT SDL2_BUILDING_LIBRARY)
# For OS X, SDL2 uses Cocoa as a backend so it must link to Cocoa.
# CMake doesn't display the -framework Cocoa string in the UI even
# though it actually is there if I modify a pre-used variable.
# I think it has something to do with the CACHE STRING.
# So I use a temporary variable until the end so I can set the
# "real" variable in one-shot.
IF(APPLE)
SET(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} "-framework Cocoa")
ENDIF(APPLE)
# For threads, as mentioned Apple doesn't need this.
# In fact, there seems to be a problem if I used the Threads package
# and try using this line, so I'm just skipping it entirely for OS X.
IF(NOT APPLE)
SET(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} ${CMAKE_THREAD_LIBS_INIT})
ENDIF(NOT APPLE)
# For MinGW library
IF(MINGW)
SET(SDL2_LIBRARY_TEMP ${MINGW32_LIBRARY} ${SDL2_LIBRARY_TEMP} -lversion -limm32)
ENDIF(MINGW)
# Add some stuff from pkg-config, if available
IF(NOT PKG_CONFIG_EXECUTABLE)
FIND_PACKAGE(PkgConfig QUIET)
ENDIF(NOT PKG_CONFIG_EXECUTABLE)
IF(PKG_CONFIG_EXECUTABLE)
# get any definitions
EXECUTE_PROCESS(COMMAND ${PKG_CONFIG_EXECUTABLE} --cflags-only-other sdl2 OUTPUT_VARIABLE SDL2_DEFINITIONS ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
SET(SDL2_DEFINITIONS ${SDL2_DEFINITIONS} CACHE STRING "Extra CFLAGS for SDL2 from pkg-config")
# get any extra stuff needed for linking
IF(NOT SDL2_STATIC)
EXECUTE_PROCESS(COMMAND ${PKG_CONFIG_EXECUTABLE} --libs-only-other sdl2 OUTPUT_VARIABLE SDL2_LINKER_FLAGS_RAW ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
EXECUTE_PROCESS(COMMAND ${PKG_CONFIG_EXECUTABLE} --libs-only-l sdl2 OUTPUT_VARIABLE SDL2_EXTRA_LIBS_RAW ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
ELSE(NOT SDL2_STATIC)
EXECUTE_PROCESS(COMMAND ${PKG_CONFIG_EXECUTABLE} --static --libs-only-other sdl2 OUTPUT_VARIABLE SDL2_LINKER_FLAGS_RAW ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
EXECUTE_PROCESS(COMMAND ${PKG_CONFIG_EXECUTABLE} --static --libs-only-l sdl2 OUTPUT_VARIABLE SDL2_EXTRA_LIBS_RAW ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
ENDIF(NOT SDL2_STATIC)
STRING(REGEX REPLACE "[^ ]+SDL2[^ ]*" "" SDL2_EXTRA_LIBS_RAW2 "${SDL2_EXTRA_LIBS_RAW}")
STRING(REGEX REPLACE " +" ";" SDL2_EXTRA_LIBS "${SDL2_EXTRA_LIBS_RAW2}")
STRING(REGEX REPLACE " +" ";" SDL2_LINKER_FLAGS "${SDL2_LINKER_FLAGS_RAW}")
SET(SDL2_LINKER_FLAGS ${SDL2_LINKER_FLAGS} CACHE STRING "Linker flags for linking SDL2")
SET(SDL2_EXTRA_LIBS ${SDL2_EXTRA_LIBS} CACHE STRING "Extra libraries for linking SDL2")
SET(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} ${SDL2_EXTRA_LIBS} ${SDL2_LINKER_FLAGS})
ENDIF(PKG_CONFIG_EXECUTABLE)
# Set the final string here so the GUI reflects the final state.
SET(SDL2_LIBRARY ${SDL2_LIBRARY_TEMP} CACHE STRING "Where the SDL2 Library can be found")
# Set the temp variable to INTERNAL so it is not seen in the CMake GUI
SET(SDL2_LIBRARY_TEMP "${SDL2_LIBRARY_TEMP}" CACHE INTERNAL "")
ENDIF(SDL2_LIBRARY_TEMP)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2 REQUIRED_VARS SDL2_LIBRARY SDL2_INCLUDE_DIR)

365
cmake/FindSFML.cmake Normal file
View File

@ -0,0 +1,365 @@
# This script locates the SFML library
# ------------------------------------
#
# Usage
# -----
#
# When you try to locate the SFML libraries, you must specify which modules you want to use (system, window, graphics, network, audio, main).
# If none is given, the SFML_LIBRARIES variable will be empty and you'll end up linking to nothing.
# example:
# find_package(SFML COMPONENTS graphics window system) # find the graphics, window and system modules
#
# You can enforce a specific version, either MAJOR.MINOR or only MAJOR.
# If nothing is specified, the version won't be checked (i.e. any version will be accepted).
# example:
# find_package(SFML COMPONENTS ...) # no specific version required
# find_package(SFML 2 COMPONENTS ...) # any 2.x version
# find_package(SFML 2.4 COMPONENTS ...) # version 2.4 or greater
#
# By default, the dynamic libraries of SFML will be found. To find the static ones instead,
# you must set the SFML_STATIC_LIBRARIES variable to TRUE before calling find_package(SFML ...).
# Since you have to link yourself all the SFML dependencies when you link it statically, the following
# additional variables are defined: SFML_XXX_DEPENDENCIES and SFML_DEPENDENCIES (see their detailed
# description below).
# In case of static linking, the SFML_STATIC macro will also be defined by this script.
# example:
# set(SFML_STATIC_LIBRARIES TRUE)
# find_package(SFML 2 COMPONENTS network system)
#
# On Mac OS X if SFML_STATIC_LIBRARIES is not set to TRUE then by default CMake will search for frameworks unless
# CMAKE_FIND_FRAMEWORK is set to "NEVER" for example. Please refer to CMake documentation for more details.
# Moreover, keep in mind that SFML frameworks are only available as release libraries unlike dylibs which
# are available for both release and debug modes.
#
# If SFML is not installed in a standard path, you can use the SFML_ROOT CMake (or environment) variable
# to tell CMake where SFML is.
#
# Output
# ------
#
# This script defines the following variables:
# - For each specified module XXX (system, window, graphics, network, audio, main):
# - SFML_XXX_LIBRARY_DEBUG: the name of the debug library of the xxx module (set to SFML_XXX_LIBRARY_RELEASE is no debug version is found)
# - SFML_XXX_LIBRARY_RELEASE: the name of the release library of the xxx module (set to SFML_XXX_LIBRARY_DEBUG is no release version is found)
# - SFML_XXX_LIBRARY: the name of the library to link to for the xxx module (includes both debug and optimized names if necessary)
# - SFML_XXX_FOUND: true if either the debug or release library of the xxx module is found
# - SFML_XXX_DEPENDENCIES: the list of libraries the module depends on, in case of static linking
# - SFML_LIBRARIES: the list of all libraries corresponding to the required modules
# - SFML_FOUND: true if all the required modules are found
# - SFML_INCLUDE_DIR: the path where SFML headers are located (the directory containing the SFML/Config.hpp file)
# - SFML_DEPENDENCIES: the list of libraries SFML depends on, in case of static linking
#
# example:
# find_package(SFML 2 COMPONENTS system window graphics audio REQUIRED)
# include_directories(${SFML_INCLUDE_DIR})
# add_executable(myapp ...)
# target_link_libraries(myapp ${SFML_LIBRARIES})
# define the SFML_STATIC macro if static build was chosen
if(SFML_STATIC_LIBRARIES)
add_definitions(-DSFML_STATIC)
endif()
# define the list of search paths for headers and libraries
set(FIND_SFML_PATHS
${SFML_ROOT}
$ENV{SFML_ROOT}
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt)
# find the SFML include directory
find_path(SFML_INCLUDE_DIR SFML/Config.hpp
PATH_SUFFIXES include
PATHS ${FIND_SFML_PATHS})
# check the version number
set(SFML_VERSION_OK TRUE)
if(SFML_FIND_VERSION AND SFML_INCLUDE_DIR)
# extract the major and minor version numbers from SFML/Config.hpp
# we have to handle framework a little bit differently:
if("${SFML_INCLUDE_DIR}" MATCHES "SFML.framework")
set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/Headers/Config.hpp")
else()
set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/SFML/Config.hpp")
endif()
FILE(READ "${SFML_CONFIG_HPP_INPUT}" SFML_CONFIG_HPP_CONTENTS)
STRING(REGEX REPLACE ".*#define SFML_VERSION_MAJOR ([0-9]+).*" "\\1" SFML_VERSION_MAJOR "${SFML_CONFIG_HPP_CONTENTS}")
STRING(REGEX REPLACE ".*#define SFML_VERSION_MINOR ([0-9]+).*" "\\1" SFML_VERSION_MINOR "${SFML_CONFIG_HPP_CONTENTS}")
STRING(REGEX REPLACE ".*#define SFML_VERSION_PATCH ([0-9]+).*" "\\1" SFML_VERSION_PATCH "${SFML_CONFIG_HPP_CONTENTS}")
if (NOT "${SFML_VERSION_PATCH}" MATCHES "^[0-9]+$")
set(SFML_VERSION_PATCH 0)
endif()
math(EXPR SFML_REQUESTED_VERSION "${SFML_FIND_VERSION_MAJOR} * 10000 + ${SFML_FIND_VERSION_MINOR} * 100 + ${SFML_FIND_VERSION_PATCH}")
# if we could extract them, compare with the requested version number
if (SFML_VERSION_MAJOR)
# transform version numbers to an integer
math(EXPR SFML_VERSION "${SFML_VERSION_MAJOR} * 10000 + ${SFML_VERSION_MINOR} * 100 + ${SFML_VERSION_PATCH}")
# compare them
if(SFML_VERSION LESS SFML_REQUESTED_VERSION)
set(SFML_VERSION_OK FALSE)
endif()
else()
# SFML version is < 2.0
if (SFML_REQUESTED_VERSION GREATER 10900)
set(SFML_VERSION_OK FALSE)
set(SFML_VERSION_MAJOR 1)
set(SFML_VERSION_MINOR x)
set(SFML_VERSION_PATCH x)
endif()
endif()
endif()
# find the requested modules
set(SFML_FOUND TRUE) # will be set to false if one of the required modules is not found
foreach(FIND_SFML_COMPONENT ${SFML_FIND_COMPONENTS})
string(TOLOWER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_LOWER)
string(TOUPPER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_UPPER)
set(FIND_SFML_COMPONENT_NAME sfml-${FIND_SFML_COMPONENT_LOWER})
# no suffix for sfml-main, it is always a static library
if(FIND_SFML_COMPONENT_LOWER STREQUAL "main")
# release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
else()
# static release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}-s
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# static debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-s-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# dynamic release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# dynamic debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# choose the entries that fit the requested link type
if(SFML_STATIC_LIBRARIES)
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE})
endif()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG})
endif()
else()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE})
endif()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG})
endif()
endif()
endif()
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG OR SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
# library found
set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND TRUE)
# if both are found, set SFML_XXX_LIBRARY to contain both
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY debug ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG}
optimized ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
endif()
# if only one debug/release variant is found, set the other to be equal to the found one
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
# debug and not release
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG})
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG})
endif()
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG)
# release and not debug
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
endif()
else()
# library not found
set(SFML_FOUND FALSE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND FALSE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY "")
set(FIND_SFML_MISSING "${FIND_SFML_MISSING} SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY")
endif()
# mark as advanced
MARK_AS_ADVANCED(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG)
# add to the global list of libraries
set(SFML_LIBRARIES ${SFML_LIBRARIES} "${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY}")
endforeach()
# in case of static linking, we must also define the list of all the dependencies of SFML libraries
if(SFML_STATIC_LIBRARIES)
# detect the OS
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
set(FIND_SFML_OS_WINDOWS 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
set(FIND_SFML_OS_LINUX 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
set(FIND_SFML_OS_FREEBSD 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
set(FIND_SFML_OS_MACOSX 1)
endif()
# start with an empty list
set(SFML_DEPENDENCIES)
set(FIND_SFML_DEPENDENCIES_NOTFOUND)
# macro that searches for a 3rd-party library
macro(find_sfml_dependency output friendlyname)
# No lookup in environment variables (PATH on Windows), as they may contain wrong library versions
find_library(${output} NAMES ${ARGN} PATHS ${FIND_SFML_PATHS} PATH_SUFFIXES lib NO_SYSTEM_ENVIRONMENT_PATH)
if(${${output}} STREQUAL "${output}-NOTFOUND")
unset(output)
set(FIND_SFML_DEPENDENCIES_NOTFOUND "${FIND_SFML_DEPENDENCIES_NOTFOUND} ${friendlyname}")
endif()
endmacro()
# sfml-system
list(FIND SFML_FIND_COMPONENTS "system" FIND_SFML_SYSTEM_COMPONENT)
if(NOT ${FIND_SFML_SYSTEM_COMPONENT} EQUAL -1)
# update the list -- these are only system libraries, no need to find them
if(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD OR FIND_SFML_OS_MACOSX)
set(SFML_SYSTEM_DEPENDENCIES "pthread")
endif()
if(FIND_SFML_OS_LINUX)
set(SFML_SYSTEM_DEPENDENCIES ${SFML_SYSTEM_DEPENDENCIES} "rt")
endif()
if(FIND_SFML_OS_WINDOWS)
set(SFML_SYSTEM_DEPENDENCIES "winmm")
endif()
set(SFML_DEPENDENCIES ${SFML_SYSTEM_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-network
list(FIND SFML_FIND_COMPONENTS "network" FIND_SFML_NETWORK_COMPONENT)
if(NOT ${FIND_SFML_NETWORK_COMPONENT} EQUAL -1)
# update the list -- these are only system libraries, no need to find them
if(FIND_SFML_OS_WINDOWS)
set(SFML_NETWORK_DEPENDENCIES "ws2_32")
endif()
set(SFML_DEPENDENCIES ${SFML_NETWORK_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-window
list(FIND SFML_FIND_COMPONENTS "window" FIND_SFML_WINDOW_COMPONENT)
if(NOT ${FIND_SFML_WINDOW_COMPONENT} EQUAL -1)
# find libraries
if(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD)
find_sfml_dependency(X11_LIBRARY "X11" X11)
find_sfml_dependency(XRANDR_LIBRARY "Xrandr" Xrandr)
endif()
if(FIND_SFML_OS_LINUX)
find_sfml_dependency(UDEV_LIBRARIES "UDev" udev libudev)
endif()
# update the list
if(FIND_SFML_OS_WINDOWS)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "opengl32" "winmm" "gdi32")
elseif(FIND_SFML_OS_LINUX)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "GL" ${X11_LIBRARY} ${XRANDR_LIBRARY} ${UDEV_LIBRARIES})
elseif(FIND_SFML_OS_FREEBSD)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "GL" ${X11_LIBRARY} ${XRANDR_LIBRARY} "usbhid")
elseif(FIND_SFML_OS_MACOSX)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "-framework OpenGL -framework Foundation -framework AppKit -framework IOKit -framework Carbon")
endif()
set(SFML_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-graphics
list(FIND SFML_FIND_COMPONENTS "graphics" FIND_SFML_GRAPHICS_COMPONENT)
if(NOT ${FIND_SFML_GRAPHICS_COMPONENT} EQUAL -1)
# find libraries
find_sfml_dependency(FREETYPE_LIBRARY "FreeType" freetype)
find_sfml_dependency(JPEG_LIBRARY "libjpeg" jpeg)
# update the list
set(SFML_GRAPHICS_DEPENDENCIES ${FREETYPE_LIBRARY} ${JPEG_LIBRARY})
set(SFML_DEPENDENCIES ${SFML_GRAPHICS_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-audio
list(FIND SFML_FIND_COMPONENTS "audio" FIND_SFML_AUDIO_COMPONENT)
if(NOT ${FIND_SFML_AUDIO_COMPONENT} EQUAL -1)
# find libraries
find_sfml_dependency(OPENAL_LIBRARY "OpenAL" openal openal32)
find_sfml_dependency(OGG_LIBRARY "Ogg" ogg)
find_sfml_dependency(VORBIS_LIBRARY "Vorbis" vorbis)
find_sfml_dependency(VORBISFILE_LIBRARY "VorbisFile" vorbisfile)
find_sfml_dependency(VORBISENC_LIBRARY "VorbisEnc" vorbisenc)
find_sfml_dependency(FLAC_LIBRARY "FLAC" FLAC)
# update the list
set(SFML_AUDIO_DEPENDENCIES ${OPENAL_LIBRARY} ${FLAC_LIBRARY} ${VORBISENC_LIBRARY} ${VORBISFILE_LIBRARY} ${VORBIS_LIBRARY} ${OGG_LIBRARY})
set(SFML_DEPENDENCIES ${SFML_DEPENDENCIES} ${SFML_AUDIO_DEPENDENCIES})
endif()
endif()
# handle errors
if(NOT SFML_VERSION_OK)
# SFML version not ok
set(FIND_SFML_ERROR "SFML found but version too low (requested: ${SFML_FIND_VERSION}, found: ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR}.${SFML_VERSION_PATCH})")
set(SFML_FOUND FALSE)
elseif(SFML_STATIC_LIBRARIES AND FIND_SFML_DEPENDENCIES_NOTFOUND)
set(FIND_SFML_ERROR "SFML found but some of its dependencies are missing (${FIND_SFML_DEPENDENCIES_NOTFOUND})")
set(SFML_FOUND FALSE)
elseif(NOT SFML_FOUND)
# include directory or library not found
set(FIND_SFML_ERROR "Could NOT find SFML (missing: ${FIND_SFML_MISSING})")
endif()
if (NOT SFML_FOUND)
if(SFML_FIND_REQUIRED)
# fatal error
message(FATAL_ERROR ${FIND_SFML_ERROR})
elseif(NOT SFML_FIND_QUIETLY)
# error but continue
message("${FIND_SFML_ERROR}")
endif()
endif()
# handle success
if(SFML_FOUND AND NOT SFML_FIND_QUIETLY)
message(STATUS "Found SFML ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR}.${SFML_VERSION_PATCH} in ${SFML_INCLUDE_DIR}")
endif()

76
cmake/FindSSP.cmake Normal file
View File

@ -0,0 +1,76 @@
# FindSSP.cmake
#
# Find libssp necessary when using gcc with e.g. -fstack-protector=strong
#
# See: http://wiki.osdev.org/Stack_Smashing_Protector
#
# To use:
#
# put a copy into your <project_root>/cmake/
#
# In your main CMakeLists.txt do something like this:
#
# if(WIN32)
# set(SSP_STATIC ON)
# endif()
#
# find_package(SSP)
#
# if(SSP_LIBRARY)
# set(CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} ${SSP_LIBRARY}")
# set(CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_LINK_EXECUTABLE} ${SSP_LIBRARY}")
# endif()
# only do this when compiling with gcc/g++
if(NOT CMAKE_COMPILER_IS_GNUCXX)
return()
endif()
function(FindSSP)
if(NOT CMAKE_CXX_COMPILER AND CMAKE_C_COMPILER)
set(CMAKE_CXX_COMPILER ${CMAKE_C_COMPILER})
endif()
foreach(arg ${CMAKE_CXX_COMPILER_ARG1} ${CMAKE_CXX_COMPILER_ARG2} ${CMAKE_CXX_COMPILER_ARG3} ${CMAKE_CXX_COMPILER_ARG4} ${CMAKE_CXX_COMPILER_ARG5} ${CMAKE_CXX_COMPILER_ARG6} ${CMAKE_CXX_COMPILER_ARG7} ${CMAKE_CXX_COMPILER_ARG8} ${CMAKE_CXX_COMPILER_ARG9})
string(STRIP ${arg} arg)
set(gcc_args "${gcc_args};${arg}")
endforeach()
execute_process(COMMAND ${CMAKE_CXX_COMPILER} ${gcc_args} --print-prog-name=gcc OUTPUT_VARIABLE GCC_EXECUTABLE OUTPUT_STRIP_TRAILING_WHITESPACE)
if(WIN32 AND NOT MSYS)
execute_process(COMMAND where.exe ${GCC_EXECUTABLE} OUTPUT_VARIABLE GCC_EXECUTABLE OUTPUT_STRIP_TRAILING_WHITESPACE)
else()
execute_process(COMMAND sh -c "command -v ${GCC_EXECUTABLE}" OUTPUT_VARIABLE GCC_EXECUTABLE OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
get_filename_component(GCC_DIRNAME "${GCC_EXECUTABLE}" DIRECTORY)
execute_process(COMMAND ${CMAKE_CXX_COMPILER} ${gcc_args} --print-libgcc-file-name OUTPUT_VARIABLE LIBGCC_FILE OUTPUT_STRIP_TRAILING_WHITESPACE)
get_filename_component(LIBGCC_DIRNAME "${LIBGCC_FILE}" DIRECTORY)
set(SSP_SEARCH_PATHS ${GCC_DIRNAME} ${LIBGCC_DIRNAME})
if(SSP_STATIC)
if(WIN32)
set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a)
else()
set(CMAKE_FIND_LIBRARY_SUFFIXES .a)
endif()
endif()
find_library(SSP_LIBRARY
NAMES ssp libssp
HINTS ${SSP_SEARCH_PATHS}
PATH_SUFFIXES lib64 lib lib/x64 lib/x86
)
set(SSP_LIBRARY PARENT_SCOPE)
endfunction()
FindSSP()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(SSP REQUIRED_VARS SSP_LIBRARY)

View File

@ -7,6 +7,23 @@
#
# Returns the refspec and sha hash of the current head revision
#
# git_describe(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe on the source tree, and adjusting
# the output so that it tests false if an error occurs.
#
# git_get_exact_tag(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe --exact-match on the source tree,
# and adjusting the output so that it tests false if there was no exact
# matching tag.
#
# git_local_changes(<var>)
#
# Returns either "CLEAN" or "DIRTY" with respect to uncommitted changes.
# Uses the return code of "git diff-index --quiet HEAD --".
# Does not regard untracked files.
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
@ -68,3 +85,84 @@ function(get_git_head_revision _refspecvar _hashvar)
set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE)
set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE)
endfunction()
function(git_describe _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
return()
endif()
# TODO sanitize
#if((${ARGN}" MATCHES "&&") OR
# (ARGN MATCHES "||") OR
# (ARGN MATCHES "\\;"))
# message("Please report the following error to the project!")
# message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
#endif()
#message(STATUS "Arguments to execute_process: ${ARGN}")
execute_process(COMMAND
"${GIT_EXECUTABLE}"
describe
${hash}
${ARGN}
WORKING_DIRECTORY
"${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE
res
OUTPUT_VARIABLE
out
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_get_exact_tag _var)
git_describe(out --exact-match ${ARGN})
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_local_changes _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
return()
endif()
execute_process(COMMAND
"${GIT_EXECUTABLE}"
diff-index --quiet HEAD --
WORKING_DIRECTORY
"${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE
res
OUTPUT_VARIABLE
out
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(res EQUAL 0)
set(${_var} "CLEAN" PARENT_SCOPE)
else()
set(${_var} "DIRTY" PARENT_SCOPE)
endif()
endfunction()

View File

@ -3,9 +3,10 @@ function(git_version version revision version_release)
set(${revision} "" CACHE STRING "Latest Git Tag Revision" FORCE)
set(${version_release} 0 CACHE STRING "Is this a versioned release without revision" FORCE)
find_package(Git)
if(GIT_FOUND AND EXISTS "${CMAKE_SOURCE_DIR}/.git")
# get latest version from tag history
execute_process(COMMAND "${GIT_EXECUTABLE}" tag "--format=%(align:width=20)%(refname:short)%(end)%(if)%(*objectname)%(then)%(*objectname)%(else)%(objectname)%(end)" --sort=-v:refname OUTPUT_VARIABLE tags OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
execute_process(COMMAND "${GIT_EXECUTABLE}" tag "--format=%(align:width=20)%(refname:short)%(end)%(if)%(*objectname)%(then)%(*objectname)%(else)%(objectname)%(end)" --sort=-creatordate OUTPUT_VARIABLE tags OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
# if no tags (e.g. shallow clone) do nothing
if(tags STREQUAL "")

View File

@ -1,40 +1,29 @@
function(host_compile src dst_cmd)
if(CMAKE_CROSSCOMPILING)
unset(link_flags)
set(dst "${dst_cmd}")
unset(link_flags)
if(CMAKE_HOST_WIN32)
if(CMAKE_COMPILER_IS_GNUCXX)
set(link_flags -Wl,--subsystem,console)
endif()
if(CMAKE_HOST_WIN32)
if(NOT dst MATCHES "\\.[Ee][Xx][Ee]\$")
set(dst "${dst_cmd}.exe")
endif()
if(MSVC)
set(msvc_compile_script ${CMAKE_SOURCE_DIR}/cmake/MSVC_x86_Host_Compile.cmake)
add_custom_command(
OUTPUT ${dst}
DEPENDS ${src} ${msvc_compile_script}
COMMAND ${CMAKE_COMMAND} -D "src=${src}" -D "dst=${dst}" -P ${msvc_compile_script}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
else()
set(dst ${dst_cmd})
# Assume: cc foo.c -o foo # will work on most hosts
add_custom_command(
OUTPUT ${dst}
DEPENDS ${src}
COMMAND cc ${src} -o ${dst} ${link_flags}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
if(CMAKE_COMPILER_IS_GNUCXX)
set(link_flags -Wl,--subsystem,console)
endif()
else()
get_filename_component(dst ${dst_cmd} NAME)
set(dst "${dst_cmd}")
endif()
add_executable(${dst} ${src})
if(NOT MSVC)
# assume cc foo.c -o foo # will work on most hosts
set(compile_command cc ${src} -o ${dst} ${link_flags})
else()
# special case for Visual Studio
set(compile_command cl ${src} /link "/out:${dst}")
endif()
# this is necessary because we override main with SDL_main
target_compile_definitions(${dst} PRIVATE -Dmain=main)
execute_process(COMMAND ${compile_command} OUTPUT_VARIABLE compile_out ERROR_VARIABLE compile_out RESULT_VARIABLE compile_result)
if(NOT compile_result EQUAL 0)
message(FATAL_ERROR "Failed compiling ${src} for the host: ${compile_out}")
endif()
endfunction()

32
cmake/LLVMToolchain.cmake Normal file
View File

@ -0,0 +1,32 @@
function(use_llvm_toolchain)
if(CMAKE_C_COMPILER_ID STREQUAL Clang)
set(compiler "${CMAKE_C_COMPILER}")
elseif(CMAKE_CXX_COMPILER_ID STREQUAL Clang)
set(compiler "${CMAKE_CXX_COMPILER}")
else()
return()
endif()
foreach(tool ar ranlib ld nm objdump as)
execute_process(
COMMAND "${compiler}" -print-prog-name=llvm-${tool}
OUTPUT_VARIABLE prog_path
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(prog_path MATCHES "^/")
if(tool STREQUAL ld)
set(tool linker)
elseif(tool STREQUAL as)
set(tool asm_compiler)
endif()
string(TOUPPER ${tool} utool)
set(CMAKE_${utool} "${prog_path}" PARENT_SCOPE)
set(CMAKE_${utool} "${prog_path}" CACHE FILEPATH "${tool}" FORCE)
endif()
endforeach()
endfunction()
use_llvm_toolchain()

View File

@ -1,24 +0,0 @@
# This is a hack to be run with cmake -P to compile a source C program passed
# in `src` to the `dst` executable using the host MSVC x86 toolchain.
find_program(cl_path NAME cl.exe HINTS ENV PATH)
string(REGEX REPLACE "[^/]+/cl\\.exe$" "x86/cl.exe" cl_path "${cl_path}")
set(orig_lib "$ENV{LIB}")
set(new_lib)
foreach(lib $ENV{LIB})
string(REGEX REPLACE "[^\\]+$" "x86" lib "${lib}")
list(APPEND new_lib "${lib}")
endforeach()
set(ENV{LIB} "${new_lib}")
execute_process(
COMMAND ${cl_path} /nologo ${src} /Fe:${dst}
OUTPUT_QUIET
)
set(ENV{LIB} "${orig_lib}")

View File

@ -11,8 +11,8 @@
# In addition, the following commands are called with the package manager's
# paths:
#
# include_directories()
# link_directories()
# INCLUDE_DIRECTORIES()
# LINK_DIRECTORIES()
#
# The paths of package managers not currently in $ENV{PATH} are added to
# CMAKE_IGNORE_PATH .
@ -41,75 +41,66 @@
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
if(NOT APPLE)
return()
endif()
IF(NOT APPLE)
RETURN()
ENDIF()
if(NOT "$ENV{IN_NIX_SHELL}" STREQUAL "")
message(STATUS "Configuring for Nix")
IF(EXISTS /usr/local/bin/brew AND $ENV{PATH} MATCHES "(^|:)/usr/local/bin/?(:|$)")
MESSAGE("-- Configuring for Mac Homebrew")
set(NIX ON)
SET(MAC_HOMEBREW ON)
set(CMAKE_IGNORE_PATH /opt/local /opt/local/bin /opt/local/include /opt/local/Library/Frameworks /opt/local/lib ${CMAKE_IGNORE_PATH})
set(CMAKE_IGNORE_PATH /sw /sw/bin /sw/include /sw/Library/Frameworks /sw/lib ${CMAKE_IGNORE_PATH})
elseif(EXISTS /usr/local/bin/brew AND $ENV{PATH} MATCHES "(^|:)/usr/local/bin/?(:|$)")
message(STATUS "Configuring for Mac Homebrew")
SET(CMAKE_IGNORE_PATH /opt/local /opt/local/bin /opt/local/include /opt/local/Library/Frameworks /opt/local/lib ${CMAKE_IGNORE_PATH})
SET(CMAKE_IGNORE_PATH /sw /sw/bin /sw/include /sw/Library/Frameworks /sw/lib ${CMAKE_IGNORE_PATH})
set(MAC_HOMEBREW ON)
SET(CMAKE_FRAMEWORK_PATH /usr/local/Frameworks ${CMAKE_FRAMEWORK_PATH})
set(CMAKE_IGNORE_PATH /opt/local /opt/local/bin /opt/local/include /opt/local/Library/Frameworks /opt/local/lib ${CMAKE_IGNORE_PATH})
set(CMAKE_IGNORE_PATH /sw /sw/bin /sw/include /sw/Library/Frameworks /sw/lib ${CMAKE_IGNORE_PATH})
SET(CMAKE_INCLUDE_PATH /usr/local/include ${CMAKE_INCLUDE_PATH})
INCLUDE_DIRECTORIES("/usr/local/include")
set(CMAKE_FRAMEWORK_PATH /usr/local/Frameworks ${CMAKE_FRAMEWORK_PATH})
SET(CMAKE_LIBRARY_PATH /usr/local/lib ${CMAKE_LIBRARY_PATH})
LINK_DIRECTORIES("/usr/local/lib")
set(CMAKE_INCLUDE_PATH /usr/local/include ${CMAKE_INCLUDE_PATH})
include_directories("/usr/local/include")
SET(CMAKE_PROGRAM_PATH /usr/local/bin ${CMAKE_PROGRAM_PATH})
ELSEIF(EXISTS /opt/local/bin/port AND $ENV{PATH} MATCHES "(^|:)/opt/local/bin/?(:|$)")
MESSAGE("-- Configuring for MacPorts")
set(CMAKE_LIBRARY_PATH /usr/local/lib ${CMAKE_LIBRARY_PATH})
link_directories("/usr/local/lib")
SET(MACPORTS ON)
set(CMAKE_PROGRAM_PATH /usr/local/bin ${CMAKE_PROGRAM_PATH})
SET(CMAKE_IGNORE_PATH /sw /sw/bin /sw/include /sw/Library/Frameworks /sw/lib ${CMAKE_IGNORE_PATH})
set(ZLIB_ROOT /usr/local/opt/zlib)
elseif(EXISTS /opt/local/bin/port AND $ENV{PATH} MATCHES "(^|:)/opt/local/bin/?(:|$)")
message(STATUS "Configuring for MacPorts")
SET(CMAKE_FRAMEWORK_PATH /opt/local/Library/Frameworks ${CMAKE_FRAMEWORK_PATH})
set(MACPORTS ON)
SET(CMAKE_INCLUDE_PATH /opt/local/include ${CMAKE_INCLUDE_PATH})
INCLUDE_DIRECTORIES("/opt/local/include")
set(CMAKE_IGNORE_PATH /sw /sw/bin /sw/include /sw/Library/Frameworks /sw/lib ${CMAKE_IGNORE_PATH})
SET(CMAKE_LIBRARY_PATH /opt/local/lib ${CMAKE_LIBRARY_PATH})
LINK_DIRECTORIES("/opt/local/lib")
set(CMAKE_FRAMEWORK_PATH /opt/local/Library/Frameworks ${CMAKE_FRAMEWORK_PATH})
SET(CMAKE_PROGRAM_PATH /opt/local/bin ${CMAKE_PROGRAM_PATH})
ELSEIF(EXISTS /sw/bin/fink AND $ENV{PATH} MATCHES "(^|:)/sw/bin/?(:|$)")
MESSAGE("-- Configuring for Fink")
set(CMAKE_INCLUDE_PATH /opt/local/include ${CMAKE_INCLUDE_PATH})
include_directories("/opt/local/include")
SET(FINK ON)
set(CMAKE_LIBRARY_PATH /opt/local/lib ${CMAKE_LIBRARY_PATH})
link_directories("/opt/local/lib")
SET(CMAKE_IGNORE_PATH /opt/local /opt/local/bin /opt/local/include /opt/local/Library/Frameworks /opt/local/lib ${CMAKE_IGNORE_PATH})
set(CMAKE_PROGRAM_PATH /opt/local/bin ${CMAKE_PROGRAM_PATH})
elseif(EXISTS /sw/bin/fink AND $ENV{PATH} MATCHES "(^|:)/sw/bin/?(:|$)")
message(STATUS "Configuring for Fink")
SET(CMAKE_FRAMEWORK_PATH /sw/Library/Frameworks ${CMAKE_FRAMEWORK_PATH})
set(FINK ON)
SET(CMAKE_INCLUDE_PATH /sw/include ${CMAKE_INCLUDE_PATH})
INCLUDE_DIRECTORIES("/sw/include")
set(CMAKE_IGNORE_PATH /opt/local /opt/local/bin /opt/local/include /opt/local/Library/Frameworks /opt/local/lib ${CMAKE_IGNORE_PATH})
SET(CMAKE_LIBRARY_PATH /sw/lib ${CMAKE_LIBRARY_PATH})
LINK_DIRECTORIES("/sw/lib")
set(CMAKE_FRAMEWORK_PATH /sw/Library/Frameworks ${CMAKE_FRAMEWORK_PATH})
set(CMAKE_INCLUDE_PATH /sw/include ${CMAKE_INCLUDE_PATH})
include_directories("/sw/include")
set(CMAKE_LIBRARY_PATH /sw/lib ${CMAKE_LIBRARY_PATH})
link_directories("/sw/lib")
set(CMAKE_PROGRAM_PATH /sw/bin ${CMAKE_PROGRAM_PATH})
else()
SET(CMAKE_PROGRAM_PATH /sw/bin ${CMAKE_PROGRAM_PATH})
ELSE()
# no package manager found or active, do nothing
return()
endif()
RETURN()
ENDIF()
# only ignore /usr/local if brew is installed and not in the PATH
# in other cases, it is the user's personal installations
if(NOT MAC_HOMEBREW AND EXISTS /usr/local/bin/brew)
set(CMAKE_IGNORE_PATH /usr/local /usr/local/bin /usr/local/include /usr/local/Library/Frameworks /usr/local/lib /usr/local/opt/gettext/bin /usr/local/opt/gettext/lib ${CMAKE_IGNORE_PATH})
endif()
IF(NOT MAC_HOMEBREW AND EXISTS /usr/local/bin/brew)
SET(CMAKE_IGNORE_PATH /usr/local /usr/local/bin /usr/local/include /usr/local/Library/Frameworks /usr/local/lib ${CMAKE_IGNORE_PATH})
ENDIF()

View File

@ -1,244 +0,0 @@
# Set TAG_RELEASE to ON/TRUE/1 to increment minor, or to new version, or to
# UNDO to undo release.
# Increment version.
# Update CHANGELOG.md with git log.
# Make release commit.
# Tag release commit.
if(NOT EXISTS "${CMAKE_SOURCE_DIR}/.git")
message(FATAL_ERROR "releases can only be done from a git clone")
endif()
find_program(GPG_EXECUTABLE gpg)
if(NOT GPG_EXECUTABLE)
message(FATAL_ERROR "gpg must be installed and set up with your key to make a release")
endif()
# From: https://gist.github.com/alorence/59d18896aaad5188b7b4.
macro(CURRENT_DATE RESULT)
if(CMAKE_HOST_SYSTEM MATCHES Windows OR ((NOT DEFINED CMAKE_HOST_SYSTEM) AND WIN32))
execute_process(COMMAND "cmd" " /C date /T" OUTPUT_VARIABLE ${RESULT})
string(REGEX REPLACE ".*(..)/(..)/(....).*" "\\3-\\1-\\2" ${RESULT} ${${RESULT}})
else()
execute_process(COMMAND "date" "+%Y-%m-%d" OUTPUT_VARIABLE ${RESULT})
endif()
endmacro()
function(make_release_commit_and_tag)
# First make sure we are on master.
execute_process(
COMMAND git rev-parse --short --abbrev-ref=strict HEAD
OUTPUT_VARIABLE git_branch
OUTPUT_STRIP_TRAILING_WHITESPACE
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
if(NOT git_branch STREQUAL master)
message(FATAL_ERROR "you must be on the git master branch to release")
endif()
execute_process(
COMMAND git status --porcelain=2
OUTPUT_VARIABLE git_status
OUTPUT_STRIP_TRAILING_WHITESPACE
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
string(LENGTH "${git_status}" git_status_length)
if(NOT git_status_length EQUAL 0)
message(FATAL_ERROR "working tree must be clean to do a release")
endif()
execute_process(
COMMAND git tag --sort=-v:refname
OUTPUT_VARIABLE git_tags
OUTPUT_STRIP_TRAILING_WHITESPACE
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
string(REGEX REPLACE ";" "\\\\;" git_tags_lines "${git_tags}")
string(REGEX REPLACE "\r?\n" ";" git_tags_lines "${git_tags_lines}")
foreach(line ${git_tags_lines})
if(line MATCHES "^v[0-9]")
set(git_last_tag ${line})
break()
endif()
endforeach()
if(NOT DEFINED git_last_tag)
message(FATAL_ERROR "cannot find last release tag")
endif()
execute_process(
COMMAND git log ${git_last_tag}.. "--pretty=format:* %h - %s [%aL]"
OUTPUT_VARIABLE release_log
OUTPUT_STRIP_TRAILING_WHITESPACE
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
# Calculate new release version, unless it was passed in.
if(TAG_RELEASE STREQUAL UNDO)
execute_process(
COMMAND git tag -d ${git_last_tag}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
execute_process(
COMMAND git reset HEAD~1
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
execute_process(
COMMAND git checkout HEAD CHANGELOG.md
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
message(FATAL_ERROR [=[
**** RELEASE COMMIT AND TAG HAVE BEEN REMOVED ****"
The git and working tree state have been restored to their state before the
TAG_RELEASE operation.
Ignore the following cmake error.
]=])
elseif(NOT (TAG_RELEASE STREQUAL TRUE OR TAG_RELEASE STREQUAL ON OR TAG_RELEASE STREQUAL 1))
set(new_tag ${TAG_RELEASE})
else()
string(REGEX MATCH "\\.[0-9]+$" last_tag_minor_part ${git_last_tag})
string(REGEX REPLACE "\\.[0-9]+$" "" last_tag_minor_stripped ${git_last_tag})
string(SUBSTRING ${last_tag_minor_part} 1 -1 last_tag_minor)
math(EXPR last_minor_incremented "${last_tag_minor} + 1")
string(CONCAT new_tag ${last_tag_minor_stripped} . ${last_minor_incremented})
endif()
# Make sure tag begins with "v".
if(NOT new_tag MATCHES "^v")
set(new_tag "v${new_tag}")
endif()
# But remove the "v" for the version string.
string(REGEX REPLACE "^v" "" new_version ${new_tag})
current_date(current_date)
# Rewrite CHANGELOG.md
# First make a copy for backing out.
configure_file(
${CMAKE_SOURCE_DIR}/CHANGELOG.md
${CMAKE_BINARY_DIR}/CHANGELOG.md.orig
COPYONLY
)
# Now read it and add the new release.
include(FileIterator)
fi_open_file(${CMAKE_SOURCE_DIR}/CHANGELOG.md)
set(work_file ${CMAKE_BINARY_DIR}/CHANGELOG.md.work)
file(REMOVE ${work_file})
set(last_release_found FALSE)
while(NOT fi_done)
fi_get_next_line()
if(NOT last_release_found AND fi_line MATCHES "^## \\[[0-9]")
set(last_release_found TRUE)
set(tag_line "## [${new_version}] - ${current_date}")
string(LENGTH "${tag_line}" tag_line_length)
unset(tag_line_under_bar)
foreach(i RANGE 1 ${tag_line_length})
set(tag_line_under_bar "=${tag_line_under_bar}")
endforeach()
file(APPEND ${work_file} ${tag_line} "\n")
file(APPEND ${work_file} ${tag_line_under_bar} "\n")
file(APPEND ${work_file} "${release_log}" "\n")
file(APPEND ${work_file} "\n")
endif()
file(APPEND ${work_file} "${fi_line}" "\n")
endwhile()
# Convert to UNIX line endings on Windows, just copy the file otherwise.
if(CMAKE_HOST_SYSTEM MATCHES Windows OR ((NOT DEFINED CMAKE_HOST_SYSTEM) AND WIN32))
if(NOT DEFINED POWERSHELL)
message(FATAL_ERROR "Powershell is required to convert line endings on Windows.")
endif()
execute_process(
COMMAND ${POWERSHELL} -NoLogo -NoProfile -ExecutionPolicy Bypass -Command [=[
$text = [IO.File]::ReadAllText("CHANGELOG.md.work") -replace "`r`n", "`n"
[IO.File]::WriteAllText("CHANGELOG.md", $text)
]=]
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
else()
configure_file(
${CMAKE_BINARY_DIR}/CHANGELOG.md.work
${CMAKE_BINARY_DIR}/CHANGELOG.md
COPYONLY
)
endif()
# Copy the new file and add it to the commit.
configure_file(
${CMAKE_BINARY_DIR}/CHANGELOG.md
${CMAKE_SOURCE_DIR}/CHANGELOG.md
COPYONLY
)
execute_process(
COMMAND git add CHANGELOG.md
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
message(FATAL_ERROR "
Release prepared.
Edit CHANGELOG.md to remove any non-user-facing commits, and optionally add any
release notes.
Run the following commands to commit the change:
git commit -m'release ${new_tag}' --signoff -S
git tag -s -m'${new_tag}' ${new_tag}
To rollback these changes, run this command:
cmake .. -DTAG_RELEASE=UNDO
==== IF YOU ARE SURE YOU WANT TO RELEASE, THIS **CANNOT** BE REVERSED ====
Run the following to push the release commit and tag:
git push
git push --tags
Ignore the 'configuration incomplete' message following, this mode does not
build anything.
")
endfunction()
make_release_commit_and_tag()

View File

@ -1,53 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file LICENCE.txt or https://cmake.org/licensing for details.
function(add_metal_shader_library TARGET)
cmake_parse_arguments(PARSE_ARGV 1 _amsl
""
"STANDARD"
""
)
add_library(${TARGET} MODULE ${_amsl_UNPARSED_ARGUMENTS})
set_target_properties(${TARGET} PROPERTIES
DEBUG_POSTFIX ""
XCODE_PRODUCT_TYPE com.apple.product-type.metal-library
XCODE_ATTRIBUTE_MTL_FAST_MATH "YES"
XCODE_ATTRIBUTE_MTL_ENABLE_DEBUG_INFO[variant=Debug] "INCLUDE_SOURCE"
XCODE_ATTRIBUTE_MTL_ENABLE_DEBUG_INFO[variant=RelWithDebInfo] "INCLUDE_SOURCE"
XCODE_ATTRIBUTE_MTL_HEADER_SEARCH_PATHS "$(HEADER_SEARCH_PATHS)"
)
if(_amsl_STANDARD AND _amsl_STANDARD MATCHES "metal([0-9]+)\.([0-9]+)")
target_compile_options(${TARGET}
PRIVATE "-std=${_amsl_STANDARD}"
)
set_target_properties(${TARGET} PROPERTIES
XCODE_ATTRIBUTE_MTL_LANGUAGE_REVISION "Metal${CMAKE_MATCH_1}${CMAKE_MATCH_2}"
)
endif()
endfunction()
function(target_embed_metal_shader_libraries TARGET)
cmake_parse_arguments(PARSE_ARGV 1 _temsl
""
""
""
)
if(${CMAKE_VERSION} VERSION_GREATER_EQUAL 3.28 AND ${CMAKE_GENERATOR} STREQUAL "Xcode")
set_target_properties(${TARGET} PROPERTIES
XCODE_EMBED_RESOURCES "${_temsl_UNPARSED_ARGUMENTS}"
)
else()
foreach(SHADERLIB IN LISTS _temsl_UNPARSED_ARGUMENTS)
add_dependencies(${TARGET} ${SHADERLIB})
add_custom_command(TARGET ${TARGET} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_FILE:${SHADERLIB}>" "$<TARGET_BUNDLE_CONTENT_DIR:${TARGET}>/Resources/$<TARGET_FILE_NAME:${SHADERLIB}>"
VERBATIM
)
endforeach()
endif()
endfunction()

View File

@ -1,210 +0,0 @@
option(BUILD_TESTING "Build testing" ON)
option(BUILD_SHARED_LIBS "Build dynamic libraries" OFF)
option(TRANSLATIONS_ONLY "Build only the translations.zip" OFF)
if(TRANSLATIONS_ONLY)
set(BUILD_DEFAULT OFF)
else()
set(BUILD_DEFAULT ON)
endif()
set(ENABLE_SDL_DEFAULT ${BUILD_DEFAULT})
if(WIN32 OR APPLE)
set(ENABLE_SDL_DEFAULT OFF)
endif()
# Static linking
set(VBAM_STATIC_DEFAULT OFF)
if(VCPKG_TARGET_TRIPLET MATCHES -static OR CMAKE_TOOLCHAIN_FILE MATCHES "mxe|-static")
set(VBAM_STATIC_DEFAULT ON)
elseif(MINGW OR MSYS)
# Default to static builds on MinGW and all MSYS2 envs.
set(VBAM_STATIC_DEFAULT ON)
endif()
option(VBAM_STATIC "Try to link all libraries statically" ${VBAM_STATIC_DEFAULT})
if(VBAM_STATIC)
set(SDL2_STATIC ON)
set(SDL3_STATIC ON)
set(SFML_STATIC_LIBRARIES ON)
set(FFMPEG_STATIC ON)
set(OPENAL_STATIC ON)
set_property(GLOBAL PROPERTY LINK_SEARCH_START_STATIC ON)
set_property(GLOBAL PROPERTY LINK_SEARCH_END_STATIC ON)
if(MSVC)
set(CMAKE_FIND_LIBRARY_SUFFIXES .lib)
else()
list(INSERT CMAKE_FIND_LIBRARY_SUFFIXES 0 .a)
endif()
endif()
find_package(SDL3 QUIET)
option(ENABLE_SDL3 "Use SDL3" "${SDL3_FOUND}")
if(ENABLE_SDL3)
find_package(SDL3 CONFIG REQUIRED)
else()
find_package(SDL2 CONFIG REQUIRED)
endif()
option(ENABLE_GENERIC_FILE_DIALOGS "Use generic file dialogs" OFF)
option(DISABLE_OPENGL "Disable OpenGL" OFF)
option(ENABLE_SDL "Build the SDL port" ${ENABLE_SDL_DEFAULT})
option(ENABLE_WX "Build the wxWidgets port" ${BUILD_DEFAULT})
option(ENABLE_DEBUGGER "Enable the debugger" ON)
option(ENABLE_ASAN "Enable -fsanitize=address by default. Requires debug build with GCC/Clang" OFF)
if(ENABLE_SDL3)
set(CMAKE_C_FLAGS "-DENABLE_SDL3 ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-DENABLE_SDL3 ${CMAKE_CXX_FLAGS}")
endif()
if(DISABLE_OPENGL)
set(CMAKE_C_FLAGS "-DNO_OPENGL -DNO_OGL ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-DNO_OPENGL -DNO_OGL ${CMAKE_CXX_FLAGS}")
endif()
option(ENABLE_ASM "Enable x86 ASM related options" OFF)
# The ARM ASM core seems to be very buggy, see #98 and #54. Default to it being
# OFF for the time being, until it is either fixed or replaced.
option(ENABLE_ASM_CORE "Enable x86 ASM CPU cores (EXPERIMENTAL)" OFF)
set(ASM_SCALERS_DEFAULT ${ENABLE_ASM})
set(MMX_DEFAULT ${ENABLE_ASM})
option(ENABLE_ASM_SCALERS "Enable x86 ASM graphic filters" ${ASM_SCALERS_DEFAULT})
include(CMakeDependentOption)
cmake_dependent_option(ENABLE_MMX "Enable MMX" ${MMX_DEFAULT} "ENABLE_ASM_SCALERS" OFF)
option(ENABLE_LIRC "Enable LIRC support" OFF)
# Add support for Homebrew, MacPorts and Fink on macOS
option(DISABLE_MACOS_PACKAGE_MANAGERS "Set to TRUE to disable support for macOS Homebrew, MacPorts and Fink." FALSE)
if(APPLE AND NOT DISABLE_MACOS_PACKAGE_MANAGERS)
include(MacPackageManagers)
endif()
find_package(PkgConfig)
# Link / SFML
if(NOT TRANSLATIONS_ONLY)
set(ENABLE_LINK_DEFAULT ON)
endif()
option(ENABLE_LINK "Enable GBA linking functionality" ${ENABLE_LINK_DEFAULT})
# FFMpeg
set(FFMPEG_DEFAULT OFF)
set(FFMPEG_COMPONENTS AVCODEC AVFORMAT SWSCALE AVUTIL SWRESAMPLE X264 X265)
set(FFMPEG_COMPONENT_VERSIONS AVCODEC>=58.18.100 AVFORMAT>=58.12.100 SWSCALE>=5.1.100 AVUTIL>=56.14.100 SWRESAMPLE>=3.1.100 X264>=0 X265>=0)
option(FIND_FFMPEG_APPLE "Find using Apple FFMPEG function" OFF)
if(NOT TRANSLATIONS_ONLY AND (NOT DEFINED ENABLE_FFMPEG OR ENABLE_FFMPEG))
set(FFMPEG_DEFAULT ON)
if (APPLE OR MINGW)
find_package(AppleFFMPEG COMPONENTS ${FFMPEG_COMPONENTS})
else()
find_package(FFMPEG COMPONENTS ${FFMPEG_COMPONENTS})
endif()
# check versions, but only if pkgconfig is available
if(FFMPEG_FOUND AND PKG_CONFIG_FOUND AND NOT CMAKE_TOOLCHAIN_FILE MATCHES vcpkg)
foreach(component ${FFMPEG_COMPONENT_VERSIONS})
string(REPLACE ">=" ";" parts ${component})
list(GET parts 0 name)
list(GET parts 1 version)
if((NOT DEFINED ${name}_VERSION) OR ${name}_VERSION VERSION_LESS ${version})
set(FFMPEG_FOUND OFF)
endif()
endforeach()
endif()
if(NOT FFMPEG_FOUND)
set(FFMPEG_DEFAULT OFF)
endif()
endif()
option(ENABLE_FFMPEG "Enable ffmpeg A/V recording" ${FFMPEG_DEFAULT})
# Online Updates
set(ONLINEUPDATES_DEFAULT OFF)
if(DEFINED(UPSTREAM_RELEASE) AND UPSTREAM_RELEASE)
set(ONLINEUPDATES_DEFAULT ON)
endif()
option(ENABLE_ONLINEUPDATES "Enable online update checks" ${ONLINEUPDATES_DEFAULT})
option(HTTPS "Use https URL for winsparkle" ON)
# We generally don't want LTO when debugging because it makes linking slow
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(LTO_DEFAULT OFF)
else()
set(LTO_DEFAULT ON)
endif()
option(ENABLE_LTO "Compile with Link Time Optimization" ${LTO_DEFAULT})
option(ENABLE_GBA_LOGGING "Enable extended GBA logging" ON)
option(UPSTREAM_RELEASE "do some optimizations and release automation tasks" OFF)
if(WIN32)
# not yet implemented
option(ENABLE_DIRECT3D "Enable Direct3D rendering for the wxWidgets port" OFF)
set(XAUDIO2_DEFAULT ON)
if ((MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL Clang) OR (MINGW AND X86))
# TODO: We should update the XAudio headers to build with clang-cl. See
# https://github.com/visualboyadvance-m/visualboyadvance-m/issues/1021
set(XAUDIO2_DEFAULT OFF)
endif()
option(ENABLE_XAUDIO2 "Enable xaudio2 sound output for the wxWidgets port" ${XAUDIO2_DEFAULT})
endif()
find_package(OpenAL QUIET)
set(OPENAL_DEFAULT ${OpenAL_FOUND})
if(MINGW AND X86)
# OpenAL-Soft uses avrt.dll which is not available on Windows XP.
set(OPENAL_DEFAULT OFF)
endif()
option(ENABLE_OPENAL "Enable OpenAL-Soft sound output for the wxWidgets port" ${OPENAL_DEFAULT})
set(ENABLE_FAUDIO_DEFAULT OFF)
find_package(FAudio QUIET)
if(FAudio_FOUND AND NOT (MINGW AND X86))
set(ENABLE_FAUDIO_DEFAULT ON)
endif()
option(ENABLE_FAUDIO "Enable FAudio sound output for the wxWidgets port" ${ENABLE_FAUDIO_DEFAULT})
option(ZIP_SUFFIX [=[suffix for release zip files, e.g. "-somebranch".zip]=] OFF)
# The SDL port can't be built without debugging support
if(NOT ENABLE_DEBUGGER AND ENABLE_SDL)
message(FATAL_ERROR "The SDL port can't be built without debugging support")
endif()
if(TRANSLATIONS_ONLY AND (ENABLE_SDL OR ENABLE_WX))
message(FATAL_ERROR "The SDL and wxWidgets ports can't be built when TRANSLATIONS_ONLY is enabled")
endif()
option(GPG_SIGNATURES "Create GPG signatures for release files" OFF)
if(APPLE)
set(wx_mac_patched_default OFF)
if(UPSTREAM_RELEASE)
set(wx_mac_patched_default ON)
endif()
option(WX_MAC_PATCHED "A build of wxWidgets that is patched for the alert sound bug is being used" ${wx_mac_patched_default})
endif()

71
cmake/PathRun.cmake Normal file
View File

@ -0,0 +1,71 @@
function(make_path_run_wrapper cmd target)
get_filename_component(cmd_resolved "${cmd}" REALPATH)
get_filename_component(base_name "${cmd_resolved}" NAME)
get_filename_component(dir_name "${cmd_resolved}" DIRECTORY)
set(source "${target}.c")
file(WRITE "${source}"
"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define BUF_SZ 4096
#ifdef _WIN32
#include <process.h>
#define PATH_SEP ';'
#define setenv(var, val, dummy) _putenv_s(var, val)
#define execvp my_execvp
#else
#include <unistd.h>
#define PATH_SEP ':'
#endif
char* dir_name = \"${dir_name}\";
char* base_name = \"${base_name}\";
int main(int argc, char** argv) {
size_t dir_len = strlen(dir_name);
char* path = getenv(\"PATH\");
size_t path_len = strlen(path);
char* new_path = malloc(dir_len + path_len + 2);
char** new_argv = malloc(sizeof(char*) * argc);
char** p;
char buf[BUF_SZ];
strcpy(new_path, dir_name);
new_path[dir_len] = PATH_SEP;
strcpy(new_path + dir_len + 1, path);
setenv(\"PATH\", new_path, 1);
free(new_path);
p = new_argv;
*(p++) = base_name;
while (*(++argv)) *(p++) = *argv;
*p = NULL;
execvp(base_name, new_argv);
// this is only reached if exec failed
snprintf(buf, BUF_SZ, \"%s: exec failed\", argv[0]);
perror(buf);
return EXIT_FAILURE;
}
#ifdef _WIN32
int my_execvp(char* cmd, char** argv) {
int ret = _spawnvp(_P_WAIT, cmd, argv);
if (ret == -1) return ret;
exit(ret);
}
#endif
")
include(HostCompile)
host_compile("${source}" "${target}")
endfunction()

View File

@ -1,13 +0,0 @@
# Remove StrawberryPerl from the PATH environment variable due to various build
# pollution.
unset(new_path)
foreach(p $ENV{PATH})
if(NOT p MATCHES "(^|\\\\)[Ss]trawberry\\\\([Pp]erl|[Cc])\\\\(.*\\\\)?[Bb]in$")
list(APPEND new_path ${p})
endif()
endforeach()
set(ENV{PATH} "${new_path}")
# vim:sw=4 et sts=4 ts=8:

View File

@ -1,644 +0,0 @@
if(TRANSLATIONS_ONLY)
return()
endif()
if(NOT DEFINED VCPKG_TARGET_TRIPLET)
if(NOT WIN32)
return()
endif()
# Check if we are in an MSVC environment.
find_program(cl_exe_path NAME cl.exe HINTS ENV PATH)
if(ENV{CXX} MATCHES "cl.exe$" OR cl_exe_path)
# Infer the architecture from the LIB folders.
foreach(lib $ENV{LIB})
if(lib MATCHES "x64$")
set(VBAM_VCPKG_PLATFORM "x64-windows-static")
break()
endif()
if(lib MATCHES "x86$")
set(VBAM_VCPKG_PLATFORM "x86-windows-static")
break()
endif()
if(lib MATCHES "ARM64$")
set(VBAM_VCPKG_PLATFORM "arm64-windows-static")
foreach(path $ENV{PATH})
if(path MATCHES "[Hh]ost[Xx]64")
set(VCPKG_HOST_TRIPLET "x64-windows-static" CACHE STRING "Vcpkg host triplet" FORCE)
set(VCPKG_USE_HOST_TOOLS ON CACHE BOOL "Use vcpkg host tools" FORCE)
break()
endif()
endforeach()
break()
endif()
endforeach()
# If all else fails, try to use a sensible default.
if(NOT DEFINED VBAM_VCPKG_PLATFORM)
set(VBAM_VCPKG_PLATFORM "x64-windows-static")
endif()
unset(cl_exe_path)
elseif (NOT DEFINED CMAKE_CXX_COMPILER)
# No way to infer the compiler.
return()
elseif(${CMAKE_CXX_COMPILER} MATCHES "clang-cl.exe$" OR ${CMAKE_CXX_COMPILER} MATCHES "clang-cl$")
# For stand-alone clang-cl, assume x64.
set(VBAM_VCPKG_PLATFORM "x64-windows-static")
endif()
if (NOT DEFINED VBAM_VCPKG_PLATFORM)
# Probably not an MSVC environment.
return()
endif()
set(VCPKG_TARGET_TRIPLET ${VBAM_VCPKG_PLATFORM} CACHE STRING "Vcpkg target triplet (ex. x64-windows-static)" FORCE)
message(STATUS "Inferred VCPKG_TARGET_TRIPLET=${VCPKG_TARGET_TRIPLET}")
endif()
function(vcpkg_seconds)
if(CMAKE_HOST_SYSTEM MATCHES Windows OR ((NOT DEFINED CMAKE_HOST_SYSTEM) AND WIN32))
execute_process(
COMMAND cmd /c echo %TIME:~0,8%
OUTPUT_VARIABLE time
)
else()
execute_process(
COMMAND date +%H:%M:%S
OUTPUT_VARIABLE time
)
endif()
string(SUBSTRING "${time}" 0 2 hours)
string(SUBSTRING "${time}" 3 2 minutes)
string(SUBSTRING "${time}" 6 2 secs)
math(EXPR seconds "(${hours} * 60 * 60) + (${minutes} * 60) + ${secs}")
set(seconds ${seconds} PARENT_SCOPE)
endfunction()
function(vcpkg_check_git_status git_status)
# The VS vcpkg component cannot be written to without elevation.
if(NOT git_status EQUAL 0 AND NOT VCPKG_ROOT MATCHES "Visual Studio")
message(FATAL_ERROR "Error updating vcpkg from git, please make sure git for windows is installed correctly, it can be installed from Visual Studio components")
endif()
endfunction()
function(vcpkg_get_first_upgrade vcpkg_exe)
# First get the list of upgraded ports.
execute_process(
COMMAND ${vcpkg_exe} upgrade
OUTPUT_VARIABLE upgradable
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET
WORKING_DIRECTORY ${VCPKG_ROOT}
)
string(REGEX REPLACE "\r?\n" ";" upgrade_lines "${upgradable}")
unset(first_upgrade)
foreach(line ${upgrade_lines})
if(line MATCHES "^ [* ] [^ ]*:")
string(REGEX REPLACE "^ [* ] ([^[]+).*" "\\1" pkg ${line})
string(REGEX REPLACE "^[^:]+:(.+)$" "\\1" triplet ${line})
if(triplet STREQUAL "${VCPKG_TARGET_TRIPLET}")
# Prefer upgrading zlib before anything else.
if(NOT first_upgrade OR pkg MATCHES zlib)
set(first_upgrade ${pkg})
endif()
endif()
endif()
endforeach()
if(DEFINED first_upgrade)
set(first_upgrade ${first_upgrade} PARENT_SCOPE)
endif()
endfunction()
function(vcpkg_deps_fixup vcpkg_exe)
# Get installed list.
execute_process(
COMMAND ${vcpkg_exe} list
OUTPUT_VARIABLE pkg_list
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET
WORKING_DIRECTORY ${VCPKG_ROOT}
)
# If libvorbis is NOT installed but libogg is, remove libvorbis recursively.
if(pkg_list MATCHES libogg AND (NOT pkg_list MATCHES libvorbis))
execute_process(
COMMAND ${vcpkg_exe} remove --recurse libogg:${VCPKG_TARGET_TRIPLET}
WORKING_DIRECTORY ${VCPKG_ROOT}
)
endif()
endfunction()
function(vcpkg_is_installed vcpkg_exe pkg_name pkg_ver pkg_triplet powershell outvar)
set(${outvar} FALSE PARENT_SCOPE)
unset(CMAKE_MATCH_1)
string(REGEX REPLACE "-r([0-9]+)\$" "" pkg_ver ${pkg_ver})
set(pkg_rev ${CMAKE_MATCH_1})
string(REPLACE "-" "." pkg_ver ${pkg_ver})
if(NOT DEFINED VCPKG_INSTALLED_COUNT)
execute_process(
COMMAND ${powershell}
-executionpolicy bypass -noprofile
-command "import-module '${CMAKE_BINARY_DIR}/vcpkg-binpkg/vcpkg-binpkg.psm1'; vcpkg-list"
OUTPUT_VARIABLE vcpkg_list_text
)
string(REGEX REPLACE "\r?\n" ";" vcpkg_list_raw "${vcpkg_list_text}")
set(VCPKG_INSTALLED_COUNT 0 PARENT_SCOPE)
foreach(pkg ${vcpkg_list_raw})
if(NOT pkg MATCHES "^([^:[]+)[^:]*:([^ ]+) +([0-9][^ ]*) +.*\$")
continue()
endif()
set(inst_pkg_name ${CMAKE_MATCH_1})
set(inst_pkg_ver ${CMAKE_MATCH_3})
set(inst_pkg_triplet ${CMAKE_MATCH_2})
unset(CMAKE_MATCH_1)
string(REGEX REPLACE "#([0-9]+)\$" "" inst_pkg_ver ${inst_pkg_ver})
if(CMAKE_MATCH_1)
set(inst_pkg_rev ${CMAKE_MATCH_1})
else()
set(inst_pkg_rev FALSE)
endif()
string(REPLACE "-" "." inst_pkg_ver ${inst_pkg_ver})
list(APPEND VCPKG_INSTALLED ${inst_pkg_name} ${inst_pkg_ver} ${inst_pkg_rev} ${inst_pkg_triplet})
math(EXPR VCPKG_INSTALLED_COUNT "${VCPKG_INSTALLED_COUNT} + 1")
endforeach()
set(VCPKG_INSTALLED ${VCPKG_INSTALLED} PARENT_SCOPE)
set(VCPKG_INSTALLED_COUNT ${VCPKG_INSTALLED_COUNT} PARENT_SCOPE)
endif()
if(NOT VCPKG_INSTALLED_COUNT GREATER 0)
return()
endif()
math(EXPR idx_max "(${VCPKG_INSTALLED_COUNT} - 1) * 4")
foreach(idx RANGE 0 ${idx_max} 4)
math(EXPR idx_ver "${idx} + 1")
math(EXPR idx_rev "${idx} + 2")
math(EXPR idx_triplet "${idx} + 3")
list(GET VCPKG_INSTALLED ${idx} inst_pkg_name)
list(GET VCPKG_INSTALLED ${idx_ver} inst_pkg_ver)
list(GET VCPKG_INSTALLED ${idx_rev} inst_pkg_rev)
list(GET VCPKG_INSTALLED ${idx_triplet} inst_pkg_triplet)
if(NOT inst_pkg_triplet STREQUAL pkg_triplet)
continue()
endif()
if(inst_pkg_name STREQUAL pkg_name
AND pkg_ver VERSION_LESS inst_pkg_ver
OR (pkg_ver VERSION_EQUAL inst_pkg_ver
AND ((NOT pkg_rev AND NOT inst_pkg_rev)
OR (pkg_rev AND inst_pkg_rev AND (NOT pkg_rev GREATER inst_pkg_rev)))))
set(${outvar} TRUE PARENT_SCOPE)
return()
endif()
endforeach()
endfunction()
function(get_triplet_package_list triplet)
if(EXISTS "${CMAKE_BINARY_DIR}/binary_package_list_${triplet}.html")
return()
endif()
file(
DOWNLOAD "https://nightly.visualboyadvance-m.org/vcpkg/${triplet}/" "${CMAKE_BINARY_DIR}/binary_package_list_${triplet}.html"
STATUS pkg_list_status
)
list(GET pkg_list_status 1 pkg_list_error)
list(GET pkg_list_status 0 pkg_list_status)
if(NOT pkg_list_status EQUAL 0)
message(STATUS "Failed to download vcpkg binary package list: ${pkg_list_status} - ${pkg_list_error}")
return()
endif()
endfunction()
function(download_package pkg pkgs_dir)
string(REGEX REPLACE "^[^_]+_[^_]+_([^.]+)[.]zip\$" "\\1" pkg_triplet ${pkg})
message(STATUS "Downloading https://nightly.visualboyadvance-m.org/vcpkg/${pkg_triplet}/${pkg} ...")
file(
DOWNLOAD "https://nightly.visualboyadvance-m.org/vcpkg/${pkg_triplet}/${pkg}" "${pkgs_dir}/${pkg}"
STATUS pkg_download_status
)
list(GET pkg_download_status 1 pkg_download_error)
list(GET pkg_download_status 0 pkg_download_status)
if(NOT pkg_download_status EQUAL 0)
message(STATUS "Failed to download vcpkg binary package '${pkg}': ${pkg_download_status} - ${pkg_download_error}")
return()
endif()
message(STATUS "done.")
endfunction()
function(get_binary_packages vcpkg_exe)
set(binary_packages_installed FALSE PARENT_SCOPE)
get_triplet_package_list(${VCPKG_TARGET_TRIPLET})
if(NOT EXISTS "${CMAKE_BINARY_DIR}/binary_package_list_${VCPKG_TARGET_TRIPLET}.html")
message(STATUS "Failed to download binary package list found for triplet '${VCPKG_TARGET_TRIPLET}', aborting.")
return()
endif()
file(READ "${CMAKE_BINARY_DIR}/binary_package_list_${VCPKG_TARGET_TRIPLET}.html" raw_html)
string(REGEX MATCHALL "<a href=\"[^\"]+[.]zip\"" links ${raw_html})
foreach(link ${links})
string(REGEX REPLACE "<a href=\"([^\"]+[.]zip)\"" "\\1" pkg ${link})
list(APPEND binary_packages ${pkg})
endforeach()
set(vcpkg_binpkg_dir ${CMAKE_BINARY_DIR}/vcpkg-binpkg)
include(FetchContent)
FetchContent_Declare(
vcpkg_binpkg
URL "https://github.com/rkitover/vcpkg-binpkg-prototype/archive/refs/heads/master.zip"
SOURCE_DIR ${vcpkg_binpkg_dir}
)
FetchContent_GetProperties(vcpkg_binpkg)
if(NOT vcpkg_binpkg_POPULATED)
FetchContent_MakeAvailable(vcpkg_binpkg)
endif()
foreach(pkg ${binary_packages})
if(NOT pkg MATCHES "([^_]+)_([^_]+)_([^.]+)[.]zip")
continue()
endif()
set(pkg_name ${CMAKE_MATCH_1})
set(pkg_version ${CMAKE_MATCH_2})
set(pkg_triplet ${CMAKE_MATCH_3})
vcpkg_is_installed(${vcpkg_exe} ${pkg_name} ${pkg_version} ${pkg_triplet} ${POWERSHELL} pkg_installed)
if(NOT pkg_installed)
list(APPEND to_install ${pkg})
endif()
endforeach()
if(to_install)
set(bin_pkgs_dir ${CMAKE_BINARY_DIR}/vcpkg-binary-packages)
file(MAKE_DIRECTORY ${bin_pkgs_dir})
foreach(pkg ${to_install})
download_package("${pkg}" "${bin_pkgs_dir}")
if(NOT EXISTS "${bin_pkgs_dir}/${pkg}")
message(STATUS "Failed to download package '${pkg}', aborting.")
return()
endif()
endforeach()
while(TRUE)
# -command "import-module ($env:USERPROFILE + '/source/repos/vcpkg-binpkg-prototype/vcpkg-binpkg.psm1'); vcpkg-listmissing ."
execute_process(
COMMAND ${POWERSHELL}
-executionpolicy bypass -noprofile
-command "import-module '${CMAKE_BINARY_DIR}/vcpkg-binpkg/vcpkg-binpkg.psm1'; vcpkg-listmissing ."
WORKING_DIRECTORY ${bin_pkgs_dir}
OUTPUT_VARIABLE host_deps
RESULT_VARIABLE host_deps_status
)
if(NOT host_deps_status EQUAL 0)
message(STATUS "Failed to calculate host dependencies: ${host_deps_status}")
return()
endif()
string(REGEX REPLACE "\r?\n" ";" host_deps "${host_deps}")
if(NOT host_deps)
break()
endif()
foreach(host_dep ${host_deps})
if(NOT host_dep MATCHES "^([^:]+):([^:]+)\$")
continue()
endif()
set(host_dep_name ${CMAKE_MATCH_1})
set(host_dep_triplet ${CMAKE_MATCH_2})
get_triplet_package_list(${host_dep_triplet})
file(READ "${CMAKE_BINARY_DIR}/binary_package_list_${host_dep_triplet}.html" raw_html)
string(REGEX MATCHALL "<a href=\"${host_dep_name}_[^\"]+[.]zip\"" links ${raw_html})
list(LENGTH links links_count)
if(NOT links_count EQUAL 1)
message(STATUS "Multiple host dependencies found for '${host_dep_name}' for triplet '${host_dep_triplet}', aborting.")
return()
endif()
string(REGEX REPLACE "<a href=\"([^\"]+[.]zip)\"" "\\1" pkg ${links})
download_package("${pkg}" "${bin_pkgs_dir}")
if(NOT EXISTS "${bin_pkgs_dir}/${pkg}")
message(STATUS "Failed to download host dependency package '${pkg}', aborting.")
return()
endif()
endforeach()
endwhile()
execute_process(
COMMAND ${POWERSHELL}
-executionpolicy bypass -noprofile
-command "import-module '${CMAKE_BINARY_DIR}/vcpkg-binpkg/vcpkg-binpkg.psm1'; vcpkg-instpkg ."
WORKING_DIRECTORY ${bin_pkgs_dir}
)
file(REMOVE_RECURSE ${bin_pkgs_dir})
endif()
set(binary_packages_installed TRUE PARENT_SCOPE)
endfunction()
function(vcpkg_remove_optional_deps vcpkg_exe)
list(LENGTH VCPKG_DEPS_OPTIONAL optionals_list_len)
math(EXPR optionals_list_last "${optionals_list_len} - 1")
unset(deps)
foreach(i RANGE 0 ${optionals_list_last} 2)
list(GET VCPKG_DEPS_OPTIONAL ${i} dep)
list(APPEND deps ${dep}:${VCPKG_TARGET_TRIPLET})
endforeach()
execute_process(
COMMAND ${vcpkg_exe} remove --recurse ${deps}
WORKING_DIRECTORY ${VCPKG_ROOT}
)
endfunction()
function(vcpkg_set_toolchain)
get_filename_component(preferred_root ${CMAKE_SOURCE_DIR}/../vcpkg ABSOLUTE)
if(NOT DEFINED POWERSHELL)
message(FATAL_ERROR "Powershell is required to use vcpkg binaries.")
endif()
if(NOT DEFINED ENV{VCPKG_ROOT})
if(WIN32)
if(DEFINED ENV{CI} OR EXISTS /vcpkg)
set(VCPKG_ROOT /vcpkg)
elseif(EXISTS c:/vcpkg)
set(VCPKG_ROOT c:/vcpkg)
# Prefer the preferred root to the VS default which is more difficult to deal with, if it exists.
elseif(EXISTS ${preferred_root})
set(VCPKG_ROOT ${preferred_root})
else()
find_program(vcpkg_exe_path NAME vcpkg.exe HINTS ENV PATH)
if(vcpkg_exe_path)
get_filename_component(VCPKG_ROOT ${vcpkg_exe_path} DIRECTORY)
get_filename_component(VCPKG_ROOT ${VCPKG_ROOT} ABSOLUTE)
endif()
unset(vcpkg_exe_path)
endif()
endif()
if(NOT DEFINED VCPKG_ROOT)
set(VCPKG_ROOT ${preferred_root})
endif()
set(ENV{VCPKG_ROOT} ${VCPKG_ROOT})
else()
set(VCPKG_ROOT $ENV{VCPKG_ROOT})
endif()
# Avoid using Visual Studio default vcpkg, because that requires elevaction.
if(VCPKG_ROOT MATCHES "Visual Studio")
set(mkdir_status 0)
if(NOT EXISTS "${preferred_root}")
file(
MAKE_DIRECTORY "${preferred_root}"
RESULT mkdir_status
)
endif()
if(mkdir_status EQUAL 0)
set(VCPKG_ROOT "${preferred_root}")
set(ENV{VCPKG_ROOT} ${VCPKG_ROOT})
endif()
endif()
set(VCPKG_ROOT ${VCPKG_ROOT} CACHE FILEPATH "vcpkg installation root path" FORCE)
if(NOT EXISTS ${VCPKG_ROOT})
get_filename_component(root_parent ${VCPKG_ROOT}/.. ABSOLUTE)
execute_process(
COMMAND git clone https://github.com/microsoft/vcpkg.git
RESULT_VARIABLE git_status
WORKING_DIRECTORY ${root_parent}
)
vcpkg_check_git_status(${git_status})
else()
# this is the case when we cache vcpkg/installed with the appveyor build cache
if(NOT EXISTS ${VCPKG_ROOT}/.git)
set(git_commands
"git init"
"git remote add origin https://github.com/microsoft/vcpkg.git"
"git fetch --all --prune"
"git reset --hard origin/master"
"git branch --set-upstream-to=origin/master master"
)
foreach(git_command ${git_commands})
separate_arguments(git_command)
execute_process(
COMMAND ${git_command}
RESULT_VARIABLE git_status
WORKING_DIRECTORY ${VCPKG_ROOT}
)
vcpkg_check_git_status(${git_status})
endforeach()
else()
execute_process(
COMMAND git fetch origin
RESULT_VARIABLE git_status
WORKING_DIRECTORY ${VCPKG_ROOT}
)
vcpkg_check_git_status(${git_status})
execute_process(
COMMAND git status
RESULT_VARIABLE git_status
OUTPUT_VARIABLE git_status_text
WORKING_DIRECTORY ${VCPKG_ROOT}
)
vcpkg_check_git_status(${git_status})
set(git_up_to_date FALSE)
if(git_status_text MATCHES "Your branch is up to date with")
set(git_up_to_date TRUE)
endif()
if(NOT git_up_to_date)
execute_process(
COMMAND git pull --rebase
RESULT_VARIABLE git_status
WORKING_DIRECTORY ${VCPKG_ROOT}
)
vcpkg_check_git_status(${git_status})
endif()
endif()
endif()
# build latest vcpkg, if needed
if(NOT git_up_to_date)
if(WIN32)
execute_process(
COMMAND bootstrap-vcpkg.bat
WORKING_DIRECTORY ${VCPKG_ROOT}
)
else()
execute_process(
COMMAND ./bootstrap-vcpkg.sh
WORKING_DIRECTORY ${VCPKG_ROOT}
)
endif()
endif()
foreach(pkg ${VCPKG_DEPS})
list(APPEND VCPKG_DEPS_QUALIFIED ${pkg}:${VCPKG_TARGET_TRIPLET})
if(VCPKG_TARGET_TRIPLET STREQUAL "x86-mingw-static")
list(APPEND VCPKG_DEPS_QUALIFIED libsamplerate:x86-mingw-static)
endif()
endforeach()
if(WIN32)
set(vcpkg_exe "${VCPKG_ROOT}/vcpkg.exe")
else()
set(vcpkg_exe "${VCPKG_ROOT}/vcpkg")
endif()
# update portfiles
execute_process(
COMMAND ${vcpkg_exe} update
WORKING_DIRECTORY ${VCPKG_ROOT}
)
if (NOT (NO_VCPKG_UPDATES OR (NOT VCPKG_BINARY_PACKAGES)))
get_binary_packages(${vcpkg_exe})
endif()
if(NOT binary_packages_installed)
# Get number of seconds since midnight (might be wrong if am/pm is in effect on Windows.)
vcpkg_seconds()
set(began ${seconds})
# Limit total installation time to 20 minutes to not overrun CI time limit.
math(EXPR time_limit "${began} + (20 * 60)")
vcpkg_deps_fixup("${vcpkg_exe}")
# Install core deps.
execute_process(
COMMAND ${vcpkg_exe} --triplet ${VCPKG_TARGET_TRIPLET} install ${pkg}
WORKING_DIRECTORY ${VCPKG_ROOT}
)
# If ports have been updated, and there is time, rebuild cache one at a time to not overrun the CI time limit.
vcpkg_seconds()
if(seconds LESS time_limit)
vcpkg_get_first_upgrade(${vcpkg_exe})
if(DEFINED first_upgrade)
# If we have to upgrade zlib, remove optional deps first so that
# the build doesn't overrun the CI time limit.
if(first_upgrade STREQUAL "zlib")
vcpkg_remove_optional_deps(${vcpkg_exe})
endif()
execute_process(
COMMAND ${vcpkg_exe} upgrade --no-dry-run "${first_upgrade}:${VCPKG_TARGET_TRIPLET}"
WORKING_DIRECTORY ${VCPKG_ROOT}
)
endif()
endif()
# Install optional deps, within time limit.
list(LENGTH VCPKG_DEPS_OPTIONAL optionals_list_len)
math(EXPR optionals_list_last "${optionals_list_len} - 1")
foreach(i RANGE 0 ${optionals_list_last} 2)
list(GET VCPKG_DEPS_OPTIONAL ${i} dep)
math(EXPR var_idx "${i} + 1")
list(GET VCPKG_DEPS_OPTIONAL ${var_idx} var)
set(val "${${var}}")
vcpkg_seconds()
if("${val}" OR (seconds LESS time_limit AND ("${val}" OR "${val}" STREQUAL "")))
set(dep_qualified "${dep}:${VCPKG_TARGET_TRIPLET}")
execute_process(
COMMAND --triplet ${VCPKG_TARGET_TRIPLET} ${vcpkg_exe} install ${dep}
WORKING_DIRECTORY ${VCPKG_ROOT}
)
set(${var} ON)
else()
set(${var} OFF)
endif()
endforeach()
endif()
if(WIN32 AND VCPKG_TARGET_TRIPLET MATCHES x64 AND CMAKE_GENERATOR MATCHES "Visual Studio")
set(CMAKE_GENERATOR_PLATFORM x64 CACHE STRING "visual studio build architecture" FORCE)
endif()
if(WIN32 AND NOT CMAKE_GENERATOR MATCHES "Visual Studio" AND NOT DEFINED CMAKE_CXX_COMPILER)
if(VCPKG_TARGET_TRIPLET MATCHES "^x[68][46]-windows-")
# set toolchain to VS for e.g. Ninja or jom
set(CMAKE_C_COMPILER cl CACHE STRING "Microsoft C/C++ Compiler" FORCE)
set(CMAKE_CXX_COMPILER cl CACHE STRING "Microsoft C/C++ Compiler" FORCE)
elseif(VCPKG_TARGET_TRIPLET MATCHES "^x[68][46]-mingw-")
# set toolchain to MinGW for e.g. Ninja or jom
set(CMAKE_C_COMPILER gcc CACHE STRING "MinGW GCC C Compiler" FORCE)
set(CMAKE_CXX_COMPILER g++ CACHE STRING "MinGW G++ C++ Compiler" FORCE)
endif()
endif()
set(CMAKE_TOOLCHAIN_FILE ${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake CACHE FILEPATH "vcpkg toolchain" FORCE)
endfunction()
vcpkg_set_toolchain()
include(${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake)

View File

@ -1,37 +0,0 @@
if(NOT ENABLE_ASAN)
return()
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
check_cxx_compiler_flag(/fsanitize=address MSVC_ASAN_SUPPORTED)
if(MSVC_ASAN_SUPPORTED)
add_compile_options(/fsanitize=address)
add_compile_definitions(_DISABLE_VECTOR_ANNOTATION _DISABLE_STRING_ANNOTATION)
else()
message(WARNING "ASAN not available for the compiler, disabling.")
set(ENABLE_ASAN OFF)
return()
endif()
else()
# ASAN does not work on non-debug builds for GCC and Clang.
if(NOT CMAKE_BUILD_TYPE STREQUAL Debug)
message(WARNING "ASAN requires debug build, set -DCMAKE_BUILD_TYPE=Debug, disabling.")
set(ENABLE_ASAN OFF)
return()
endif()
# It is necessary to modify the linker flagas for the compiler check to work.
set(BACKUP_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS})
set(CMAKE_EXE_LINKER_FLAGS "-fsanitize=address")
check_cxx_compiler_flag(-fsanitize=address ASAN_SUPPORTED)
set(CMAKE_EXE_LINKER_FLAGS ${BACKUP_LINKER_FLAGS})
if(ASAN_SUPPORTED)
add_compile_options(-fsanitize=address)
add_link_options(-fsanitize=address)
else()
message(WARNING "ASAN not available for the compiler, disabling.")
set(ENABLE_ASAN OFF)
return()
endif()
endif()

View File

@ -1,78 +0,0 @@
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR ${CROSS_ARCH})
set(COMPILER_PREFIX "${CROSS_ARCH}-w64-mingw32")
unset(CMAKE_RC_COMPILER CACHE)
unset(CMAKE_C_COMPILER CACHE)
unset(CMAKE_CXX_COMPILER CACHE)
unset(PKG_CONFIG_EXECUTABLE CACHE)
# Which compilers to use for C and C++.
find_program(CMAKE_RC_COMPILER NAMES ${COMPILER_PREFIX}-windres)
find_program(CMAKE_C_COMPILER NAMES ${COMPILER_PREFIX}-gcc)
find_program(CMAKE_CXX_COMPILER NAMES ${COMPILER_PREFIX}-g++)
SET(CMAKE_FIND_ROOT_PATH
/usr/${COMPILER_PREFIX}
/usr/${COMPILER_PREFIX}/usr
/usr/${COMPILER_PREFIX}/sys-root/mingw
/usr/local/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX}
/home/linuxbrew/.linuxbrew/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX}
$ENV{HOME}/.linuxbrew/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX}
)
# find wx-config
foreach(p ${CMAKE_FIND_ROOT_PATH})
file(GLOB paths ${p}/lib/wx/config/${COMPILER_PREFIX}-msw-*)
list(APPEND wx_confs ${paths})
endforeach()
foreach(p ${wx_confs})
if(CMAKE_TOOLCHAIN_FILE MATCHES -static)
string(REGEX MATCH "(static-)?([0-9]+\\.?)+$" wx_conf_ver ${p})
else()
string(REGEX MATCH "([0-9]+\\.?)+$" wx_conf_ver ${p})
endif()
list(APPEND wx_conf_vers ${wx_conf_ver})
endforeach()
list(SORT wx_conf_vers)
list(REVERSE wx_conf_vers)
list(GET wx_conf_vers 0 wx_conf_ver)
foreach(p ${wx_confs})
if(p MATCHES "${wx_conf_ver}$")
set(wx_conf ${p})
break()
endif()
endforeach()
set(wxWidgets_CONFIG_EXECUTABLE ${wx_conf} CACHE FILEPATH "path to wx-config script for the desired wxWidgets configuration" FORCE)
if(CMAKE_TOOLCHAIN_FILE MATCHES -static)
# find the right static zlib
foreach(p ${CMAKE_FIND_ROOT_PATH})
if(EXISTS ${p}/lib/libz.a)
set(ZLIB_ROOT ${p} CACHE FILEPATH "where to find zlib" FORCE)
break()
endif()
endforeach()
endif()
if(CMAKE_PREFIX_PATH)
set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${CMAKE_PREFIX_PATH})
endif()
# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search
# programs in the host environment too
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# pkg-config may be under the prefix
find_program(PKG_CONFIG_EXECUTABLE NAMES ${COMPILER_PREFIX}-pkg-config)

View File

@ -1 +0,0 @@
include(${CMAKE_CURRENT_LIST_DIR}/Toolchain-cross-MinGW-w64-i686.cmake)

View File

@ -1,3 +1,30 @@
SET(CMAKE_SYSTEM_NAME Windows)
set(CROSS_ARCH i686)
set(CMAKE_SIZEOF_VOID_P 4)
include(${CMAKE_CURRENT_LIST_DIR}/Toolchain-cross-MinGW-w64-common.cmake)
set(COMPILER_PREFIX "${CROSS_ARCH}-w64-mingw32")
unset(CMAKE_RC_COMPILER CACHE)
unset(CMAKE_C_COMPILER CACHE)
unset(CMAKE_CXX_COMPILER CACHE)
unset(PKG_CONFIG_EXECUTABLE CACHE)
# which compilers to use for C and C++
find_program(CMAKE_RC_COMPILER NAMES ${COMPILER_PREFIX}-windres)
find_program(CMAKE_C_COMPILER NAMES ${COMPILER_PREFIX}-gcc)
find_program(CMAKE_CXX_COMPILER NAMES ${COMPILER_PREFIX}-g++)
SET(CMAKE_FIND_ROOT_PATH /usr/${COMPILER_PREFIX} /usr/${COMPILER_PREFIX}/usr /usr/${COMPILER_PREFIX}/sys-root/mingw /usr/local/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX} /home/linuxbrew/.linuxbrew/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX} $ENV{HOME}/.linuxbrew/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX})
if(CMAKE_PREFIX_PATH)
set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${CMAKE_PREFIX_PATH})
endif()
# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search
# programs in the host environment too
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# pkg-config may be under the prefix
find_program(PKG_CONFIG_EXECUTABLE NAMES ${COMPILER_PREFIX}-pkg-config)

View File

@ -1 +0,0 @@
include(${CMAKE_CURRENT_LIST_DIR}/Toolchain-cross-MinGW-w64-x86_64.cmake)

View File

@ -1,3 +1,30 @@
SET(CMAKE_SYSTEM_NAME Windows)
set(CROSS_ARCH x86_64)
set(CMAKE_SIZEOF_VOID_P 8)
include(${CMAKE_CURRENT_LIST_DIR}/Toolchain-cross-MinGW-w64-common.cmake)
set(COMPILER_PREFIX "${CROSS_ARCH}-w64-mingw32")
unset(CMAKE_RC_COMPILER CACHE)
unset(CMAKE_C_COMPILER CACHE)
unset(CMAKE_CXX_COMPILER CACHE)
unset(PKG_CONFIG_EXECUTABLE CACHE)
# which compilers to use for C and C++
find_program(CMAKE_RC_COMPILER NAMES ${COMPILER_PREFIX}-windres)
find_program(CMAKE_C_COMPILER NAMES ${COMPILER_PREFIX}-gcc)
find_program(CMAKE_CXX_COMPILER NAMES ${COMPILER_PREFIX}-g++)
SET(CMAKE_FIND_ROOT_PATH /usr/${COMPILER_PREFIX} /usr/${COMPILER_PREFIX}/usr /usr/${COMPILER_PREFIX}/sys-root/mingw /usr/local/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX} /home/linuxbrew/.linuxbrew/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX} $ENV{HOME}/.linuxbrew/opt/mingw-w64/toolchain-${CROSS_ARCH}/${COMPILER_PREFIX})
if(CMAKE_PREFIX_PATH)
set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${CMAKE_PREFIX_PATH})
endif()
# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search
# programs in the host environment too
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# pkg-config may be under the prefix
find_program(PKG_CONFIG_EXECUTABLE NAMES ${COMPILER_PREFIX}-pkg-config)

View File

@ -1,82 +0,0 @@
if(X86_32 OR X86_64)
add_compile_options(-msse2)
endif()
if(UPSTREAM_RELEASE)
if(X86_64)
# Require and optimize for Core2 level support, tune for generic.
if(APPLE)
add_compile_options(-march=core2 -mtune=skylake)
else()
add_compile_options(-march=core2 -mtune=generic)
endif()
elseif(X86_32)
# Optimize for pentiumi3 and tune for generic for Windows XP builds.
set(WINXP TRUE)
add_compile_options(-march=pentium3 -mtune=generic)
add_compile_definitions(-DWINXP)
endif()
endif()
# Common flags.
add_compile_options(
-pipe
$<$<COMPILE_LANGUAGE:CXX>:-Wno-deprecated-copy>
-Wformat
-Wformat-security
-fdiagnostics-color=always
)
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
add_compile_options(-Wno-unused-command-line-argument)
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
add_compile_options(-feliminate-unused-debug-types)
endif()
# check if ssp flags are supported.
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
check_cxx_compiler_flag(-fstack-protector-strong STACK_PROTECTOR_SUPPORTED)
if(STACK_PROTECTOR_SUPPORTED)
add_compile_options(-fstack-protector-strong)
check_cxx_compiler_flag("--param ssp-buffer-size=4" SSP_BUFFER_SIZE_SUPPORTED)
if(SSP_BUFFER_SIZE_SUPPORTED)
add_compile_options(--param ssp-buffer-size=4)
endif()
endif()
endif()
#add_compile_options(-std=c++14)
if(NOT ENABLE_ASM) # inline asm is not allowed with -fPIC
add_compile_options(-fPIC)
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_options(-ggdb3 -fno-omit-frame-pointer -Wall -Wextra)
else()
add_compile_options(-O3 -ffast-math -fomit-frame-pointer)
endif()
# for some reason this is necessary
if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
include_directories(/usr/local/include)
endif()
if(VBAM_STATIC)
if(APPLE)
add_link_options(-static-libstdc++)
else()
add_link_options(-static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread)
endif()
endif()
# To support LTO, this must always fail.
add_compile_options(-Werror=odr -Werror=strict-aliasing)
add_link_options( -Werror=odr -Werror=strict-aliasing)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
add_compile_options(-Werror=lto-type-mismatch)
add_link_options( -Werror=lto-type-mismatch)
endif()

View File

@ -1,10 +0,0 @@
if (NOT MINGW)
return()
endif()
# this has to run after the toolchain is initialized.
include_directories("${CMAKE_SOURCE_DIR}/win32-deps/mingw-include")
include_directories("${CMAKE_SOURCE_DIR}/win32-deps/mingw-xaudio/include")
# Add Winsock as the last library linked because of broken link precedence.
set(CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} -lws2_32")

View File

@ -1,85 +0,0 @@
# Set the runtime library properly.
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:DEBUG>:Debug>" CACHE INTERNAL "")
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
# MSVC-specific flags (not supported by clang-cl).
add_compile_options(/nologo)
if (NOT CMAKE_GENERATOR MATCHES "Ninja")
# Multi-processor compilation does not work well with Ninja.
add_compile_options(/MP)
endif()
endif()
include_directories("${CMAKE_SOURCE_DIR}/win32-deps/msvc")
add_compile_definitions(
_FORCENAMELESSUNION
WIN32_LEAN_AND_MEAN
WIN32
_WINDOWS
__STDC_LIMIT_MACROS
__STDC_CONSTANT_MACROS
_CRT_SECURE_NO_WARNINGS
_UNICODE
UNICODE
WINVER=0x0A00
NTDDI_VERSION=0x0A000007
NOMINMAX
)
add_compile_options(
/W4
/GR
/EHsc
)
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_definitions(_DEBUG)
add_compile_options(/Ob0 /Od /RTC1)
if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" AND NOT ENABLE_ASAN)
# Use Edit and Continue with MSVC.
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "EditAndContinue" CACHE STRING "" FORCE)
else()
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "ProgramDatabase" CACHE STRING "" FORCE)
endif()
else()
add_compile_options(/MT /Oi /Gy)
add_link_options(/OPT:REF /OPT:ICF)
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "ProgramDatabase" CACHE STRING "" FORCE)
if (CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
add_compile_options(/O1 /Ob1)
elseif(CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo")
add_compile_options(/O2 /Ob1)
else()
add_compile_options(/O2)
endif()
endif()
if(CMAKE_VERSION VERSION_LESS "3.25")
# Backwards-compatible way of setting the /Z option.
if(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT STREQUAL "EditAndContinue")
add_compile_options(/ZI)
elseif(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT STREQUAL "ProgramDatabase")
add_compile_options(/Zi)
elseif(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT STREQUAL "Embedded")
add_compile_options(/Z7)
else()
message(FATAL_ERROR "Unknown value for CMAKE_MSVC_DEBUG_INFORMATION_FORMAT: ${CMAKE_MSVC_DEBUG_INFORMATION_FORMAT}")
endif()
endif()
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/std:c++17>)
set(CMAKE_RC_FLAGS "-c65001 /DWIN32" CACHE STRING "" FORCE)
# We need to explicitly set all of these to override the CMake defaults.
set(CMAKE_CXX_FLAGS "" CACHE STRING "" FORCE)
set(CMAKE_C_FLAGS "" CACHE STRING "" FORCE)
set(CMAKE_CXX_FLAGS_DEBUG "" CACHE STRING "" FORCE)
set(CMAKE_C_FLAGS_DEBUG "" CACHE STRING "" FORCE)
set(CMAKE_CXX_FLAGS_RELEASE "" CACHE STRING "" FORCE)
set(CMAKE_C_FLAGS_RELEASE "" CACHE STRING "" FORCE)
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "" CACHE STRING "" FORCE)
set(CMAKE_C_FLAGS_RELWITHDEBINFO "" CACHE STRING "" FORCE)
set(CMAKE_CXX_FLAGS_MINSIZEREL "" CACHE STRING "" FORCE)
set(CMAKE_C_FLAGS_MINSIZEREL "" CACHE STRING "" FORCE)

View File

@ -1,126 +0,0 @@
if(TRANSLATIONS_ONLY)
return()
endif()
# Compiler stuff
include(CheckCXXCompilerFlag)
include(ProcessorCount)
ProcessorCount(num_cpus)
if(ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT LTO_SUPPORTED)
# MINGW64 does not support LTO
if(WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(LTO_SUPPORTED FALSE)
endif()
if(LTO_SUPPORTED)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
else()
message(WARNING "LTO is not supported by the compiler, diasabling LTO")
set(ENABLE_LTO OFF)
endif()
endif()
# Output all binaries at top level
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR})
if(NOT HTTPS)
add_compile_definitions(NO_HTTPS)
endif()
if(ENABLE_GBA_LOGGING)
add_compile_definitions(GBA_LOGGING )
endif()
if(ENABLE_MMX)
add_compile_definitions(MMX)
endif()
if(NOT ENABLE_ONLINEUPDATES)
add_compile_definitions(NO_ONLINEUPDATES)
endif()
# The debugger is enabled by default
if(ENABLE_DEBUGGER)
add_compile_definitions(VBAM_ENABLE_DEBUGGER)
endif()
# The ASM core is disabled by default because we don't know on which platform we are
if(NOT ENABLE_ASM_CORE)
add_compile_definitions(C_CORE)
endif()
# Set up "src" and generated directory as a global include directory.
set(VBAM_GENERATED_DIR ${CMAKE_BINARY_DIR}/generated)
include_directories(
${CMAKE_SOURCE_DIR}/src
${VBAM_GENERATED_DIR}
)
# C defines
add_compile_definitions(HAVE_NETINET_IN_H HAVE_ARPA_INET_H HAVE_ZLIB_H FINAL_VERSION SDL USE_OPENGL SYSCONF_INSTALL_DIR="${CMAKE_INSTALL_FULL_SYSCONFDIR}")
add_compile_definitions(PKGDATADIR="${CMAKE_INSTALL_FULL_DATADIR}/vbam")
add_compile_definitions(__STDC_FORMAT_MACROS)
add_compile_definitions(LOCALEDIR="${LOCALEDIR}")
# Common compiler settings.
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_definitions(DEBUG)
else()
add_compile_definitions(NDEBUG)
endif()
if(APPLE)
add_compile_definitions(MACHO)
elseif("${CMAKE_SYSTEM}" MATCHES "Linux")
add_compile_definitions(ELF)
endif()
if(X86_64)
add_compile_definitions(__AMD64__ __X86_64__)
endif()
# Enable ASAN if requested and supported.
include(Toolchain-asan)
# MINGW/MSYS-specific settings.
include(Toolchain-mingw)
# Toolchain-specific settings.
if(MSVC)
# This also includes clang-cl.
include(Toolchain-msvc)
else()
include(Toolchain-gcc-clang)
endif()
# Assembler flags.
if(ENABLE_ASM_CORE OR ENABLE_ASM_SCALERS)
if(MSVC)
if(NOT EXISTS ${CMAKE_BINARY_DIR}/nuget.exe)
file(DOWNLOAD "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" ${CMAKE_BINARY_DIR}/nuget.exe)
endif()
execute_process(
COMMAND nuget.exe install nasm2 -OutputDirectory ${CMAKE_BINARY_DIR}/nuget
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
file(GLOB pkg ${CMAKE_BINARY_DIR}/nuget/nasm2*)
list(APPEND CMAKE_PROGRAM_PATH ${pkg}/tools)
endif()
enable_language(ASM_NASM)
set(ASM_ENABLED ON)
endif()
if(ASM_ENABLED)
string(REGEX REPLACE "<FLAGS>" "-I${CMAKE_SOURCE_DIR}/src/filters/hq/asm/ -O1 -w-orphan-labels" CMAKE_ASM_NASM_COMPILE_OBJECT ${CMAKE_ASM_NASM_COMPILE_OBJECT})
endif()

View File

@ -1,148 +0,0 @@
# Clone web-data.
# Update version in appcast.xml to latest tag.
# Commit web-data.
function(update_appcast)
if(UPDATE_APPCAST STREQUAL UNDO)
file(REMOVE_RECURSE ${CMAKE_BINARY_DIR}/web-data)
message(FATAL_ERROR [=[
**** APPCAST.XML UPDATE HAS BEEN UNDONE ****"
Ignore the following cmake error.
]=])
endif()
# Get last tag.
execute_process(
COMMAND git tag --sort=-v:refname
OUTPUT_VARIABLE git_tags
OUTPUT_STRIP_TRAILING_WHITESPACE
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
string(REGEX REPLACE ";" "\\\\;" git_tags_lines "${git_tags}")
string(REGEX REPLACE "\r?\n" ";" git_tags_lines "${git_tags_lines}")
foreach(line ${git_tags_lines})
if(line MATCHES "^v[0-9]")
set(new_tag ${line})
break()
endif()
endforeach()
if(NOT DEFINED new_tag)
message(FATAL_ERROR "cannot find last release tag")
endif()
# Remove the "v" for the version string.
string(REGEX REPLACE "^v" "" new_version ${new_tag})
# Clone repo.
execute_process(
COMMAND git clone git@github.com:visualboyadvance-m/visualboyadvance-m.github.io web-data
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
# Rewrite appcast.xml.
# First make a copy for backing out.
configure_file(
${CMAKE_BINARY_DIR}/web-data/appcast.xml
${CMAKE_BINARY_DIR}/appcast.xml.orig
COPYONLY
)
# Now read it and replace the versions.
include(FileIterator)
fi_open_file(${CMAKE_BINARY_DIR}/web-data/appcast.xml)
set(work_file ${CMAKE_BINARY_DIR}/appcast.xml.work)
file(REMOVE ${work_file})
while(NOT fi_done)
fi_get_next_line()
string(REGEX REPLACE [=[(:version="|v)([0-9.]+)([/"])]=] "\\1${new_version}\\3" fi_line "${fi_line}")
file(APPEND ${work_file} "${fi_line}" "\n")
endwhile()
# Convert to UNIX line endings on Windows, just copy the file otherwise.
if(CMAKE_HOST_SYSTEM MATCHES Windows OR ((NOT DEFINED CMAKE_HOST_SYSTEM) AND WIN32))
if(NOT DEFINED POWERSHELL)
message(FATAL_ERROR "Powershell is required to convert line endings on Windows.")
endif()
execute_process(
COMMAND ${POWERSHELL} -NoLogo -NoProfile -ExecutionPolicy Bypass -Command [=[
$text = [IO.File]::ReadAllText("appcast.xml.work") -replace "`r`n", "`n"
[IO.File]::WriteAllText("appcast.xml", $text)
]=]
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
else()
configure_file(
${CMAKE_BINARY_DIR}/appcast.xml.work
${CMAKE_BINARY_DIR}/appcast.xml
COPYONLY
)
endif()
# Copy the new file and add it to the commit.
configure_file(
${CMAKE_BINARY_DIR}/appcast.xml
${CMAKE_BINARY_DIR}/web-data/appcast.xml
COPYONLY
)
execute_process(
COMMAND git add appcast.xml
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/web-data
)
# Commit the change.
execute_process(
COMMAND git commit -m "release ${new_tag}" --signoff -S
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/web-data
)
# Make release tag.
execute_process(
COMMAND git tag -s -m${new_tag} ${new_tag}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/web-data
)
message(FATAL_ERROR [=[
appcast.xml updated.
**** IF YOU ARE SURE YOU WANT TO RELEASE ****
Run the following commands to push the release commit and tag:
cd web-data
git push
git push --tags
**** TO UNDO THE RELEASE ****
To rollback these changes, run this command:
cmake .. -DUPDATE_APPCAST=UNDO
Ignore the "configuration incomplete" message following, this mode does not
build anything.
]=])
endfunction()
update_appcast()

View File

@ -0,0 +1,103 @@
# UseGCCBinUtilsWrappers.cmake
#
# Use gcc binutils wrappers such as gcc-ar, this may be necessary for LTO.
#
# To use:
#
# put a copy into your <project_root>/CMakeScripts/
#
# In your main CMakeLists.txt add the command:
#
# INCLUDE(UseGCCBinUtilsWrappers)
#
# BSD 2-Clause License
#
# Copyright (c) 2016, Rafael Kitover
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# only do this when compiling with gcc/g++
IF(NOT (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUC))
RETURN()
ENDIF()
# first try appending -util to basename of compiler
STRING(REGEX MATCH "\\.(exe|EXE)$" GCC_EXE_SUFFIX ${CMAKE_C_COMPILER})
STRING(REGEX REPLACE "\\.(exe|EXE)$" "" GCC_BASENAME ${CMAKE_C_COMPILER})
SET(GCC_AR "${GCC_BASENAME}-ar${GCC_EXE_SUFFIX}")
SET(GCC_NM "${GCC_BASENAME}-nm${GCC_EXE_SUFFIX}")
SET(GCC_RANLIB "${GCC_BASENAME}-ranlib${GCC_EXE_SUFFIX}")
# if that does not work, try looking for gcc-util in the compiler directory,
# and failing that in the PATH
GET_FILENAME_COMPONENT(GCC_DIRNAME ${CMAKE_C_COMPILER} DIRECTORY)
IF(NOT EXISTS ${GCC_AR})
UNSET(GCC_AR)
FIND_PROGRAM(GCC_AR NAMES gcc-ar gcc-ar.exe GCC-AR.EXE HINTS ${GCC_DIRNAME})
ENDIF()
IF(NOT EXISTS ${GCC_NM})
UNSET(GCC_NM)
FIND_PROGRAM(GCC_NM NAMES gcc-nm gcc-nm.exe GCC-NM.EXE HINTS ${GCC_DIRNAME})
ENDIF()
IF(NOT EXISTS ${GCC_RANLIB})
UNSET(GCC_RANLIB)
FIND_PROGRAM(GCC_RANLIB NAMES gcc-ranlib gcc-ranlib.exe GCC-RANLIB.EXE HINTS ${GCC_DIRNAME})
ENDIF()
INCLUDE(PathRun)
IF(EXISTS ${GCC_AR})
MESSAGE("-- Found gcc-ar: ${GCC_AR}")
SET(target "${CMAKE_BINARY_DIR}/gcc-ar-wrap")
MAKE_PATH_RUN_WRAPPER("${GCC_AR}" "${target}")
SET(CMAKE_AR "${target}")
ENDIF()
IF(EXISTS ${GCC_NM})
MESSAGE("-- Found gcc-nm: ${GCC_NM}")
SET(target "${CMAKE_BINARY_DIR}/gcc-nm-wrap")
MAKE_PATH_RUN_WRAPPER("${GCC_NM}" "${target}")
SET(CMAKE_NM "${target}")
ENDIF()
IF(EXISTS ${GCC_RANLIB})
MESSAGE("-- Found gcc-ranlib: ${GCC_RANLIB}")
SET(target "${CMAKE_BINARY_DIR}/gcc-ranlib-wrap")
MAKE_PATH_RUN_WRAPPER("${GCC_RANLIB}" "${target}")
SET(CMAKE_RANLIB "${target}")
ENDIF()
FOREACH(VAR "GCC_AR" "GCC_NM" "GCC_RANLIB" "GCC_DIRNAME" "GCC_BASENAME" "GCC_EXE_SUFFIX" "target")
UNSET(${VAR})
ENDFOREACH()

View File

@ -1,3 +1,33 @@
# From: https://stackoverflow.com/a/7216542
function(JOIN VALUES GLUE OUTPUT)
string (REGEX REPLACE "([^\\]|^);" "\\1${GLUE}" _TMP_STR "${VALUES}")
string (REGEX REPLACE "[\\](.)" "\\1" _TMP_STR "${_TMP_STR}") #fixes escaping
set (${OUTPUT} "${_TMP_STR}" PARENT_SCOPE)
endfunction()
# convert msys paths like /c/foo to windows paths like c:/foo
# for variables set by FindWxWidgets
function(normalize_wx_paths)
if(MSYS)
unset(new_paths)
foreach(p ${wxWidgets_LIBRARY_DIRS})
execute_process(COMMAND cygpath -m "${p}" OUTPUT_VARIABLE p_win OUTPUT_STRIP_TRAILING_WHITESPACE)
list(APPEND new_paths "${p_win}")
endforeach()
set(wxWidgets_LIBRARY_DIRS ${new_paths} PARENT_SCOPE)
string(REGEX REPLACE "((^| )[^/]*)/([a-zA-Z])/" "\\1\\3:/" new_libs "${wxWidgets_LIBRARIES}")
set(wxWidgets_LIBRARIES ${new_libs} PARENT_SCOPE)
endif()
endfunction()
macro(cleanup_wx_vars)
if(wxWidgets_CXX_FLAGS)
list(REMOVE_ITEM wxWidgets_CXX_FLAGS -fpermissive)
endif()
endmacro()
function(cygpath var path)
execute_process(
@ -38,31 +68,18 @@ function(check_clean_exit var)
endfunction()
function(find_wx_util var util)
if(WIN32 OR EXISTS /etc/gentoo-release)
# On win32, including cross builds we prefer the plain utility
# name first from PATH, with the exception of -static for static
# builds.
#
# On Gentoo /usr/bin/wx-config loads the eselected build, so we
# want to try that first.
#
# This makes a one element of empty string list.
if(VBAM_STATIC)
set(conf_suffixes "static;")
else()
set(conf_suffixes ";")
endif()
set(major_versions ";")
# on win32, including cross builds we prefer the plain utility name first from PATH
if(WIN32)
set(conf_suffixes "" gtk4 gtk3)
set(major_versions "" 4 3 2)
else()
set(conf_suffixes gtk4 gtk3 "")
set(major_versions 4 3 2 "")
endif()
list(APPEND conf_suffixes gtk4u gtk4 gtk3u gtk3 gtk2u gtk2 "")
list(APPEND major_versions 4 3 2 "")
foreach(conf_suffix IN LISTS conf_suffixes)
foreach(major_version IN LISTS major_versions)
foreach(minor_version RANGE 100 -1 -1)
foreach(minor_version RANGE 100 0 -1)
unset(suffix)
if(conf_suffix)
set(suffix "-${conf_suffix}")
@ -70,7 +87,7 @@ function(find_wx_util var util)
if(major_version)
set(suffix "${suffix}-${major_version}")
if(NOT minor_version EQUAL -1)
if(NOT minor_version EQUAL 0)
set(suffix "${suffix}.${minor_version}")
endif()
endif()
@ -79,16 +96,6 @@ function(find_wx_util var util)
set(exe NOTFOUND CACHE INTERNAL "" FORCE)
find_program(exe NAMES "${util}${suffix}")
# try infix variant, as on FreeBSD
if(NOT EXISTS ${exe})
string(REGEX REPLACE "^-" "" suffix "${suffix}")
string(REGEX REPLACE "-" "${suffix}-" try ${util})
set(exe NOTFOUND CACHE INTERNAL "" FORCE)
find_program(exe NAMES ${try})
endif()
if(EXISTS ${exe})
# check that the utility can be executed cleanly
# in case we find e.g. the wrong architecture binary

65
cmake/Win32Deps.cmake Normal file
View File

@ -0,0 +1,65 @@
if(WIN32 OR CMAKE_TOOLCHAIN_FILE MATCHES "[Mm][Ii][Nn][Gg][Ww]")
# compiler has not been detected yet maybe
if(CMAKE_C_COMPILER MATCHES "cl\\.exe" OR CMAKE_CXX_COMPILER MATCHES "cl\\.exe" OR MSVC OR DEFINED ENV{VisualStudioVersion})
set(VS TRUE)
endif()
set(WINARCH x86)
if(CMAKE_C_COMPILER MATCHES x64 OR CMAKE_CXX_COMPILER MATCHES x64 OR "$ENV{VSCMD_ARG_TGT_ARCH}" MATCHES x64)
set(WINARCH x64)
endif()
# Win32 deps submodules (dependencies and vcpkg)
if(NOT EXISTS "${CMAKE_SOURCE_DIR}/dependencies/mingw-xaudio/include" OR NOT EXISTS "${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake")
set(git_checkout FALSE)
if(EXISTS "${CMAKE_SOURCE_DIR}/.git")
set(git_checkout TRUE)
execute_process(
COMMAND git submodule update --init --remote --recursive
RESULT_VARIABLE git_status
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
)
endif()
if(NOT (git_checkout AND git_status EQUAL 0))
message(FATAL_ERROR "Please pull in git submodules, e.g.\nrun: git submodule update --init --remote --recursive")
endif()
endif()
if(VS)
set(DEPS_MSVC "${CMAKE_SOURCE_DIR}/dependencies/msvc")
include_directories("${DEPS_MSVC}") # for GL/glext.h and getopt.h
endif()
if(VS AND ENABLE_VCPKG)
if(NOT DEFINED ENV{VCPKG_ROOT})
set(ENV{VCPKG_ROOT} "${CMAKE_SOURCE_DIR}/vcpkg")
endif()
# build vcpkg if not built
if(NOT EXISTS $ENV{VCPKG_ROOT}/vcpkg.exe)
execute_process(
COMMAND bootstrap-vcpkg.bat
WORKING_DIRECTORY $ENV{VCPKG_ROOT}
)
endif()
foreach(pkg ${VCPKG_DEPS})
#list(APPEND VCPKG_DEPS_QUALIFIED ${pkg}:${WINARCH}-windows-static)
list(APPEND VCPKG_DEPS_QUALIFIED ${pkg}:${WINARCH}-windows)
endforeach()
# build our deps
execute_process(
COMMAND vcpkg install ${VCPKG_DEPS_QUALIFIED}
WORKING_DIRECTORY $ENV{VCPKG_ROOT}
)
set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" CACHE FILEPATH '' FORCE)
include("$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake")
set(NLS_DEFAULT OFF)
set(ENABLE_NLS OFF) # not sure why this is necessary
endif()
endif()

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
<channel>
<item>
<link>https://github.com/visualboyadvance-m/visualboyadvance-m/releases/download/v2.1.4/visualboyadvance-m-Win-64bit.zip</link>
<enclosure
sparkle:os="windows-x64"
sparkle:version="2.1.4"
length="0"
type="application/octet-stream"
/>
</item>
<item>
<link>https://github.com/visualboyadvance-m/visualboyadvance-m/releases/download/v2.1.4/visualboyadvance-m-Win-32bit.zip</link>
<enclosure
sparkle:os="windows-x86"
sparkle:version="2.1.4"
length="0"
type="application/octet-stream"
/>
</item>
<item>
<link>https://github.com/visualboyadvance-m/visualboyadvance-m/releases/download/v2.1.4/visualboyadvance-m-Mac-64bit.zip</link>
<enclosure
sparkle:os="macos"
sparkle:version="2.1.4"
length="0"
type="application/octet-stream"
/>
</item>
</channel>
</rss>

View File

@ -1,8 +0,0 @@
with import <nixpkgs> {};
stdenv.mkDerivation {
name = "visualboyadvance-m";
buildInputs = if stdenv.isDarwin then
[ ninja cmake nasm faudio gettext libintl libtiff pkg-config zip zlib openal ffmpeg wxGTK32 sdl3 pcre pcre2 darwin.apple_sdk.frameworks.System darwin.apple_sdk.frameworks.IOKit darwin.apple_sdk.frameworks.Carbon darwin.apple_sdk.frameworks.Cocoa darwin.apple_sdk.frameworks.QuartzCore darwin.apple_sdk.frameworks.AudioToolbox darwin.apple_sdk.frameworks.OpenGL darwin.apple_sdk.frameworks.OpenAL llvmPackages_latest.clang llvmPackages_latest.bintools ]
else
[ ninja cmake gcc clang llvm llvmPackages.libcxx nasm faudio gettext libintl libtiff pkg-config zip zlib openal ffmpeg wxGTK32 libGL libGLU glfw sdl3 gtk3-x11 pcre pcre2 util-linuxMinimal libselinux libsepol libthai libdatrie xorg.libXdmcp xorg.libXtst libxkbcommon libepoxy dbus at-spi2-core ];
}

1
dependencies Submodule

@ -0,0 +1 @@
Subproject commit 3e018956d57cf32278a3f3cdd67763b304732482

View File

@ -2,27 +2,59 @@
Developer Information File
==========================
Known preprocessor switches:
- SDL: Defined for the SDL version
- GBA_LOGGING: Enables logging for the GBA core
- FINAL_VERSION: Defined for release versions, disables additional GBA logging and completely disables GB logging. Increases the amount of CPU cycles being emulated in one go.
- VBAM_ENABLE_DEBUGGER: Enable remote debugging support
- BKPT_SUPPORT
- MMX: Enable MMX instruction set
- NO_ASM: Use C++ version of hq3x/4x filters
- RGB555: Use 16bit colors with 5bit green instead of 6bit green in hq3x/4x filters (C++ version)
- NO_OGL: Exclude OpenGL code
- NO_D3D: Exclude Direct3D code
- VBAM_ENABLE_XAUDIO2: Enable XAudio2 code (the XAudio2 interface is DirectSound's successor)
- VBAM_ENABLE_FAUDIO: Enable FAudio code (the FAudio interface is an open source multiplatform re-implementation of XAudio2)
- NO_OAL: Exclude OpenAL code
- NO_XAUDIO2: Exclude XAudio2 code (the XAudio2 interface is DirectSound's successor)
- NO_LINK: Exclude linking code (joybus, multilink, ...)
- WIN64: This macro is only defined for 64 bit builds
Download locations:
NASM: http://nasm.us/
DirectX SDK: http://msdn.microsoft.com/en-us/xna/aa937788.aspx
OpenAL SDK: http://connect.creativelabs.com/openal/default.aspx
OpenGL files: http://www.opengl.org/registry/
zlib: http://zlib.net/
libpng: http://libpng.org/pub/png/libpng.html
You can find pre-built versions of zlib & libpng at:
http://spacy51.sp.funpic.de/VBA-M/libs/
Just extract them somewhere and point Visual C++ 2008 to the include & lib folders.
They are built with the static C runtime (this is what the release builds use).
###########################
# --- Build Systems --- #
###########################
===src/sdl===
===Win32/MFC===
This is the full-featured Windows build using the MFC GUI.
The project files are located in /project/vc2008_mfc (VBA2008.sln) and /project/vs2010_mfc (VBA2010.sln).
Anyone distributing builds should be using MSVC 2010 SP1, the unpatched release has a bug where it applies SSE2 updates to mov and other instructions resulting in illegal instruction errors on cpu's only supporting SSE.
You also have to install Microsoft's DirectX SDK for Direct3D, DirectInput & XAudio2.
If you want to enable OpenAL sound output, install the OpenAL SDK. If you do not want it, add NO_OAL to the VBA-M project's preprocessor definitions.
SubWCRev.exe is used to append the svn versioning to the output executable, this as of TortoiseSVN 1.7, is only available by installing TortoiseSVN.
All other dependencies for MSVC builds may be found in the ../dependencies directory (above /trunk).
Normally, Windows users will want to checkout the root of the repository instead of just the trunk directory. Afterwards, simply opening the .sln of choice, setting preprocessor definitions, and hitting build is all that's required.
===*nix/GTK===
This is the standard build configuration on non-Windows.
Running cmake will inform you of any packages you need to install.
===src/wx===
The wxWidgets interface is an in-development frontend meant to be more cross-platform friendly than MFC and SDL.
===*/wxw===
The wxWidgets interface is an in-development frontend meant to be more cross-platform friendly than MFC and GTK.
Running cmake will inform you of any packages you need to install.
NOTE: In addition to what cmake currently checks for, you will also need the wxrc tool and libgdiplus.

View File

@ -9,7 +9,7 @@
VisualBoyAdvance-M
Nintendo Game Boy & Game Boy Advance Emulator
Project Homepage: http://visualboyadvance-m.org
Project Homepage: http://vba-m.com
This program is distributed under the GNU General Public License
http://www.gnu.org/licenses/gpl.html

200
fex/7z_C/7z.h Normal file
View File

@ -0,0 +1,200 @@
/* 7z.h -- 7z interface
2010-03-11 : Igor Pavlov : Public domain */
#ifndef __7Z_H
#define __7Z_H
#include "7zBuf.h"
EXTERN_C_BEGIN
#define k7zStartHeaderSize 0x20
#define k7zSignatureSize 6
extern Byte k7zSignature[k7zSignatureSize];
#define k7zMajorVersion 0
enum EIdEnum {
k7zIdEnd,
k7zIdHeader,
k7zIdArchiveProperties,
k7zIdAdditionalStreamsInfo,
k7zIdMainStreamsInfo,
k7zIdFilesInfo,
k7zIdPackInfo,
k7zIdUnpackInfo,
k7zIdSubStreamsInfo,
k7zIdSize,
k7zIdCRC,
k7zIdFolder,
k7zIdCodersUnpackSize,
k7zIdNumUnpackStream,
k7zIdEmptyStream,
k7zIdEmptyFile,
k7zIdAnti,
k7zIdName,
k7zIdCTime,
k7zIdATime,
k7zIdMTime,
k7zIdWinAttributes,
k7zIdComment,
k7zIdEncodedHeader,
k7zIdStartPos,
k7zIdDummy
};
typedef struct
{
UInt32 NumInStreams;
UInt32 NumOutStreams;
UInt64 MethodID;
CBuf Props;
} CSzCoderInfo;
void SzCoderInfo_Init(CSzCoderInfo* p);
void SzCoderInfo_Free(CSzCoderInfo* p, ISzAlloc* alloc);
typedef struct
{
UInt32 InIndex;
UInt32 OutIndex;
} CSzBindPair;
typedef struct
{
CSzCoderInfo* Coders;
CSzBindPair* BindPairs;
UInt32* PackStreams;
UInt64* UnpackSizes;
UInt32 NumCoders;
UInt32 NumBindPairs;
UInt32 NumPackStreams;
int UnpackCRCDefined;
UInt32 UnpackCRC;
UInt32 NumUnpackStreams;
} CSzFolder;
void SzFolder_Init(CSzFolder* p);
UInt64 SzFolder_GetUnpackSize(CSzFolder* p);
int SzFolder_FindBindPairForInStream(CSzFolder* p, UInt32 inStreamIndex);
UInt32 SzFolder_GetNumOutStreams(CSzFolder* p);
UInt64 SzFolder_GetUnpackSize(CSzFolder* p);
SRes SzFolder_Decode(const CSzFolder* folder, const UInt64* packSizes,
ILookInStream* stream, UInt64 startPos,
Byte* outBuffer, size_t outSize, ISzAlloc* allocMain);
typedef struct
{
UInt32 Low;
UInt32 High;
} CNtfsFileTime;
typedef struct
{
CNtfsFileTime MTime;
UInt64 Size;
UInt32 Crc;
UInt32 Attrib;
Byte HasStream;
Byte IsDir;
Byte IsAnti;
Byte CrcDefined;
Byte MTimeDefined;
Byte AttribDefined;
} CSzFileItem;
void SzFile_Init(CSzFileItem* p);
typedef struct
{
UInt64* PackSizes;
Byte* PackCRCsDefined;
UInt32* PackCRCs;
CSzFolder* Folders;
CSzFileItem* Files;
UInt32 NumPackStreams;
UInt32 NumFolders;
UInt32 NumFiles;
} CSzAr;
void SzAr_Init(CSzAr* p);
void SzAr_Free(CSzAr* p, ISzAlloc* alloc);
/*
SzExtract extracts file from archive
*outBuffer must be 0 before first call for each new archive.
Extracting cache:
If you need to decompress more than one file, you can send
these values from previous call:
*blockIndex,
*outBuffer,
*outBufferSize
You can consider "*outBuffer" as cache of solid block. If your archive is solid,
it will increase decompression speed.
If you use external function, you can declare these 3 cache variables
(blockIndex, outBuffer, outBufferSize) as static in that external function.
Free *outBuffer and set *outBuffer to 0, if you want to flush cache.
*/
typedef struct
{
CSzAr db;
UInt64 startPosAfterHeader;
UInt64 dataPos;
UInt32* FolderStartPackStreamIndex;
UInt64* PackStreamStartPositions;
UInt32* FolderStartFileIndex;
UInt32* FileIndexToFolderIndexMap;
size_t* FileNameOffsets; /* in 2-byte steps */
CBuf FileNames; /* UTF-16-LE */
} CSzArEx;
void SzArEx_Init(CSzArEx* p);
void SzArEx_Free(CSzArEx* p, ISzAlloc* alloc);
UInt64 SzArEx_GetFolderStreamPos(const CSzArEx* p, UInt32 folderIndex, UInt32 indexInFolder);
int SzArEx_GetFolderFullPackSize(const CSzArEx* p, UInt32 folderIndex, UInt64* resSize);
/*
if dest == NULL, the return value specifies the required size of the buffer,
in 16-bit characters, including the null-terminating character.
if dest != NULL, the return value specifies the number of 16-bit characters that
are written to the dest, including the null-terminating character. */
size_t SzArEx_GetFileNameUtf16(const CSzArEx* p, size_t fileIndex, UInt16* dest);
SRes SzArEx_Extract(
const CSzArEx* db,
ILookInStream* inStream,
UInt32 fileIndex, /* index of file */
UInt32* blockIndex, /* index of solid block */
Byte** outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */
size_t* outBufferSize, /* buffer size for output buffer */
size_t* offset, /* offset of stream for required file in *outBuffer */
size_t* outSizeProcessed, /* size of file in *outBuffer */
ISzAlloc* allocMain,
ISzAlloc* allocTemp);
/*
SzArEx_Open Errors:
SZ_ERROR_NO_ARCHIVE
SZ_ERROR_ARCHIVE
SZ_ERROR_UNSUPPORTED
SZ_ERROR_MEM
SZ_ERROR_CRC
SZ_ERROR_INPUT_EOF
SZ_ERROR_FAIL
*/
SRes SzArEx_Open(CSzArEx* p, ILookInStream* inStream, ISzAlloc* allocMain, ISzAlloc* allocTemp);
EXTERN_C_END
#endif

74
fex/7z_C/7zAlloc.c Normal file
View File

@ -0,0 +1,74 @@
/* 7zAlloc.c -- Allocation functions
2010-10-29 : Igor Pavlov : Public domain */
#include "7zAlloc.h"
/* #define _SZ_ALLOC_DEBUG */
/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */
#ifdef _SZ_ALLOC_DEBUG
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdio.h>
int g_allocCount = 0;
int g_allocCountTemp = 0;
#endif
void* SzAlloc(void* p, size_t size)
{
(void)p; // unused param
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc %10d bytes; count = %10d", size, g_allocCount);
g_allocCount++;
#endif
return malloc(size);
}
void SzFree(void* p, void* address)
{
(void)p; // unused param
#ifdef _SZ_ALLOC_DEBUG
if (address != 0) {
g_allocCount--;
fprintf(stderr, "\nFree; count = %10d", g_allocCount);
}
#endif
free(address);
}
void* SzAllocTemp(void* p, size_t size)
{
(void)p; // unused param
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc_temp %10d bytes; count = %10d", size, g_allocCountTemp);
g_allocCountTemp++;
#ifdef _WIN32
return HeapAlloc(GetProcessHeap(), 0, size);
#endif
#endif
return malloc(size);
}
void SzFreeTemp(void* p, void* address)
{
(void)p; // unused param
#ifdef _SZ_ALLOC_DEBUG
if (address != 0) {
g_allocCountTemp--;
fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp);
}
#ifdef _WIN32
HeapFree(GetProcessHeap(), 0, address);
return;
#endif
#endif
free(address);
}

15
fex/7z_C/7zAlloc.h Normal file
View File

@ -0,0 +1,15 @@
/* 7zAlloc.h -- Allocation functions
2010-10-29 : Igor Pavlov : Public domain */
#ifndef __7Z_ALLOC_H
#define __7Z_ALLOC_H
#include <stdlib.h>
void* SzAlloc(void* p, size_t size);
void SzFree(void* p, void* address);
void* SzAllocTemp(void* p, size_t size);
void SzFreeTemp(void* p, void* address);
#endif

34
fex/7z_C/7zBuf.c Normal file
View File

@ -0,0 +1,34 @@
/* 7zBuf.c -- Byte Buffer
2008-03-28
Igor Pavlov
Public domain */
#include "7zBuf.h"
void Buf_Init(CBuf* p)
{
p->data = 0;
p->size = 0;
}
int Buf_Create(CBuf* p, size_t size, ISzAlloc* alloc)
{
p->size = 0;
if (size == 0) {
p->data = 0;
return 1;
}
p->data = (Byte*)alloc->Alloc(alloc, size);
if (p->data != 0) {
p->size = size;
return 1;
}
return 0;
}
void Buf_Free(CBuf* p, ISzAlloc* alloc)
{
alloc->Free(alloc, p->data);
p->data = 0;
p->size = 0;
}

39
fex/7z_C/7zBuf.h Normal file
View File

@ -0,0 +1,39 @@
/* 7zBuf.h -- Byte Buffer
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __7Z_BUF_H
#define __7Z_BUF_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
Byte* data;
size_t size;
} CBuf;
void Buf_Init(CBuf* p);
int Buf_Create(CBuf* p, size_t size, ISzAlloc* alloc);
void Buf_Free(CBuf* p, ISzAlloc* alloc);
typedef struct
{
Byte* data;
size_t size;
size_t pos;
} CDynBuf;
void DynBuf_Construct(CDynBuf* p);
void DynBuf_SeekToBeg(CDynBuf* p);
int DynBuf_Write(CDynBuf* p, const Byte* buf, size_t size, ISzAlloc* alloc);
void DynBuf_Free(CDynBuf* p, ISzAlloc* alloc);
#ifdef __cplusplus
}
#endif
#endif

80
fex/7z_C/7zCrc.c Normal file
View File

@ -0,0 +1,80 @@
/* 7zCrc.c -- CRC32 init
2010-12-01 : Igor Pavlov : Public domain */
#include "7zCrc.h"
#include "CpuArch.h"
#define kCrcPoly 0xEDB88320
#ifdef MY_CPU_X86_OR_AMD64
#define CRC_NUM_TABLES 8
UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void* data, size_t size, const UInt32* table);
#elif defined(MY_CPU_LE)
#define CRC_NUM_TABLES 4
#else
#define CRC_NUM_TABLES 5
#define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24))
UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void* data, size_t size, const UInt32* table);
#endif
#ifndef MY_CPU_BE
UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void* data, size_t size, const UInt32* table);
#endif
typedef UInt32(MY_FAST_CALL* CRC_FUNC)(UInt32 v, const void* data, size_t size, const UInt32* table);
static CRC_FUNC g_CrcUpdate;
UInt32 g_CrcTable[256 * CRC_NUM_TABLES];
UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void* data, size_t size)
{
return g_CrcUpdate(v, data, size, g_CrcTable);
}
UInt32 MY_FAST_CALL CrcCalc(const void* data, size_t size)
{
return g_CrcUpdate(CRC_INIT_VAL, data, size, g_CrcTable) ^ CRC_INIT_VAL;
}
void MY_FAST_CALL CrcGenerateTable()
{
UInt32 i;
for (i = 0; i < 256; i++) {
UInt32 r = i;
unsigned j;
for (j = 0; j < 8; j++)
r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
g_CrcTable[i] = r;
}
for (; i < 256 * CRC_NUM_TABLES; i++) {
UInt32 r = g_CrcTable[i - 256];
g_CrcTable[i] = g_CrcTable[r & 0xFF] ^ (r >> 8);
}
#ifdef MY_CPU_LE
g_CrcUpdate = CrcUpdateT4;
#if CRC_NUM_TABLES == 8
if (!CPU_Is_InOrder())
g_CrcUpdate = CrcUpdateT8;
#endif
#else
{
#ifndef MY_CPU_BE
UInt32 k = 1;
if (*(const Byte*)&k == 1)
g_CrcUpdate = CrcUpdateT4;
else
#endif
{
for (i = 256 * CRC_NUM_TABLES - 1; i >= 256; i--) {
UInt32 x = g_CrcTable[i - 256];
g_CrcTable[i] = CRC_UINT32_SWAP(x);
}
g_CrcUpdate = CrcUpdateT1_BeT4;
}
}
#endif
}

25
fex/7z_C/7zCrc.h Normal file
View File

@ -0,0 +1,25 @@
/* 7zCrc.h -- CRC32 calculation
2009-11-21 : Igor Pavlov : Public domain */
#ifndef __7Z_CRC_H
#define __7Z_CRC_H
#include "Types.h"
EXTERN_C_BEGIN
extern UInt32 g_CrcTable[];
/* Call CrcGenerateTable one time before other CRC functions */
void MY_FAST_CALL CrcGenerateTable(void);
#define CRC_INIT_VAL 0xFFFFFFFF
#define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL)
#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void* data, size_t size);
UInt32 MY_FAST_CALL CrcCalc(const void* data, size_t size);
EXTERN_C_END
#endif

53
fex/7z_C/7zCrcOpt.c Normal file
View File

@ -0,0 +1,53 @@
/* 7zCrcOpt.c -- CRC32 calculation
2010-12-01 : Igor Pavlov : Public domain */
#include "CpuArch.h"
#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
#ifndef MY_CPU_BE
UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void* data, size_t size, const UInt32* table)
{
const Byte* p = (const Byte*)data;
for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++)
v = CRC_UPDATE_BYTE_2(v, *p);
for (; size >= 4; size -= 4, p += 4) {
v ^= *(const UInt32*)p;
v = table[0x300 + (v & 0xFF)] ^ table[0x200 + ((v >> 8) & 0xFF)] ^ table[0x100 + ((v >> 16) & 0xFF)] ^ table[0x000 + ((v >> 24))];
}
for (; size > 0; size--, p++)
v = CRC_UPDATE_BYTE_2(v, *p);
return v;
}
UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void* data, size_t size, const UInt32* table)
{
return CrcUpdateT4(v, data, size, table);
}
#endif
#ifndef MY_CPU_LE
#define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24))
UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void* data, size_t size, const UInt32* table)
{
const Byte* p = (const Byte*)data;
for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++)
v = CRC_UPDATE_BYTE_2(v, *p);
v = CRC_UINT32_SWAP(v);
table += 0x100;
for (; size >= 4; size -= 4, p += 4) {
v ^= *(const UInt32*)p;
v = table[0x000 + (v & 0xFF)] ^ table[0x100 + ((v >> 8) & 0xFF)] ^ table[0x200 + ((v >> 16) & 0xFF)] ^ table[0x300 + ((v >> 24))];
}
table -= 0x100;
v = CRC_UINT32_SWAP(v);
for (; size > 0; size--, p++)
v = CRC_UPDATE_BYTE_2(v, *p);
return v;
}
#endif

413
fex/7z_C/7zDec.c Normal file
View File

@ -0,0 +1,413 @@
/* 7zDec.c -- Decoding from 7z folder
2010-11-02 : Igor Pavlov : Public domain */
#include <string.h>
/* #define _7ZIP_PPMD_SUPPPORT */
#include "7z.h"
#include "Bcj2.h"
#include "Bra.h"
#include "CpuArch.h"
#include "Lzma2Dec.h"
#include "LzmaDec.h"
#ifdef _7ZIP_PPMD_SUPPPORT
#include "Ppmd7.h"
#endif
#define k_Copy 0
#define k_LZMA2 0x21
#define k_LZMA 0x30101
#define k_BCJ 0x03030103
#define k_PPC 0x03030205
#define k_ARM 0x03030501
#define k_ARMT 0x03030701
#define k_SPARC 0x03030805
#define k_BCJ2 0x0303011B
#ifdef _7ZIP_PPMD_SUPPPORT
#define k_PPMD 0x30401
typedef struct
{
IByteIn p;
const Byte* cur;
const Byte* end;
const Byte* begin;
UInt64 processed;
Bool extra;
SRes res;
ILookInStream* inStream;
} CByteInToLook;
static Byte ReadByte(void* pp)
{
CByteInToLook* p = (CByteInToLook*)pp;
if (p->cur != p->end)
return *p->cur++;
if (p->res == SZ_OK) {
size_t size = p->cur - p->begin;
p->processed += size;
p->res = p->inStream->Skip(p->inStream, size);
size = (1 << 25);
p->res = p->inStream->Look(p->inStream, (const void**)&p->begin, &size);
p->cur = p->begin;
p->end = p->begin + size;
if (size != 0)
return *p->cur++;
;
}
p->extra = True;
return 0;
}
static SRes SzDecodePpmd(CSzCoderInfo* coder, UInt64 inSize, ILookInStream* inStream,
Byte* outBuffer, SizeT outSize, ISzAlloc* allocMain)
{
CPpmd7 ppmd;
CByteInToLook s;
SRes res = SZ_OK;
s.p.Read = ReadByte;
s.inStream = inStream;
s.begin = s.end = s.cur = NULL;
s.extra = False;
s.res = SZ_OK;
s.processed = 0;
if (coder->Props.size != 5)
return SZ_ERROR_UNSUPPORTED;
{
unsigned order = coder->Props.data[0];
UInt32 memSize = GetUi32(coder->Props.data + 1);
if (order < PPMD7_MIN_ORDER || order > PPMD7_MAX_ORDER || memSize < PPMD7_MIN_MEM_SIZE || memSize > PPMD7_MAX_MEM_SIZE)
return SZ_ERROR_UNSUPPORTED;
Ppmd7_Construct(&ppmd);
if (!Ppmd7_Alloc(&ppmd, memSize, allocMain))
return SZ_ERROR_MEM;
Ppmd7_Init(&ppmd, order);
}
{
CPpmd7z_RangeDec rc;
Ppmd7z_RangeDec_CreateVTable(&rc);
rc.Stream = &s.p;
if (!Ppmd7z_RangeDec_Init(&rc))
res = SZ_ERROR_DATA;
else if (s.extra)
res = (s.res != SZ_OK ? s.res : SZ_ERROR_DATA);
else {
SizeT i;
for (i = 0; i < outSize; i++) {
int sym = Ppmd7_DecodeSymbol(&ppmd, &rc.p);
if (s.extra || sym < 0)
break;
outBuffer[i] = (Byte)sym;
}
if (i != outSize)
res = (s.res != SZ_OK ? s.res : SZ_ERROR_DATA);
else if (s.processed + (s.cur - s.begin) != inSize || !Ppmd7z_RangeDec_IsFinishedOK(&rc))
res = SZ_ERROR_DATA;
}
}
Ppmd7_Free(&ppmd, allocMain);
return res;
}
#endif
static SRes SzDecodeLzma(CSzCoderInfo* coder, UInt64 inSize, ILookInStream* inStream,
Byte* outBuffer, SizeT outSize, ISzAlloc* allocMain)
{
CLzmaDec state;
SRes res = SZ_OK;
LzmaDec_Construct(&state);
RINOK(LzmaDec_AllocateProbs(&state, coder->Props.data, (unsigned)coder->Props.size, allocMain));
state.dic = outBuffer;
state.dicBufSize = outSize;
LzmaDec_Init(&state);
for (;;) {
Byte* inBuf = NULL;
size_t lookahead = (1 << 18);
if (lookahead > inSize)
lookahead = (size_t)inSize;
res = inStream->Look((void*)inStream, (const void**)&inBuf, &lookahead);
if (res != SZ_OK)
break;
{
SizeT inProcessed = (SizeT)lookahead, dicPos = state.dicPos;
ELzmaStatus status;
res = LzmaDec_DecodeToDic(&state, outSize, inBuf, &inProcessed, LZMA_FINISH_END, &status);
lookahead -= inProcessed;
inSize -= inProcessed;
if (res != SZ_OK)
break;
if (state.dicPos == state.dicBufSize || (inProcessed == 0 && dicPos == state.dicPos)) {
if (state.dicBufSize != outSize || lookahead != 0 || (status != LZMA_STATUS_FINISHED_WITH_MARK && status != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK))
res = SZ_ERROR_DATA;
break;
}
res = inStream->Skip((void*)inStream, inProcessed);
if (res != SZ_OK)
break;
}
}
LzmaDec_FreeProbs(&state, allocMain);
return res;
}
static SRes SzDecodeLzma2(CSzCoderInfo* coder, UInt64 inSize, ILookInStream* inStream,
Byte* outBuffer, SizeT outSize, ISzAlloc* allocMain)
{
CLzma2Dec state;
SRes res = SZ_OK;
Lzma2Dec_Construct(&state);
if (coder->Props.size != 1)
return SZ_ERROR_DATA;
RINOK(Lzma2Dec_AllocateProbs(&state, coder->Props.data[0], allocMain));
state.decoder.dic = outBuffer;
state.decoder.dicBufSize = outSize;
Lzma2Dec_Init(&state);
for (;;) {
Byte* inBuf = NULL;
size_t lookahead = (1 << 18);
if (lookahead > inSize)
lookahead = (size_t)inSize;
res = inStream->Look((void*)inStream, (const void**)&inBuf, &lookahead);
if (res != SZ_OK)
break;
{
SizeT inProcessed = (SizeT)lookahead, dicPos = state.decoder.dicPos;
ELzmaStatus status;
res = Lzma2Dec_DecodeToDic(&state, outSize, inBuf, &inProcessed, LZMA_FINISH_END, &status);
lookahead -= inProcessed;
inSize -= inProcessed;
if (res != SZ_OK)
break;
if (state.decoder.dicPos == state.decoder.dicBufSize || (inProcessed == 0 && dicPos == state.decoder.dicPos)) {
if (state.decoder.dicBufSize != outSize || lookahead != 0 || (status != LZMA_STATUS_FINISHED_WITH_MARK))
res = SZ_ERROR_DATA;
break;
}
res = inStream->Skip((void*)inStream, inProcessed);
if (res != SZ_OK)
break;
}
}
Lzma2Dec_FreeProbs(&state, allocMain);
return res;
}
static SRes SzDecodeCopy(UInt64 inSize, ILookInStream* inStream, Byte* outBuffer)
{
while (inSize > 0) {
void* inBuf;
size_t curSize = (1 << 18);
if (curSize > inSize)
curSize = (size_t)inSize;
RINOK(inStream->Look((void*)inStream, (const void**)&inBuf, &curSize));
if (curSize == 0)
return SZ_ERROR_INPUT_EOF;
memcpy(outBuffer, inBuf, curSize);
outBuffer += curSize;
inSize -= curSize;
RINOK(inStream->Skip((void*)inStream, curSize));
}
return SZ_OK;
}
static Bool IS_MAIN_METHOD(UInt32 m)
{
switch (m) {
case k_Copy:
case k_LZMA:
case k_LZMA2:
#ifdef _7ZIP_PPMD_SUPPPORT
case k_PPMD:
#endif
return True;
}
return False;
}
static Bool IS_SUPPORTED_CODER(const CSzCoderInfo* c)
{
return c->NumInStreams == 1 && c->NumOutStreams == 1 && c->MethodID <= (UInt32)0xFFFFFFFF && IS_MAIN_METHOD((UInt32)c->MethodID);
}
#define IS_BCJ2(c) ((c)->MethodID == k_BCJ2 && (c)->NumInStreams == 4 && (c)->NumOutStreams == 1)
static SRes CheckSupportedFolder(const CSzFolder* f)
{
if (f->NumCoders < 1 || f->NumCoders > 4)
return SZ_ERROR_UNSUPPORTED;
if (!IS_SUPPORTED_CODER(&f->Coders[0]))
return SZ_ERROR_UNSUPPORTED;
if (f->NumCoders == 1) {
if (f->NumPackStreams != 1 || f->PackStreams[0] != 0 || f->NumBindPairs != 0)
return SZ_ERROR_UNSUPPORTED;
return SZ_OK;
}
if (f->NumCoders == 2) {
CSzCoderInfo* c = &f->Coders[1];
if (c->MethodID > (UInt32)0xFFFFFFFF || c->NumInStreams != 1 || c->NumOutStreams != 1 || f->NumPackStreams != 1 || f->PackStreams[0] != 0 || f->NumBindPairs != 1 || f->BindPairs[0].InIndex != 1 || f->BindPairs[0].OutIndex != 0)
return SZ_ERROR_UNSUPPORTED;
switch ((UInt32)c->MethodID) {
case k_BCJ:
case k_ARM:
break;
default:
return SZ_ERROR_UNSUPPORTED;
}
return SZ_OK;
}
if (f->NumCoders == 4) {
if (!IS_SUPPORTED_CODER(&f->Coders[1]) || !IS_SUPPORTED_CODER(&f->Coders[2]) || !IS_BCJ2(&f->Coders[3]))
return SZ_ERROR_UNSUPPORTED;
if (f->NumPackStreams != 4 || f->PackStreams[0] != 2 || f->PackStreams[1] != 6 || f->PackStreams[2] != 1 || f->PackStreams[3] != 0 || f->NumBindPairs != 3 || f->BindPairs[0].InIndex != 5 || f->BindPairs[0].OutIndex != 0 || f->BindPairs[1].InIndex != 4 || f->BindPairs[1].OutIndex != 1 || f->BindPairs[2].InIndex != 3 || f->BindPairs[2].OutIndex != 2)
return SZ_ERROR_UNSUPPORTED;
return SZ_OK;
}
return SZ_ERROR_UNSUPPORTED;
}
static UInt64 GetSum(const UInt64* values, UInt32 index)
{
UInt64 sum = 0;
UInt32 i;
for (i = 0; i < index; i++)
sum += values[i];
return sum;
}
#define CASE_BRA_CONV(isa) \
case k_##isa: \
isa##_Convert(outBuffer, outSize, 0, 0); \
break;
static SRes SzFolder_Decode2(const CSzFolder* folder, const UInt64* packSizes,
ILookInStream* inStream, UInt64 startPos,
Byte* outBuffer, SizeT outSize, ISzAlloc* allocMain,
Byte* tempBuf[])
{
UInt32 ci;
SizeT tempSizes[3] = { 0, 0, 0 };
SizeT tempSize3 = 0;
Byte* tempBuf3 = 0;
RINOK(CheckSupportedFolder(folder));
for (ci = 0; ci < folder->NumCoders; ci++) {
CSzCoderInfo* coder = &folder->Coders[ci];
if (IS_MAIN_METHOD((UInt32)coder->MethodID)) {
UInt32 si = 0;
UInt64 offset;
UInt64 inSize;
Byte* outBufCur = outBuffer;
SizeT outSizeCur = outSize;
if (folder->NumCoders == 4) {
UInt32 indices[] = { 3, 2, 0 };
UInt64 unpackSize = folder->UnpackSizes[ci];
si = indices[ci];
if (ci < 2) {
Byte* temp;
outSizeCur = (SizeT)unpackSize;
if (outSizeCur != unpackSize)
return SZ_ERROR_MEM;
temp = (Byte*)IAlloc_Alloc(allocMain, outSizeCur);
if (temp == 0 && outSizeCur != 0)
return SZ_ERROR_MEM;
outBufCur = tempBuf[1 - ci] = temp;
tempSizes[1 - ci] = outSizeCur;
} else if (ci == 2) {
if (unpackSize > outSize) /* check it */
return SZ_ERROR_PARAM;
tempBuf3 = outBufCur = outBuffer + (outSize - (size_t)unpackSize);
tempSize3 = outSizeCur = (SizeT)unpackSize;
} else
return SZ_ERROR_UNSUPPORTED;
}
offset = GetSum(packSizes, si);
inSize = packSizes[si];
RINOK(LookInStream_SeekTo(inStream, startPos + offset));
if (coder->MethodID == k_Copy) {
if (inSize != outSizeCur) /* check it */
return SZ_ERROR_DATA;
RINOK(SzDecodeCopy(inSize, inStream, outBufCur));
} else if (coder->MethodID == k_LZMA) {
RINOK(SzDecodeLzma(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
} else if (coder->MethodID == k_LZMA2) {
RINOK(SzDecodeLzma2(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
} else {
#ifdef _7ZIP_PPMD_SUPPPORT
RINOK(SzDecodePpmd(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
#else
return SZ_ERROR_UNSUPPORTED;
#endif
}
} else if (coder->MethodID == k_BCJ2) {
UInt64 offset = GetSum(packSizes, 1);
UInt64 s3Size = packSizes[1];
SRes res;
if (ci != 3)
return SZ_ERROR_UNSUPPORTED;
RINOK(LookInStream_SeekTo(inStream, startPos + offset));
tempSizes[2] = (SizeT)s3Size;
if (tempSizes[2] != s3Size)
return SZ_ERROR_MEM;
tempBuf[2] = (Byte*)IAlloc_Alloc(allocMain, tempSizes[2]);
if (tempBuf[2] == 0 && tempSizes[2] != 0)
return SZ_ERROR_MEM;
res = SzDecodeCopy(s3Size, inStream, tempBuf[2]);
RINOK(res)
res = Bcj2_Decode(
tempBuf3, tempSize3,
tempBuf[0], tempSizes[0],
tempBuf[1], tempSizes[1],
tempBuf[2], tempSizes[2],
outBuffer, outSize);
RINOK(res)
} else {
if (ci != 1)
return SZ_ERROR_UNSUPPORTED;
switch (coder->MethodID) {
case k_BCJ: {
UInt32 state;
x86_Convert_Init(state);
x86_Convert(outBuffer, outSize, 0, &state, 0);
break;
}
CASE_BRA_CONV(ARM)
default:
return SZ_ERROR_UNSUPPORTED;
}
}
}
return SZ_OK;
}
SRes SzFolder_Decode(const CSzFolder* folder, const UInt64* packSizes,
ILookInStream* inStream, UInt64 startPos,
Byte* outBuffer, size_t outSize, ISzAlloc* allocMain)
{
Byte* tempBuf[3] = { 0, 0, 0 };
int i;
SRes res = SzFolder_Decode2(folder, packSizes, inStream, startPos,
outBuffer, (SizeT)outSize, allocMain, tempBuf);
for (i = 0; i < 3; i++)
IAlloc_Free(allocMain, tempBuf[i]);
return res;
}

1293
fex/7z_C/7zIn.c Normal file

File diff suppressed because it is too large Load Diff

163
fex/7z_C/7zStream.c Normal file
View File

@ -0,0 +1,163 @@
/* 7zStream.c -- 7z Stream functions
2010-03-11 : Igor Pavlov : Public domain */
#include <string.h>
#include "Types.h"
SRes SeqInStream_Read2(ISeqInStream* stream, void* buf, size_t size, SRes errorType)
{
while (size != 0) {
size_t processed = size;
RINOK(stream->Read(stream, buf, &processed));
if (processed == 0)
return errorType;
buf = (void*)((Byte*)buf + processed);
size -= processed;
}
return SZ_OK;
}
SRes SeqInStream_Read(ISeqInStream* stream, void* buf, size_t size)
{
return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
}
SRes SeqInStream_ReadByte(ISeqInStream* stream, Byte* buf)
{
size_t processed = 1;
RINOK(stream->Read(stream, buf, &processed));
return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF;
}
SRes LookInStream_SeekTo(ILookInStream* stream, UInt64 offset)
{
Int64 t = offset;
return stream->Seek(stream, &t, SZ_SEEK_SET);
}
SRes LookInStream_LookRead(ILookInStream* stream, void* buf, size_t* size)
{
const void* lookBuf;
if (*size == 0)
return SZ_OK;
RINOK(stream->Look(stream, &lookBuf, size));
memcpy(buf, lookBuf, *size);
return stream->Skip(stream, *size);
}
SRes LookInStream_Read2(ILookInStream* stream, void* buf, size_t size, SRes errorType)
{
while (size != 0) {
size_t processed = size;
RINOK(stream->Read(stream, buf, &processed));
if (processed == 0)
return errorType;
buf = (void*)((Byte*)buf + processed);
size -= processed;
}
return SZ_OK;
}
SRes LookInStream_Read(ILookInStream* stream, void* buf, size_t size)
{
return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
}
static SRes LookToRead_Look_Lookahead(void* pp, const void** buf, size_t* size)
{
SRes res = SZ_OK;
CLookToRead* p = (CLookToRead*)pp;
size_t size2 = p->size - p->pos;
if (size2 == 0 && *size > 0) {
p->pos = 0;
size2 = LookToRead_BUF_SIZE;
res = p->realStream->Read(p->realStream, p->buf, &size2);
p->size = size2;
}
if (size2 < *size)
*size = size2;
*buf = p->buf + p->pos;
return res;
}
static SRes LookToRead_Look_Exact(void* pp, const void** buf, size_t* size)
{
SRes res = SZ_OK;
CLookToRead* p = (CLookToRead*)pp;
size_t size2 = p->size - p->pos;
if (size2 == 0 && *size > 0) {
p->pos = 0;
if (*size > LookToRead_BUF_SIZE)
*size = LookToRead_BUF_SIZE;
res = p->realStream->Read(p->realStream, p->buf, size);
size2 = p->size = *size;
}
if (size2 < *size)
*size = size2;
*buf = p->buf + p->pos;
return res;
}
static SRes LookToRead_Skip(void* pp, size_t offset)
{
CLookToRead* p = (CLookToRead*)pp;
p->pos += offset;
return SZ_OK;
}
static SRes LookToRead_Read(void* pp, void* buf, size_t* size)
{
CLookToRead* p = (CLookToRead*)pp;
size_t rem = p->size - p->pos;
if (rem == 0)
return p->realStream->Read(p->realStream, buf, size);
if (rem > *size)
rem = *size;
memcpy(buf, p->buf + p->pos, rem);
p->pos += rem;
*size = rem;
return SZ_OK;
}
static SRes LookToRead_Seek(void* pp, Int64* pos, ESzSeek origin)
{
CLookToRead* p = (CLookToRead*)pp;
p->pos = p->size = 0;
return p->realStream->Seek(p->realStream, pos, origin);
}
void LookToRead_CreateVTable(CLookToRead* p, int lookahead)
{
p->s.Look = lookahead ? LookToRead_Look_Lookahead : LookToRead_Look_Exact;
p->s.Skip = LookToRead_Skip;
p->s.Read = LookToRead_Read;
p->s.Seek = LookToRead_Seek;
}
void LookToRead_Init(CLookToRead* p)
{
p->pos = p->size = 0;
}
static SRes SecToLook_Read(void* pp, void* buf, size_t* size)
{
CSecToLook* p = (CSecToLook*)pp;
return LookInStream_LookRead(p->realStream, buf, size);
}
void SecToLook_CreateVTable(CSecToLook* p)
{
p->s.Read = SecToLook_Read;
}
static SRes SecToRead_Read(void* pp, void* buf, size_t* size)
{
CSecToRead* p = (CSecToRead*)pp;
return p->realStream->Read(p->realStream, buf, size);
}
void SecToRead_CreateVTable(CSecToRead* p)
{
p->s.Read = SecToRead_Read;
}

153
fex/7z_C/Bcj2.c Normal file
View File

@ -0,0 +1,153 @@
/* Bcj2.c -- Converter for x86 code (BCJ2)
2008-10-04 : Igor Pavlov : Public domain */
#include "Bcj2.h"
#ifdef _LZMA_PROB32
#define CProb UInt32
#else
#define CProb UInt16
#endif
#define IsJcc(b0, b1) ((b0) == 0x0F && ((b1)&0xF0) == 0x80)
#define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1))
#define kNumTopBits 24
#define kTopValue ((UInt32)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
#define RC_READ_BYTE (*buffer++)
#define RC_TEST \
{ \
if (buffer == bufferLim) \
return SZ_ERROR_DATA; \
}
#define RC_INIT2 \
code = 0; \
range = 0xFFFFFFFF; \
{ \
int i; \
for (i = 0; i < 5; i++) { \
RC_TEST; \
code = (code << 8) | RC_READ_BYTE; \
} \
}
#define NORMALIZE \
if (range < kTopValue) { \
RC_TEST; \
range <<= 8; \
code = (code << 8) | RC_READ_BYTE; \
}
#define IF_BIT_0(p) \
ttt = *(p); \
bound = (range >> kNumBitModelTotalBits) * ttt; \
if (code < bound)
#define UPDATE_0(p) \
range = bound; \
*(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); \
NORMALIZE;
#define UPDATE_1(p) \
range -= bound; \
code -= bound; \
*(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); \
NORMALIZE;
int Bcj2_Decode(
const Byte* buf0, SizeT size0,
const Byte* buf1, SizeT size1,
const Byte* buf2, SizeT size2,
const Byte* buf3, SizeT size3,
Byte* outBuf, SizeT outSize)
{
CProb p[256 + 2];
SizeT inPos = 0, outPos = 0;
const Byte *buffer, *bufferLim;
UInt32 range, code;
Byte prevByte = 0;
unsigned int i;
for (i = 0; i < sizeof(p) / sizeof(p[0]); i++)
p[i] = kBitModelTotal >> 1;
buffer = buf3;
bufferLim = buffer + size3;
RC_INIT2
if (outSize == 0)
return SZ_OK;
for (;;) {
Byte b;
CProb* prob;
UInt32 bound;
UInt32 ttt;
SizeT limit = size0 - inPos;
if (outSize - outPos < limit)
limit = outSize - outPos;
while (limit != 0) {
Byte b = buf0[inPos];
outBuf[outPos++] = b;
if (IsJ(prevByte, b))
break;
inPos++;
prevByte = b;
limit--;
}
if (limit == 0 || outPos == outSize)
break;
b = buf0[inPos++];
if (b == 0xE8)
prob = p + prevByte;
else if (b == 0xE9)
prob = p + 256;
else
prob = p + 257;
IF_BIT_0(prob)
{
UPDATE_0(prob)
prevByte = b;
}
else
{
UInt32 dest;
const Byte* v;
UPDATE_1(prob)
if (b == 0xE8) {
v = buf1;
if (size1 < 4)
return SZ_ERROR_DATA;
buf1 += 4;
size1 -= 4;
} else {
v = buf2;
if (size2 < 4)
return SZ_ERROR_DATA;
buf2 += 4;
size2 -= 4;
}
dest = (((UInt32)v[0] << 24) | ((UInt32)v[1] << 16) | ((UInt32)v[2] << 8) | ((UInt32)v[3])) - ((UInt32)outPos + 4);
outBuf[outPos++] = (Byte)dest;
if (outPos == outSize)
break;
outBuf[outPos++] = (Byte)(dest >> 8);
if (outPos == outSize)
break;
outBuf[outPos++] = (Byte)(dest >> 16);
if (outPos == outSize)
break;
outBuf[outPos++] = prevByte = (Byte)(dest >> 24);
}
}
return (outPos == outSize) ? SZ_OK : SZ_ERROR_DATA;
}

38
fex/7z_C/Bcj2.h Normal file
View File

@ -0,0 +1,38 @@
/* Bcj2.h -- Converter for x86 code (BCJ2)
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __BCJ2_H
#define __BCJ2_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
Conditions:
outSize <= FullOutputSize,
where FullOutputSize is full size of output stream of x86_2 filter.
If buf0 overlaps outBuf, there are two required conditions:
1) (buf0 >= outBuf)
2) (buf0 + size0 >= outBuf + FullOutputSize).
Returns:
SZ_OK
SZ_ERROR_DATA - Data error
*/
int Bcj2_Decode(
const Byte* buf0, SizeT size0,
const Byte* buf1, SizeT size1,
const Byte* buf2, SizeT size2,
const Byte* buf3, SizeT size3,
Byte* outBuf, SizeT outSize);
#ifdef __cplusplus
}
#endif
#endif

112
fex/7z_C/Bra.c Normal file
View File

@ -0,0 +1,112 @@
/* Bra.c -- Converters for RISC code
2010-04-16 : Igor Pavlov : Public domain */
#include "Bra.h"
SizeT ARM_Convert(Byte* data, SizeT size, UInt32 ip, int encoding)
{
SizeT i;
if (size < 4)
return 0;
size -= 4;
ip += 8;
for (i = 0; i <= size; i += 4) {
if (data[i + 3] == 0xEB) {
UInt32 dest;
UInt32 src = ((UInt32)data[i + 2] << 16) | ((UInt32)data[i + 1] << 8) | (data[i + 0]);
src <<= 2;
if (encoding)
dest = ip + (UInt32)i + src;
else
dest = src - (ip + (UInt32)i);
dest >>= 2;
data[i + 2] = (Byte)(dest >> 16);
data[i + 1] = (Byte)(dest >> 8);
data[i + 0] = (Byte)dest;
}
}
return i;
}
SizeT ARMT_Convert(Byte* data, SizeT size, UInt32 ip, int encoding)
{
SizeT i;
if (size < 4)
return 0;
size -= 4;
ip += 4;
for (i = 0; i <= size; i += 2) {
if ((data[i + 1] & 0xF8) == 0xF0 && (data[i + 3] & 0xF8) == 0xF8) {
UInt32 dest;
UInt32 src = (((UInt32)data[i + 1] & 0x7) << 19) | ((UInt32)data[i + 0] << 11) | (((UInt32)data[i + 3] & 0x7) << 8) | (data[i + 2]);
src <<= 1;
if (encoding)
dest = ip + (UInt32)i + src;
else
dest = src - (ip + (UInt32)i);
dest >>= 1;
data[i + 1] = (Byte)(0xF0 | ((dest >> 19) & 0x7));
data[i + 0] = (Byte)(dest >> 11);
data[i + 3] = (Byte)(0xF8 | ((dest >> 8) & 0x7));
data[i + 2] = (Byte)dest;
i += 2;
}
}
return i;
}
SizeT PPC_Convert(Byte* data, SizeT size, UInt32 ip, int encoding)
{
SizeT i;
if (size < 4)
return 0;
size -= 4;
for (i = 0; i <= size; i += 4) {
if ((data[i] >> 2) == 0x12 && (data[i + 3] & 3) == 1) {
UInt32 src = ((UInt32)(data[i + 0] & 3) << 24) | ((UInt32)data[i + 1] << 16) | ((UInt32)data[i + 2] << 8) | ((UInt32)data[i + 3] & (~3));
UInt32 dest;
if (encoding)
dest = ip + (UInt32)i + src;
else
dest = src - (ip + (UInt32)i);
data[i + 0] = (Byte)(0x48 | ((dest >> 24) & 0x3));
data[i + 1] = (Byte)(dest >> 16);
data[i + 2] = (Byte)(dest >> 8);
data[i + 3] &= 0x3;
data[i + 3] |= dest;
}
}
return i;
}
SizeT SPARC_Convert(Byte* data, SizeT size, UInt32 ip, int encoding)
{
UInt32 i;
if (size < 4)
return 0;
size -= 4;
for (i = 0; i <= size; i += 4) {
if ((data[i] == 0x40 && (data[i + 1] & 0xC0) == 0x00) || (data[i] == 0x7F && (data[i + 1] & 0xC0) == 0xC0)) {
UInt32 src = ((UInt32)data[i + 0] << 24) | ((UInt32)data[i + 1] << 16) | ((UInt32)data[i + 2] << 8) | ((UInt32)data[i + 3]);
UInt32 dest;
src <<= 2;
if (encoding)
dest = ip + i + src;
else
dest = src - (ip + i);
dest >>= 2;
dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF) | (dest & 0x3FFFFF) | 0x40000000;
data[i + 0] = (Byte)(dest >> 24);
data[i + 1] = (Byte)(dest >> 16);
data[i + 2] = (Byte)(dest >> 8);
data[i + 3] = (Byte)dest;
}
}
return i;
}

71
fex/7z_C/Bra.h Normal file
View File

@ -0,0 +1,71 @@
/* Bra.h -- Branch converters for executables
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __BRA_H
#define __BRA_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
These functions convert relative addresses to absolute addresses
in CALL instructions to increase the compression ratio.
In:
data - data buffer
size - size of data
ip - current virtual Instruction Pinter (IP) value
state - state variable for x86 converter
encoding - 0 (for decoding), 1 (for encoding)
Out:
state - state variable for x86 converter
Returns:
The number of processed bytes. If you call these functions with multiple calls,
you must start next call with first byte after block of processed bytes.
Type Endian Alignment LookAhead
x86 little 1 4
ARMT little 2 2
ARM little 4 0
PPC big 4 0
SPARC big 4 0
IA64 little 16 0
size must be >= Alignment + LookAhead, if it's not last block.
If (size < Alignment + LookAhead), converter returns 0.
Example:
UInt32 ip = 0;
for ()
{
; size must be >= Alignment + LookAhead, if it's not last block
SizeT processed = Convert(data, size, ip, 1);
data += processed;
size -= processed;
ip += processed;
}
*/
#define x86_Convert_Init(state) \
{ \
state = 0; \
}
SizeT x86_Convert(Byte* data, SizeT size, UInt32 ip, UInt32* state, int encoding);
SizeT ARM_Convert(Byte* data, SizeT size, UInt32 ip, int encoding);
SizeT ARMT_Convert(Byte* data, SizeT size, UInt32 ip, int encoding);
SizeT PPC_Convert(Byte* data, SizeT size, UInt32 ip, int encoding);
SizeT SPARC_Convert(Byte* data, SizeT size, UInt32 ip, int encoding);
SizeT IA64_Convert(Byte* data, SizeT size, UInt32 ip, int encoding);
#ifdef __cplusplus
}
#endif
#endif

77
fex/7z_C/Bra86.c Normal file
View File

@ -0,0 +1,77 @@
/* Bra86.c -- Converter for x86 code (BCJ)
2008-10-04 : Igor Pavlov : Public domain */
#include "Bra.h"
#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)
const Byte kMaskToAllowedStatus[8] = { 1, 1, 1, 0, 1, 0, 0, 0 };
const Byte kMaskToBitNumber[8] = { 0, 1, 2, 2, 3, 3, 3, 3 };
SizeT x86_Convert(Byte* data, SizeT size, UInt32 ip, UInt32* state, int encoding)
{
SizeT bufferPos = 0, prevPosT;
UInt32 prevMask = *state & 0x7;
if (size < 5)
return 0;
ip += 5;
prevPosT = (SizeT)0 - 1;
for (;;) {
Byte* p = data + bufferPos;
Byte* limit = data + size - 4;
for (; p < limit; p++)
if ((*p & 0xFE) == 0xE8)
break;
bufferPos = (SizeT)(p - data);
if (p >= limit)
break;
prevPosT = bufferPos - prevPosT;
if (prevPosT > 3)
prevMask = 0;
else {
prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7;
if (prevMask != 0) {
Byte b = p[4 - kMaskToBitNumber[prevMask]];
if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b)) {
prevPosT = bufferPos;
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
continue;
}
}
}
prevPosT = bufferPos;
if (Test86MSByte(p[4])) {
UInt32 src = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]);
UInt32 dest;
for (;;) {
Byte b;
int index;
if (encoding)
dest = (ip + (UInt32)bufferPos) + src;
else
dest = src - (ip + (UInt32)bufferPos);
if (prevMask == 0)
break;
index = kMaskToBitNumber[prevMask] * 8;
b = (Byte)(dest >> (24 - index));
if (!Test86MSByte(b))
break;
src = dest ^ ((1 << (32 - index)) - 1);
}
p[4] = (Byte)(~(((dest >> 24) & 1) - 1));
p[3] = (Byte)(dest >> 16);
p[2] = (Byte)(dest >> 8);
p[1] = (Byte)dest;
bufferPos += 5;
} else {
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
}
}
prevPosT = bufferPos - prevPosT;
*state = ((prevPosT > 3) ? 0 : ((prevMask << ((int)prevPosT - 1)) & 0x7));
return bufferPos;
}

171
fex/7z_C/CpuArch.c Normal file
View File

@ -0,0 +1,171 @@
/* CpuArch.c -- CPU specific code
2010-10-26: Igor Pavlov : Public domain */
#include "CpuArch.h"
#ifdef MY_CPU_X86_OR_AMD64
#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__)
#define USE_ASM
#endif
#if defined(USE_ASM) && !defined(MY_CPU_AMD64)
static UInt32 CheckFlag(UInt32 flag)
{
#ifdef _MSC_VER
__asm pushfd;
__asm pop EAX;
__asm mov EDX, EAX;
__asm xor EAX, flag;
__asm push EAX;
__asm popfd;
__asm pushfd;
__asm pop EAX;
__asm xor EAX, EDX;
__asm push EDX;
__asm popfd;
__asm and flag, EAX;
#else
__asm__ __volatile__(
"pushf\n\t"
"pop %%EAX\n\t"
"movl %%EAX,%%EDX\n\t"
"xorl %0,%%EAX\n\t"
"push %%EAX\n\t"
"popf\n\t"
"pushf\n\t"
"pop %%EAX\n\t"
"xorl %%EDX,%%EAX\n\t"
"push %%EDX\n\t"
"popf\n\t"
"andl %%EAX, %0\n\t"
: "=c"(flag)
: "c"(flag));
#endif
return flag;
}
#define CHECK_CPUID_IS_SUPPORTED \
if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) \
return False;
#else
#define CHECK_CPUID_IS_SUPPORTED
#endif
static void MyCPUID(UInt32 function, UInt32* a, UInt32* b, UInt32* c, UInt32* d)
{
#ifdef USE_ASM
#ifdef _MSC_VER
UInt32 a2, b2, c2, d2;
__asm xor EBX, EBX;
__asm xor ECX, ECX;
__asm xor EDX, EDX;
__asm mov EAX, function;
__asm cpuid;
__asm mov a2, EAX;
__asm mov b2, EBX;
__asm mov c2, ECX;
__asm mov d2, EDX;
*a = a2;
*b = b2;
*c = c2;
*d = d2;
#else
__asm__ __volatile__(
"cpuid"
: "=a"(*a),
"=b"(*b),
"=c"(*c),
"=d"(*d)
: "0"(function));
#endif
#else
int CPUInfo[4];
__cpuid(CPUInfo, function);
*a = CPUInfo[0];
*b = CPUInfo[1];
*c = CPUInfo[2];
*d = CPUInfo[3];
#endif
}
Bool x86cpuid_CheckAndRead(Cx86cpuid* p)
{
CHECK_CPUID_IS_SUPPORTED
MyCPUID(0, &p->maxFunc, &p->vendor[0], &p->vendor[2], &p->vendor[1]);
MyCPUID(1, &p->ver, &p->b, &p->c, &p->d);
return True;
}
static UInt32 kVendors[][3] = {
{ 0x756E6547, 0x49656E69, 0x6C65746E },
{ 0x68747541, 0x69746E65, 0x444D4163 },
{ 0x746E6543, 0x48727561, 0x736C7561 }
};
int x86cpuid_GetFirm(const Cx86cpuid* p)
{
unsigned i;
for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++) {
const UInt32* v = kVendors[i];
if (v[0] == p->vendor[0] && v[1] == p->vendor[1] && v[2] == p->vendor[2])
return (int)i;
}
return -1;
}
Bool CPU_Is_InOrder()
{
Cx86cpuid p;
int firm;
UInt32 family, model;
if (!x86cpuid_CheckAndRead(&p))
return True;
family = x86cpuid_GetFamily(&p);
model = x86cpuid_GetModel(&p);
firm = x86cpuid_GetFirm(&p);
switch (firm) {
case CPU_FIRM_INTEL:
return (family < 6 || (family == 6 && model == 0x100C));
case CPU_FIRM_AMD:
return (family < 5 || (family == 5 && (model < 6 || model == 0xA)));
case CPU_FIRM_VIA:
return (family < 6 || (family == 6 && model < 0xF));
}
return True;
}
#if !defined(MY_CPU_AMD64) && defined(_WIN32)
static Bool CPU_Sys_Is_SSE_Supported()
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (!GetVersionEx(&vi))
return False;
return (vi.dwMajorVersion >= 5);
}
#define CHECK_SYS_SSE_SUPPORT \
if (!CPU_Sys_Is_SSE_Supported()) \
return False;
#else
#define CHECK_SYS_SSE_SUPPORT
#endif
Bool CPU_Is_Aes_Supported()
{
Cx86cpuid p;
CHECK_SYS_SSE_SUPPORT
if (!x86cpuid_CheckAndRead(&p))
return False;
return (p.c >> 25) & 1;
}
#endif

156
fex/7z_C/CpuArch.h Normal file
View File

@ -0,0 +1,156 @@
/* CpuArch.h -- CPU specific code
2010-12-01: Igor Pavlov : Public domain */
#ifndef __CPU_ARCH_H
#define __CPU_ARCH_H
#include "Types.h"
EXTERN_C_BEGIN
/*
MY_CPU_LE means that CPU is LITTLE ENDIAN.
If MY_CPU_LE is not defined, we don't know about that property of platform (it can be LITTLE ENDIAN).
MY_CPU_LE_UNALIGN means that CPU is LITTLE ENDIAN and CPU supports unaligned memory accesses.
If MY_CPU_LE_UNALIGN is not defined, we don't know about these properties of platform.
*/
#if defined(_M_X64) || defined(_M_AMD64) || defined(__x86_64__)
#define MY_CPU_AMD64
#endif
#if defined(MY_CPU_AMD64) || defined(_M_IA64)
#define MY_CPU_64BIT
#endif
#if defined(_M_IX86) || defined(__i386__)
#define MY_CPU_X86
#endif
#if defined(MY_CPU_X86) || defined(MY_CPU_AMD64)
#define MY_CPU_X86_OR_AMD64
#endif
#if defined(MY_CPU_X86) || defined(_M_ARM)
#define MY_CPU_32BIT
#endif
#if defined(_WIN32) && defined(_M_ARM)
#define MY_CPU_ARM_LE
#endif
#if defined(_WIN32) && defined(_M_IA64)
#define MY_CPU_IA64_LE
#endif
#if defined(MY_CPU_X86_OR_AMD64)
#define MY_CPU_LE_UNALIGN
#endif
#if defined(MY_CPU_X86_OR_AMD64) || defined(MY_CPU_ARM_LE) || defined(MY_CPU_IA64_LE) || defined(__ARMEL__) || defined(__MIPSEL__) || defined(__LITTLE_ENDIAN__)
#define MY_CPU_LE
#endif
#if defined(__BIG_ENDIAN__) || defined(__m68k__) || defined(__ARMEB__) || defined(__MIPSEB__)
#define MY_CPU_BE
#endif
#if defined(MY_CPU_LE) && defined(MY_CPU_BE)
Stop_Compiling_Bad_Endian
#endif
#ifdef MY_CPU_LE_UNALIGN
#define GetUi16(p) (*(const UInt16*)(p))
#define GetUi32(p) (*(const UInt32*)(p))
#define GetUi64(p) (*(const UInt64*)(p))
#define SetUi16(p, d) *(UInt16*)(p) = (d);
#define SetUi32(p, d) *(UInt32*)(p) = (d);
#define SetUi64(p, d) *(UInt64*)(p) = (d);
#else
#define GetUi16(p) (((const Byte*)(p))[0] | ((UInt16)((const Byte*)(p))[1] << 8))
#define GetUi32(p) ( \
((const Byte*)(p))[0] | ((UInt32)((const Byte*)(p))[1] << 8) | ((UInt32)((const Byte*)(p))[2] << 16) | ((UInt32)((const Byte*)(p))[3] << 24))
#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte*)(p)) + 4) << 32))
#define SetUi16(p, d) \
{ \
UInt32 _x_ = (d); \
((Byte*)(p))[0] = (Byte)_x_; \
((Byte*)(p))[1] = (Byte)(_x_ >> 8); \
}
#define SetUi32(p, d) \
{ \
UInt32 _x_ = (d); \
((Byte*)(p))[0] = (Byte)_x_; \
((Byte*)(p))[1] = (Byte)(_x_ >> 8); \
((Byte*)(p))[2] = (Byte)(_x_ >> 16); \
((Byte*)(p))[3] = (Byte)(_x_ >> 24); \
}
#define SetUi64(p, d) \
{ \
UInt64 _x64_ = (d); \
SetUi32(p, (UInt32)_x64_); \
SetUi32(((Byte*)(p)) + 4, (UInt32)(_x64_ >> 32)); \
}
#endif
#if defined(MY_CPU_LE_UNALIGN) && defined(_WIN64) && (_MSC_VER >= 1300)
#pragma intrinsic(_byteswap_ulong)
#pragma intrinsic(_byteswap_uint64)
#define GetBe32(p) _byteswap_ulong(*(const UInt32*)(const Byte*)(p))
#define GetBe64(p) _byteswap_uint64(*(const UInt64*)(const Byte*)(p))
#else
#define GetBe32(p) ( \
((UInt32)((const Byte*)(p))[0] << 24) | ((UInt32)((const Byte*)(p))[1] << 16) | ((UInt32)((const Byte*)(p))[2] << 8) | ((const Byte*)(p))[3])
#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte*)(p)) + 4))
#endif
#define GetBe16(p) (((UInt16)((const Byte*)(p))[0] << 8) | ((const Byte*)(p))[1])
#ifdef MY_CPU_X86_OR_AMD64
typedef struct
{
UInt32 maxFunc;
UInt32 vendor[3];
UInt32 ver;
UInt32 b;
UInt32 c;
UInt32 d;
} Cx86cpuid;
enum {
CPU_FIRM_INTEL,
CPU_FIRM_AMD,
CPU_FIRM_VIA
};
Bool x86cpuid_CheckAndRead(Cx86cpuid* p);
int x86cpuid_GetFirm(const Cx86cpuid* p);
#define x86cpuid_GetFamily(p) (((p)->ver >> 8) & 0xFF00F)
#define x86cpuid_GetModel(p) (((p)->ver >> 4) & 0xF00F)
#define x86cpuid_GetStepping(p) ((p)->ver & 0xF)
Bool CPU_Is_InOrder();
Bool CPU_Is_Aes_Supported();
#endif
EXTERN_C_END
#endif

327
fex/7z_C/Lzma2Dec.c Normal file
View File

@ -0,0 +1,327 @@
/* Lzma2Dec.c -- LZMA2 Decoder
2010-12-15 : Igor Pavlov : Public domain */
/* #define SHOW_DEBUG_INFO */
#ifdef SHOW_DEBUG_INFO
#include <stdio.h>
#endif
#include <string.h>
#include "Lzma2Dec.h"
/*
00000000 - EOS
00000001 U U - Uncompressed Reset Dic
00000010 U U - Uncompressed No Reset
100uuuuu U U P P - LZMA no reset
101uuuuu U U P P - LZMA reset state
110uuuuu U U P P S - LZMA reset state + new prop
111uuuuu U U P P S - LZMA reset state + new prop + reset dic
u, U - Unpack Size
P - Pack Size
S - Props
*/
#define LZMA2_CONTROL_LZMA (1 << 7)
#define LZMA2_CONTROL_COPY_NO_RESET 2
#define LZMA2_CONTROL_COPY_RESET_DIC 1
#define LZMA2_CONTROL_EOF 0
#define LZMA2_IS_UNCOMPRESSED_STATE(p) (((p)->control & LZMA2_CONTROL_LZMA) == 0)
#define LZMA2_GET_LZMA_MODE(p) (((p)->control >> 5) & 3)
#define LZMA2_IS_THERE_PROP(mode) ((mode) >= 2)
#define LZMA2_LCLP_MAX 4
#define LZMA2_DIC_SIZE_FROM_PROP(p) (((UInt32)2 | ((p)&1)) << ((p) / 2 + 11))
#ifdef SHOW_DEBUG_INFO
#define PRF(x) x
#else
#define PRF(x)
#endif
typedef enum {
LZMA2_STATE_CONTROL,
LZMA2_STATE_UNPACK0,
LZMA2_STATE_UNPACK1,
LZMA2_STATE_PACK0,
LZMA2_STATE_PACK1,
LZMA2_STATE_PROP,
LZMA2_STATE_DATA,
LZMA2_STATE_DATA_CONT,
LZMA2_STATE_FINISHED,
LZMA2_STATE_ERROR
} ELzma2State;
static SRes Lzma2Dec_GetOldProps(Byte prop, Byte* props)
{
UInt32 dicSize;
if (prop > 40)
return SZ_ERROR_UNSUPPORTED;
dicSize = (prop == 40) ? 0xFFFFFFFF : LZMA2_DIC_SIZE_FROM_PROP(prop);
props[0] = (Byte)LZMA2_LCLP_MAX;
props[1] = (Byte)(dicSize);
props[2] = (Byte)(dicSize >> 8);
props[3] = (Byte)(dicSize >> 16);
props[4] = (Byte)(dicSize >> 24);
return SZ_OK;
}
SRes Lzma2Dec_AllocateProbs(CLzma2Dec* p, Byte prop, ISzAlloc* alloc)
{
Byte props[LZMA_PROPS_SIZE];
RINOK(Lzma2Dec_GetOldProps(prop, props));
return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
}
SRes Lzma2Dec_Allocate(CLzma2Dec* p, Byte prop, ISzAlloc* alloc)
{
Byte props[LZMA_PROPS_SIZE];
RINOK(Lzma2Dec_GetOldProps(prop, props));
return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
}
void Lzma2Dec_Init(CLzma2Dec* p)
{
p->state = LZMA2_STATE_CONTROL;
p->needInitDic = True;
p->needInitState = True;
p->needInitProp = True;
LzmaDec_Init(&p->decoder);
}
static ELzma2State Lzma2Dec_UpdateState(CLzma2Dec* p, Byte b)
{
switch (p->state) {
case LZMA2_STATE_CONTROL:
p->control = b;
PRF(printf("\n %4X ", p->decoder.dicPos));
PRF(printf(" %2X", b));
if (p->control == 0)
return LZMA2_STATE_FINISHED;
if (LZMA2_IS_UNCOMPRESSED_STATE(p)) {
if ((p->control & 0x7F) > 2)
return LZMA2_STATE_ERROR;
p->unpackSize = 0;
} else
p->unpackSize = (UInt32)(p->control & 0x1F) << 16;
return LZMA2_STATE_UNPACK0;
case LZMA2_STATE_UNPACK0:
p->unpackSize |= (UInt32)b << 8;
return LZMA2_STATE_UNPACK1;
case LZMA2_STATE_UNPACK1:
p->unpackSize |= (UInt32)b;
p->unpackSize++;
PRF(printf(" %8d", p->unpackSize));
return (LZMA2_IS_UNCOMPRESSED_STATE(p)) ? LZMA2_STATE_DATA : LZMA2_STATE_PACK0;
case LZMA2_STATE_PACK0:
p->packSize = (UInt32)b << 8;
return LZMA2_STATE_PACK1;
case LZMA2_STATE_PACK1:
p->packSize |= (UInt32)b;
p->packSize++;
PRF(printf(" %8d", p->packSize));
return LZMA2_IS_THERE_PROP(LZMA2_GET_LZMA_MODE(p)) ? LZMA2_STATE_PROP : (p->needInitProp ? LZMA2_STATE_ERROR : LZMA2_STATE_DATA);
case LZMA2_STATE_PROP: {
int lc, lp;
if (b >= (9 * 5 * 5))
return LZMA2_STATE_ERROR;
lc = b % 9;
b /= 9;
p->decoder.prop.pb = b / 5;
lp = b % 5;
if (lc + lp > LZMA2_LCLP_MAX)
return LZMA2_STATE_ERROR;
p->decoder.prop.lc = lc;
p->decoder.prop.lp = lp;
p->needInitProp = False;
return LZMA2_STATE_DATA;
}
}
return LZMA2_STATE_ERROR;
}
static void LzmaDec_UpdateWithUncompressed(CLzmaDec* p, const Byte* src, SizeT size)
{
memcpy(p->dic + p->dicPos, src, size);
p->dicPos += size;
if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= size)
p->checkDicSize = p->prop.dicSize;
p->processedPos += (UInt32)size;
}
void LzmaDec_InitDicAndState(CLzmaDec* p, Bool initDic, Bool initState);
SRes Lzma2Dec_DecodeToDic(CLzma2Dec* p, SizeT dicLimit,
const Byte* src, SizeT* srcLen, ELzmaFinishMode finishMode, ELzmaStatus* status)
{
SizeT inSize = *srcLen;
*srcLen = 0;
*status = LZMA_STATUS_NOT_SPECIFIED;
while (p->state != LZMA2_STATE_FINISHED) {
SizeT dicPos = p->decoder.dicPos;
if (p->state == LZMA2_STATE_ERROR)
return SZ_ERROR_DATA;
if (dicPos == dicLimit && finishMode == LZMA_FINISH_ANY) {
*status = LZMA_STATUS_NOT_FINISHED;
return SZ_OK;
}
if (p->state != LZMA2_STATE_DATA && p->state != LZMA2_STATE_DATA_CONT) {
if (*srcLen == inSize) {
*status = LZMA_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
(*srcLen)++;
p->state = Lzma2Dec_UpdateState(p, *src++);
continue;
}
{
SizeT destSizeCur = dicLimit - dicPos;
SizeT srcSizeCur = inSize - *srcLen;
ELzmaFinishMode curFinishMode = LZMA_FINISH_ANY;
if (p->unpackSize <= destSizeCur) {
destSizeCur = (SizeT)p->unpackSize;
curFinishMode = LZMA_FINISH_END;
}
if (LZMA2_IS_UNCOMPRESSED_STATE(p)) {
if (*srcLen == inSize) {
*status = LZMA_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
if (p->state == LZMA2_STATE_DATA) {
Bool initDic = (p->control == LZMA2_CONTROL_COPY_RESET_DIC);
if (initDic)
p->needInitProp = p->needInitState = True;
else if (p->needInitDic)
return SZ_ERROR_DATA;
p->needInitDic = False;
LzmaDec_InitDicAndState(&p->decoder, initDic, False);
}
if (srcSizeCur > destSizeCur)
srcSizeCur = destSizeCur;
if (srcSizeCur == 0)
return SZ_ERROR_DATA;
LzmaDec_UpdateWithUncompressed(&p->decoder, src, srcSizeCur);
src += srcSizeCur;
*srcLen += srcSizeCur;
p->unpackSize -= (UInt32)srcSizeCur;
p->state = (p->unpackSize == 0) ? LZMA2_STATE_CONTROL : LZMA2_STATE_DATA_CONT;
} else {
SizeT outSizeProcessed;
SRes res;
if (p->state == LZMA2_STATE_DATA) {
int mode = LZMA2_GET_LZMA_MODE(p);
Bool initDic = (mode == 3);
Bool initState = (mode > 0);
if ((!initDic && p->needInitDic) || (!initState && p->needInitState))
return SZ_ERROR_DATA;
LzmaDec_InitDicAndState(&p->decoder, initDic, initState);
p->needInitDic = False;
p->needInitState = False;
p->state = LZMA2_STATE_DATA_CONT;
}
if (srcSizeCur > p->packSize)
srcSizeCur = (SizeT)p->packSize;
res = LzmaDec_DecodeToDic(&p->decoder, dicPos + destSizeCur, src, &srcSizeCur, curFinishMode, status);
src += srcSizeCur;
*srcLen += srcSizeCur;
p->packSize -= (UInt32)srcSizeCur;
outSizeProcessed = p->decoder.dicPos - dicPos;
p->unpackSize -= (UInt32)outSizeProcessed;
RINOK(res);
if (*status == LZMA_STATUS_NEEDS_MORE_INPUT)
return res;
if (srcSizeCur == 0 && outSizeProcessed == 0) {
if (*status != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK || p->unpackSize != 0 || p->packSize != 0)
return SZ_ERROR_DATA;
p->state = LZMA2_STATE_CONTROL;
}
if (*status == LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK)
*status = LZMA_STATUS_NOT_FINISHED;
}
}
}
*status = LZMA_STATUS_FINISHED_WITH_MARK;
return SZ_OK;
}
SRes Lzma2Dec_DecodeToBuf(CLzma2Dec* p, Byte* dest, SizeT* destLen, const Byte* src, SizeT* srcLen, ELzmaFinishMode finishMode, ELzmaStatus* status)
{
SizeT outSize = *destLen, inSize = *srcLen;
*srcLen = *destLen = 0;
for (;;) {
SizeT srcSizeCur = inSize, outSizeCur, dicPos;
ELzmaFinishMode curFinishMode;
SRes res;
if (p->decoder.dicPos == p->decoder.dicBufSize)
p->decoder.dicPos = 0;
dicPos = p->decoder.dicPos;
if (outSize > p->decoder.dicBufSize - dicPos) {
outSizeCur = p->decoder.dicBufSize;
curFinishMode = LZMA_FINISH_ANY;
} else {
outSizeCur = dicPos + outSize;
curFinishMode = finishMode;
}
res = Lzma2Dec_DecodeToDic(p, outSizeCur, src, &srcSizeCur, curFinishMode, status);
src += srcSizeCur;
inSize -= srcSizeCur;
*srcLen += srcSizeCur;
outSizeCur = p->decoder.dicPos - dicPos;
memcpy(dest, p->decoder.dic + dicPos, outSizeCur);
dest += outSizeCur;
outSize -= outSizeCur;
*destLen += outSizeCur;
if (res != 0)
return res;
if (outSizeCur == 0 || outSize == 0)
return SZ_OK;
}
}
SRes Lzma2Decode(Byte* dest, SizeT* destLen, const Byte* src, SizeT* srcLen,
Byte prop, ELzmaFinishMode finishMode, ELzmaStatus* status, ISzAlloc* alloc)
{
CLzma2Dec p;
SRes res;
SizeT outSize = *destLen, inSize = *srcLen;
*destLen = *srcLen = 0;
*status = LZMA_STATUS_NOT_SPECIFIED;
Lzma2Dec_Construct(&p);
RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc));
p.decoder.dic = dest;
p.decoder.dicBufSize = outSize;
Lzma2Dec_Init(&p);
*srcLen = inSize;
res = Lzma2Dec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
*destLen = p.decoder.dicPos;
if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
res = SZ_ERROR_INPUT_EOF;
Lzma2Dec_FreeProbs(&p, alloc);
return res;
}

82
fex/7z_C/Lzma2Dec.h Normal file
View File

@ -0,0 +1,82 @@
/* Lzma2Dec.h -- LZMA2 Decoder
2009-05-03 : Igor Pavlov : Public domain */
#ifndef __LZMA2_DEC_H
#define __LZMA2_DEC_H
#include "LzmaDec.h"
#ifdef __cplusplus
extern "C" {
#endif
/* ---------- State Interface ---------- */
typedef struct
{
CLzmaDec decoder;
UInt32 packSize;
UInt32 unpackSize;
int state;
Byte control;
Bool needInitDic;
Bool needInitState;
Bool needInitProp;
} CLzma2Dec;
#define Lzma2Dec_Construct(p) LzmaDec_Construct(&(p)->decoder)
#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc);
#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc);
SRes Lzma2Dec_AllocateProbs(CLzma2Dec* p, Byte prop, ISzAlloc* alloc);
SRes Lzma2Dec_Allocate(CLzma2Dec* p, Byte prop, ISzAlloc* alloc);
void Lzma2Dec_Init(CLzma2Dec* p);
/*
finishMode:
It has meaning only if the decoding reaches output limit (*destLen or dicLimit).
LZMA_FINISH_ANY - use smallest number of input bytes
LZMA_FINISH_END - read EndOfStream marker after decoding
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_NEEDS_MORE_INPUT
SZ_ERROR_DATA - Data error
*/
SRes Lzma2Dec_DecodeToDic(CLzma2Dec* p, SizeT dicLimit,
const Byte* src, SizeT* srcLen, ELzmaFinishMode finishMode, ELzmaStatus* status);
SRes Lzma2Dec_DecodeToBuf(CLzma2Dec* p, Byte* dest, SizeT* destLen,
const Byte* src, SizeT* srcLen, ELzmaFinishMode finishMode, ELzmaStatus* status);
/* ---------- One Call Interface ---------- */
/*
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - use smallest number of input bytes
LZMA_FINISH_END - read EndOfStream marker after decoding
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
SZ_ERROR_DATA - Data error
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
*/
SRes Lzma2Decode(Byte* dest, SizeT* destLen, const Byte* src, SizeT* srcLen,
Byte prop, ELzmaFinishMode finishMode, ELzmaStatus* status, ISzAlloc* alloc);
#ifdef __cplusplus
}
#endif
#endif

980
fex/7z_C/LzmaDec.c Normal file
View File

@ -0,0 +1,980 @@
/* LzmaDec.c -- LZMA Decoder
2010-12-15 : Igor Pavlov : Public domain */
#include "LzmaDec.h"
#include <string.h>
#define kNumTopBits 24
#define kTopValue ((UInt32)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
#define RC_INIT_SIZE 5
#define NORMALIZE \
if (range < kTopValue) { \
range <<= 8; \
code = (code << 8) | (*buf++); \
}
#define IF_BIT_0(p) \
ttt = *(p); \
NORMALIZE; \
bound = (range >> kNumBitModelTotalBits) * ttt; \
if (code < bound)
#define UPDATE_0(p) \
range = bound; \
*(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
#define UPDATE_1(p) \
range -= bound; \
code -= bound; \
*(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
#define GET_BIT2(p, i, A0, A1) \
IF_BIT_0(p) \
{ \
UPDATE_0(p); \
i = (i + i); \
A0; \
} \
else \
{ \
UPDATE_1(p); \
i = (i + i) + 1; \
A1; \
}
#define GET_BIT(p, i) GET_BIT2(p, i, ;, ;)
#define TREE_GET_BIT(probs, i) \
{ \
GET_BIT((probs + i), i); \
}
#define TREE_DECODE(probs, limit, i) \
{ \
i = 1; \
do { \
TREE_GET_BIT(probs, i); \
} while (i < limit); \
i -= limit; \
}
/* #define _LZMA_SIZE_OPT */
#ifdef _LZMA_SIZE_OPT
#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
#else
#define TREE_6_DECODE(probs, i) \
{ \
i = 1; \
TREE_GET_BIT(probs, i); \
TREE_GET_BIT(probs, i); \
TREE_GET_BIT(probs, i); \
TREE_GET_BIT(probs, i); \
TREE_GET_BIT(probs, i); \
TREE_GET_BIT(probs, i); \
i -= 0x40; \
}
#endif
#define NORMALIZE_CHECK \
if (range < kTopValue) { \
if (buf >= bufLimit) \
return DUMMY_ERROR; \
range <<= 8; \
code = (code << 8) | (*buf++); \
}
#define IF_BIT_0_CHECK(p) \
ttt = *(p); \
NORMALIZE_CHECK; \
bound = (range >> kNumBitModelTotalBits) * ttt; \
if (code < bound)
#define UPDATE_0_CHECK range = bound;
#define UPDATE_1_CHECK \
range -= bound; \
code -= bound;
#define GET_BIT2_CHECK(p, i, A0, A1) \
IF_BIT_0_CHECK(p) \
{ \
UPDATE_0_CHECK; \
i = (i + i); \
A0; \
} \
else \
{ \
UPDATE_1_CHECK; \
i = (i + i) + 1; \
A1; \
}
#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ;, ;)
#define TREE_DECODE_CHECK(probs, limit, i) \
{ \
i = 1; \
do { \
GET_BIT_CHECK(probs + i, i) \
} while (i < limit); \
i -= limit; \
}
#define kNumPosBitsMax 4
#define kNumPosStatesMax (1 << kNumPosBitsMax)
#define kLenNumLowBits 3
#define kLenNumLowSymbols (1 << kLenNumLowBits)
#define kLenNumMidBits 3
#define kLenNumMidSymbols (1 << kLenNumMidBits)
#define kLenNumHighBits 8
#define kLenNumHighSymbols (1 << kLenNumHighBits)
#define LenChoice 0
#define LenChoice2 (LenChoice + 1)
#define LenLow (LenChoice2 + 1)
#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
#define kNumStates 12
#define kNumLitStates 7
#define kStartPosModelIndex 4
#define kEndPosModelIndex 14
#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
#define kNumPosSlotBits 6
#define kNumLenToPosStates 4
#define kNumAlignBits 4
#define kAlignTableSize (1 << kNumAlignBits)
#define kMatchMinLen 2
#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
#define IsMatch 0
#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
#define IsRepG0 (IsRep + kNumStates)
#define IsRepG1 (IsRepG0 + kNumStates)
#define IsRepG2 (IsRepG1 + kNumStates)
#define IsRep0Long (IsRepG2 + kNumStates)
#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
#define LenCoder (Align + kAlignTableSize)
#define RepLenCoder (LenCoder + kNumLenProbs)
#define Literal (RepLenCoder + kNumLenProbs)
#define LZMA_BASE_SIZE 1846
#define LZMA_LIT_SIZE 768
#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp)))
#if Literal != LZMA_BASE_SIZE
StopCompilingDueBUG
#endif
#define LZMA_DIC_MIN (1 << 12)
/* First LZMA-symbol is always decoded.
And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization
Out:
Result:
SZ_OK - OK
SZ_ERROR_DATA - Error
p->remainLen:
< kMatchSpecLenStart : normal remain
= kMatchSpecLenStart : finished
= kMatchSpecLenStart + 1 : Flush marker
= kMatchSpecLenStart + 2 : State Init Marker
*/
static int MY_FAST_CALL
LzmaDec_DecodeReal(CLzmaDec* p, SizeT limit, const Byte* bufLimit)
{
CLzmaProb* probs = p->probs;
unsigned state = p->state;
UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3];
unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1;
unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1;
unsigned lc = p->prop.lc;
Byte* dic = p->dic;
SizeT dicBufSize = p->dicBufSize;
SizeT dicPos = p->dicPos;
UInt32 processedPos = p->processedPos;
UInt32 checkDicSize = p->checkDicSize;
unsigned len = 0;
const Byte* buf = p->buf;
UInt32 range = p->range;
UInt32 code = p->code;
do {
CLzmaProb* prob;
UInt32 bound;
unsigned ttt;
unsigned posState = processedPos & pbMask;
prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
IF_BIT_0(prob)
{
unsigned symbol;
UPDATE_0(prob);
prob = probs + Literal;
if (checkDicSize != 0 || processedPos != 0)
prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) + (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc))));
if (state < kNumLitStates) {
state -= (state < 4) ? state : 3;
symbol = 1;
do {
GET_BIT(prob + symbol, symbol)
} while (symbol < 0x100);
} else {
unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
unsigned offs = 0x100;
state -= (state < 10) ? 3 : 6;
symbol = 1;
do {
unsigned bit;
CLzmaProb* probLit;
matchByte <<= 1;
bit = (matchByte & offs);
probLit = prob + offs + bit + symbol;
GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit)
} while (symbol < 0x100);
}
dic[dicPos++] = (Byte)symbol;
processedPos++;
continue;
}
else
{
UPDATE_1(prob);
prob = probs + IsRep + state;
IF_BIT_0(prob)
{
UPDATE_0(prob);
state += kNumStates;
prob = probs + LenCoder;
}
else
{
UPDATE_1(prob);
if (checkDicSize == 0 && processedPos == 0)
return SZ_ERROR_DATA;
prob = probs + IsRepG0 + state;
IF_BIT_0(prob)
{
UPDATE_0(prob);
prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
IF_BIT_0(prob)
{
UPDATE_0(prob);
dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
dicPos++;
processedPos++;
state = state < kNumLitStates ? 9 : 11;
continue;
}
UPDATE_1(prob);
}
else
{
UInt32 distance;
UPDATE_1(prob);
prob = probs + IsRepG1 + state;
IF_BIT_0(prob)
{
UPDATE_0(prob);
distance = rep1;
}
else
{
UPDATE_1(prob);
prob = probs + IsRepG2 + state;
IF_BIT_0(prob)
{
UPDATE_0(prob);
distance = rep2;
}
else
{
UPDATE_1(prob);
distance = rep3;
rep3 = rep2;
}
rep2 = rep1;
}
rep1 = rep0;
rep0 = distance;
}
state = state < kNumLitStates ? 8 : 11;
prob = probs + RepLenCoder;
}
{
unsigned limit, offset;
CLzmaProb* probLen = prob + LenChoice;
IF_BIT_0(probLen)
{
UPDATE_0(probLen);
probLen = prob + LenLow + (posState << kLenNumLowBits);
offset = 0;
limit = (1 << kLenNumLowBits);
}
else
{
UPDATE_1(probLen);
probLen = prob + LenChoice2;
IF_BIT_0(probLen)
{
UPDATE_0(probLen);
probLen = prob + LenMid + (posState << kLenNumMidBits);
offset = kLenNumLowSymbols;
limit = (1 << kLenNumMidBits);
}
else
{
UPDATE_1(probLen);
probLen = prob + LenHigh;
offset = kLenNumLowSymbols + kLenNumMidSymbols;
limit = (1 << kLenNumHighBits);
}
}
TREE_DECODE(probLen, limit, len);
len += offset;
}
if (state >= kNumStates) {
UInt32 distance;
prob = probs + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
TREE_6_DECODE(prob, distance);
if (distance >= kStartPosModelIndex) {
unsigned posSlot = (unsigned)distance;
int numDirectBits = (int)(((distance >> 1) - 1));
distance = (2 | (distance & 1));
if (posSlot < kEndPosModelIndex) {
distance <<= numDirectBits;
prob = probs + SpecPos + distance - posSlot - 1;
{
UInt32 mask = 1;
unsigned i = 1;
do {
GET_BIT2(prob + i, i, ;, distance |= mask);
mask <<= 1;
} while (--numDirectBits != 0);
}
} else {
numDirectBits -= kNumAlignBits;
do {
NORMALIZE
range >>= 1;
{
UInt32 t;
code -= range;
t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */
distance = (distance << 1) + (t + 1);
code += range & t;
}
/*
distance <<= 1;
if (code >= range)
{
code -= range;
distance |= 1;
}
*/
} while (--numDirectBits != 0);
prob = probs + Align;
distance <<= kNumAlignBits;
{
unsigned i = 1;
GET_BIT2(prob + i, i, ;, distance |= 1);
GET_BIT2(prob + i, i, ;, distance |= 2);
GET_BIT2(prob + i, i, ;, distance |= 4);
GET_BIT2(prob + i, i, ;, distance |= 8);
}
if (distance == (UInt32)0xFFFFFFFF) {
len += kMatchSpecLenStart;
state -= kNumStates;
break;
}
}
}
rep3 = rep2;
rep2 = rep1;
rep1 = rep0;
rep0 = distance + 1;
if (checkDicSize == 0) {
if (distance >= processedPos)
return SZ_ERROR_DATA;
} else if (distance >= checkDicSize)
return SZ_ERROR_DATA;
state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3;
}
len += kMatchMinLen;
if (limit == dicPos)
return SZ_ERROR_DATA;
{
SizeT rem = limit - dicPos;
unsigned curLen = ((rem < len) ? (unsigned)rem : len);
SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0);
processedPos += curLen;
len -= curLen;
if (pos + curLen <= dicBufSize) {
Byte* dest = dic + dicPos;
ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos;
const Byte* lim = dest + curLen;
dicPos += curLen;
do
*(dest) = (Byte) * (dest + src);
while (++dest != lim);
} else {
do {
dic[dicPos++] = dic[pos];
if (++pos == dicBufSize)
pos = 0;
} while (--curLen != 0);
}
}
}
} while (dicPos < limit && buf < bufLimit);
NORMALIZE;
p->buf = buf;
p->range = range;
p->code = code;
p->remainLen = len;
p->dicPos = dicPos;
p->processedPos = processedPos;
p->reps[0] = rep0;
p->reps[1] = rep1;
p->reps[2] = rep2;
p->reps[3] = rep3;
p->state = state;
return SZ_OK;
}
static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec* p, SizeT limit)
{
if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart) {
Byte* dic = p->dic;
SizeT dicPos = p->dicPos;
SizeT dicBufSize = p->dicBufSize;
unsigned len = p->remainLen;
UInt32 rep0 = p->reps[0];
if (limit - dicPos < len)
len = (unsigned)(limit - dicPos);
if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len)
p->checkDicSize = p->prop.dicSize;
p->processedPos += len;
p->remainLen -= len;
while (len != 0) {
len--;
dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
dicPos++;
}
p->dicPos = dicPos;
}
}
static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec* p, SizeT limit, const Byte* bufLimit)
{
do {
SizeT limit2 = limit;
if (p->checkDicSize == 0) {
UInt32 rem = p->prop.dicSize - p->processedPos;
if (limit - p->dicPos > rem)
limit2 = p->dicPos + rem;
}
RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit));
if (p->processedPos >= p->prop.dicSize)
p->checkDicSize = p->prop.dicSize;
LzmaDec_WriteRem(p, limit);
} while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart);
if (p->remainLen > kMatchSpecLenStart) {
p->remainLen = kMatchSpecLenStart;
}
return 0;
}
typedef enum {
DUMMY_ERROR, /* unexpected end of input stream */
DUMMY_LIT,
DUMMY_MATCH,
DUMMY_REP
} ELzmaDummy;
static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec* p, const Byte* buf, SizeT inSize)
{
UInt32 range = p->range;
UInt32 code = p->code;
const Byte* bufLimit = buf + inSize;
CLzmaProb* probs = p->probs;
unsigned state = p->state;
ELzmaDummy res;
{
CLzmaProb* prob;
UInt32 bound;
unsigned ttt;
unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1);
prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
IF_BIT_0_CHECK(prob)
{
UPDATE_0_CHECK
/* if (bufLimit - buf >= 7) return DUMMY_LIT; */
prob = probs + Literal;
if (p->checkDicSize != 0 || p->processedPos != 0)
prob += (LZMA_LIT_SIZE * ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) + (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc))));
if (state < kNumLitStates) {
unsigned symbol = 1;
do {
GET_BIT_CHECK(prob + symbol, symbol)
} while (symbol < 0x100);
} else {
unsigned matchByte = p->dic[p->dicPos - p->reps[0] + ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)];
unsigned offs = 0x100;
unsigned symbol = 1;
do {
unsigned bit;
CLzmaProb* probLit;
matchByte <<= 1;
bit = (matchByte & offs);
probLit = prob + offs + bit + symbol;
GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit)
} while (symbol < 0x100);
}
res = DUMMY_LIT;
}
else
{
unsigned len;
UPDATE_1_CHECK;
prob = probs + IsRep + state;
IF_BIT_0_CHECK(prob)
{
UPDATE_0_CHECK;
state = 0;
prob = probs + LenCoder;
res = DUMMY_MATCH;
}
else
{
UPDATE_1_CHECK;
res = DUMMY_REP;
prob = probs + IsRepG0 + state;
IF_BIT_0_CHECK(prob)
{
UPDATE_0_CHECK;
prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
IF_BIT_0_CHECK(prob)
{
UPDATE_0_CHECK;
NORMALIZE_CHECK;
return DUMMY_REP;
}
else
{
UPDATE_1_CHECK;
}
}
else
{
UPDATE_1_CHECK;
prob = probs + IsRepG1 + state;
IF_BIT_0_CHECK(prob)
{
UPDATE_0_CHECK;
}
else
{
UPDATE_1_CHECK;
prob = probs + IsRepG2 + state;
IF_BIT_0_CHECK(prob)
{
UPDATE_0_CHECK;
}
else
{
UPDATE_1_CHECK;
}
}
}
state = kNumStates;
prob = probs + RepLenCoder;
}
{
unsigned limit, offset;
CLzmaProb* probLen = prob + LenChoice;
IF_BIT_0_CHECK(probLen)
{
UPDATE_0_CHECK;
probLen = prob + LenLow + (posState << kLenNumLowBits);
offset = 0;
limit = 1 << kLenNumLowBits;
}
else
{
UPDATE_1_CHECK;
probLen = prob + LenChoice2;
IF_BIT_0_CHECK(probLen)
{
UPDATE_0_CHECK;
probLen = prob + LenMid + (posState << kLenNumMidBits);
offset = kLenNumLowSymbols;
limit = 1 << kLenNumMidBits;
}
else
{
UPDATE_1_CHECK;
probLen = prob + LenHigh;
offset = kLenNumLowSymbols + kLenNumMidSymbols;
limit = 1 << kLenNumHighBits;
}
}
TREE_DECODE_CHECK(probLen, limit, len);
len += offset;
}
if (state < 4) {
unsigned posSlot;
prob = probs + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot);
if (posSlot >= kStartPosModelIndex) {
int numDirectBits = ((posSlot >> 1) - 1);
/* if (bufLimit - buf >= 8) return DUMMY_MATCH; */
if (posSlot < kEndPosModelIndex) {
prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1;
} else {
numDirectBits -= kNumAlignBits;
do {
NORMALIZE_CHECK
range >>= 1;
code -= range & (((code - range) >> 31) - 1);
/* if (code >= range) code -= range; */
} while (--numDirectBits != 0);
prob = probs + Align;
numDirectBits = kNumAlignBits;
}
{
unsigned i = 1;
do {
GET_BIT_CHECK(prob + i, i);
} while (--numDirectBits != 0);
}
}
}
}
}
NORMALIZE_CHECK;
return res;
}
static void LzmaDec_InitRc(CLzmaDec* p, const Byte* data)
{
p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]);
p->range = 0xFFFFFFFF;
p->needFlush = 0;
}
void LzmaDec_InitDicAndState(CLzmaDec* p, Bool initDic, Bool initState)
{
p->needFlush = 1;
p->remainLen = 0;
p->tempBufSize = 0;
if (initDic) {
p->processedPos = 0;
p->checkDicSize = 0;
p->needInitState = 1;
}
if (initState)
p->needInitState = 1;
}
void LzmaDec_Init(CLzmaDec* p)
{
p->dicPos = 0;
LzmaDec_InitDicAndState(p, True, True);
}
static void LzmaDec_InitStateReal(CLzmaDec* p)
{
UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp));
UInt32 i;
CLzmaProb* probs = p->probs;
for (i = 0; i < numProbs; i++)
probs[i] = kBitModelTotal >> 1;
p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1;
p->state = 0;
p->needInitState = 0;
}
SRes LzmaDec_DecodeToDic(CLzmaDec* p, SizeT dicLimit, const Byte* src, SizeT* srcLen,
ELzmaFinishMode finishMode, ELzmaStatus* status)
{
SizeT inSize = *srcLen;
(*srcLen) = 0;
LzmaDec_WriteRem(p, dicLimit);
*status = LZMA_STATUS_NOT_SPECIFIED;
while (p->remainLen != kMatchSpecLenStart) {
int checkEndMarkNow;
if (p->needFlush != 0) {
for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--)
p->tempBuf[p->tempBufSize++] = *src++;
if (p->tempBufSize < RC_INIT_SIZE) {
*status = LZMA_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
if (p->tempBuf[0] != 0)
return SZ_ERROR_DATA;
LzmaDec_InitRc(p, p->tempBuf);
p->tempBufSize = 0;
}
checkEndMarkNow = 0;
if (p->dicPos >= dicLimit) {
if (p->remainLen == 0 && p->code == 0) {
*status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK;
return SZ_OK;
}
if (finishMode == LZMA_FINISH_ANY) {
*status = LZMA_STATUS_NOT_FINISHED;
return SZ_OK;
}
if (p->remainLen != 0) {
*status = LZMA_STATUS_NOT_FINISHED;
return SZ_ERROR_DATA;
}
checkEndMarkNow = 1;
}
if (p->needInitState)
LzmaDec_InitStateReal(p);
if (p->tempBufSize == 0) {
SizeT processed;
const Byte* bufLimit;
if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) {
int dummyRes = LzmaDec_TryDummy(p, src, inSize);
if (dummyRes == DUMMY_ERROR) {
memcpy(p->tempBuf, src, inSize);
p->tempBufSize = (unsigned)inSize;
(*srcLen) += inSize;
*status = LZMA_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
if (checkEndMarkNow && dummyRes != DUMMY_MATCH) {
*status = LZMA_STATUS_NOT_FINISHED;
return SZ_ERROR_DATA;
}
bufLimit = src;
} else
bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX;
p->buf = src;
if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0)
return SZ_ERROR_DATA;
processed = (SizeT)(p->buf - src);
(*srcLen) += processed;
src += processed;
inSize -= processed;
} else {
unsigned rem = p->tempBufSize, lookAhead = 0;
while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize)
p->tempBuf[rem++] = src[lookAhead++];
p->tempBufSize = rem;
if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) {
int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem);
if (dummyRes == DUMMY_ERROR) {
(*srcLen) += lookAhead;
*status = LZMA_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
if (checkEndMarkNow && dummyRes != DUMMY_MATCH) {
*status = LZMA_STATUS_NOT_FINISHED;
return SZ_ERROR_DATA;
}
}
p->buf = p->tempBuf;
if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0)
return SZ_ERROR_DATA;
lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf));
(*srcLen) += lookAhead;
src += lookAhead;
inSize -= lookAhead;
p->tempBufSize = 0;
}
}
if (p->code == 0)
*status = LZMA_STATUS_FINISHED_WITH_MARK;
return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA;
}
SRes LzmaDec_DecodeToBuf(CLzmaDec* p, Byte* dest, SizeT* destLen, const Byte* src, SizeT* srcLen, ELzmaFinishMode finishMode, ELzmaStatus* status)
{
SizeT outSize = *destLen;
SizeT inSize = *srcLen;
*srcLen = *destLen = 0;
for (;;) {
SizeT inSizeCur = inSize, outSizeCur, dicPos;
ELzmaFinishMode curFinishMode;
SRes res;
if (p->dicPos == p->dicBufSize)
p->dicPos = 0;
dicPos = p->dicPos;
if (outSize > p->dicBufSize - dicPos) {
outSizeCur = p->dicBufSize;
curFinishMode = LZMA_FINISH_ANY;
} else {
outSizeCur = dicPos + outSize;
curFinishMode = finishMode;
}
res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status);
src += inSizeCur;
inSize -= inSizeCur;
*srcLen += inSizeCur;
outSizeCur = p->dicPos - dicPos;
memcpy(dest, p->dic + dicPos, outSizeCur);
dest += outSizeCur;
outSize -= outSizeCur;
*destLen += outSizeCur;
if (res != 0)
return res;
if (outSizeCur == 0 || outSize == 0)
return SZ_OK;
}
}
void LzmaDec_FreeProbs(CLzmaDec* p, ISzAlloc* alloc)
{
alloc->Free(alloc, p->probs);
p->probs = 0;
}
static void LzmaDec_FreeDict(CLzmaDec* p, ISzAlloc* alloc)
{
alloc->Free(alloc, p->dic);
p->dic = 0;
}
void LzmaDec_Free(CLzmaDec* p, ISzAlloc* alloc)
{
LzmaDec_FreeProbs(p, alloc);
LzmaDec_FreeDict(p, alloc);
}
SRes LzmaProps_Decode(CLzmaProps* p, const Byte* data, unsigned size)
{
UInt32 dicSize;
Byte d;
if (size < LZMA_PROPS_SIZE)
return SZ_ERROR_UNSUPPORTED;
else
dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24);
if (dicSize < LZMA_DIC_MIN)
dicSize = LZMA_DIC_MIN;
p->dicSize = dicSize;
d = data[0];
if (d >= (9 * 5 * 5))
return SZ_ERROR_UNSUPPORTED;
p->lc = d % 9;
d /= 9;
p->pb = d / 5;
p->lp = d % 5;
return SZ_OK;
}
static SRes LzmaDec_AllocateProbs2(CLzmaDec* p, const CLzmaProps* propNew, ISzAlloc* alloc)
{
UInt32 numProbs = LzmaProps_GetNumProbs(propNew);
if (p->probs == 0 || numProbs != p->numProbs) {
LzmaDec_FreeProbs(p, alloc);
p->probs = (CLzmaProb*)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb));
p->numProbs = numProbs;
if (p->probs == 0)
return SZ_ERROR_MEM;
}
return SZ_OK;
}
SRes LzmaDec_AllocateProbs(CLzmaDec* p, const Byte* props, unsigned propsSize, ISzAlloc* alloc)
{
CLzmaProps propNew;
RINOK(LzmaProps_Decode(&propNew, props, propsSize));
RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
p->prop = propNew;
return SZ_OK;
}
SRes LzmaDec_Allocate(CLzmaDec* p, const Byte* props, unsigned propsSize, ISzAlloc* alloc)
{
CLzmaProps propNew;
SizeT dicBufSize;
RINOK(LzmaProps_Decode(&propNew, props, propsSize));
RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
dicBufSize = propNew.dicSize;
if (p->dic == 0 || dicBufSize != p->dicBufSize) {
LzmaDec_FreeDict(p, alloc);
p->dic = (Byte*)alloc->Alloc(alloc, dicBufSize);
if (p->dic == 0) {
LzmaDec_FreeProbs(p, alloc);
return SZ_ERROR_MEM;
}
}
p->dicBufSize = dicBufSize;
p->prop = propNew;
return SZ_OK;
}
SRes LzmaDecode(Byte* dest, SizeT* destLen, const Byte* src, SizeT* srcLen,
const Byte* propData, unsigned propSize, ELzmaFinishMode finishMode,
ELzmaStatus* status, ISzAlloc* alloc)
{
CLzmaDec p;
SRes res;
SizeT outSize = *destLen, inSize = *srcLen;
*destLen = *srcLen = 0;
*status = LZMA_STATUS_NOT_SPECIFIED;
if (inSize < RC_INIT_SIZE)
return SZ_ERROR_INPUT_EOF;
LzmaDec_Construct(&p);
RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc));
p.dic = dest;
p.dicBufSize = outSize;
LzmaDec_Init(&p);
*srcLen = inSize;
res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
*destLen = p.dicPos;
if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
res = SZ_ERROR_INPUT_EOF;
LzmaDec_FreeProbs(&p, alloc);
return res;
}

View File

@ -1,237 +1,226 @@
/* LzmaDec.h -- LZMA Decoder
2023-04-02 : Igor Pavlov : Public domain */
#ifndef ZIP7_INC_LZMA_DEC_H
#define ZIP7_INC_LZMA_DEC_H
#include "7zTypes.h"
EXTERN_C_BEGIN
/* #define Z7_LZMA_PROB32 */
/* Z7_LZMA_PROB32 can increase the speed on some CPUs,
but memory usage for CLzmaDec::probs will be doubled in that case */
typedef
#ifdef Z7_LZMA_PROB32
UInt32
#else
UInt16
#endif
CLzmaProb;
/* ---------- LZMA Properties ---------- */
#define LZMA_PROPS_SIZE 5
typedef struct
{
Byte lc;
Byte lp;
Byte pb;
Byte _pad_;
UInt32 dicSize;
} CLzmaProps;
/* LzmaProps_Decode - decodes properties
Returns:
SZ_OK
SZ_ERROR_UNSUPPORTED - Unsupported properties
*/
SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
/* ---------- LZMA Decoder state ---------- */
/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
#define LZMA_REQUIRED_INPUT_MAX 20
typedef struct
{
/* Don't change this structure. ASM code can use it. */
CLzmaProps prop;
CLzmaProb *probs;
CLzmaProb *probs_1664;
Byte *dic;
SizeT dicBufSize;
SizeT dicPos;
const Byte *buf;
UInt32 range;
UInt32 code;
UInt32 processedPos;
UInt32 checkDicSize;
UInt32 reps[4];
UInt32 state;
UInt32 remainLen;
UInt32 numProbs;
unsigned tempBufSize;
Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
} CLzmaDec;
#define LzmaDec_CONSTRUCT(p) { (p)->dic = NULL; (p)->probs = NULL; }
#define LzmaDec_Construct(p) LzmaDec_CONSTRUCT(p)
void LzmaDec_Init(CLzmaDec *p);
/* There are two types of LZMA streams:
- Stream with end mark. That end mark adds about 6 bytes to compressed size.
- Stream without end mark. You must know exact uncompressed size to decompress such stream. */
typedef enum
{
LZMA_FINISH_ANY, /* finish at any point */
LZMA_FINISH_END /* block must be finished at the end */
} ELzmaFinishMode;
/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
You must use LZMA_FINISH_END, when you know that current output buffer
covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
and output value of destLen will be less than output buffer size limit.
You can check status result also.
You can use multiple checks to test data integrity after full decompression:
1) Check Result and "status" variable.
2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
You must use correct finish mode in that case. */
typedef enum
{
LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
} ELzmaStatus;
/* ELzmaStatus is used only as output value for function call */
/* ---------- Interfaces ---------- */
/* There are 3 levels of interfaces:
1) Dictionary Interface
2) Buffer Interface
3) One Call Interface
You can select any of these interfaces, but don't mix functions from different
groups for same object. */
/* There are two variants to allocate state for Dictionary Interface:
1) LzmaDec_Allocate / LzmaDec_Free
2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
You can use variant 2, if you set dictionary buffer manually.
For Buffer Interface you must always use variant 1.
LzmaDec_Allocate* can return:
SZ_OK
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
*/
SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc);
void LzmaDec_FreeProbs(CLzmaDec *p, ISzAllocPtr alloc);
SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc);
void LzmaDec_Free(CLzmaDec *p, ISzAllocPtr alloc);
/* ---------- Dictionary Interface ---------- */
/* You can use it, if you want to eliminate the overhead for data copying from
dictionary to some other external buffer.
You must work with CLzmaDec variables directly in this interface.
STEPS:
LzmaDec_Construct()
LzmaDec_Allocate()
for (each new stream)
{
LzmaDec_Init()
while (it needs more decompression)
{
LzmaDec_DecodeToDic()
use data from CLzmaDec::dic and update CLzmaDec::dicPos
}
}
LzmaDec_Free()
*/
/* LzmaDec_DecodeToDic
The decoding to internal dictionary buffer (CLzmaDec::dic).
You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
finishMode:
It has meaning only if the decoding reaches output limit (dicLimit).
LZMA_FINISH_ANY - Decode just dicLimit bytes.
LZMA_FINISH_END - Stream must be finished after dicLimit.
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_NEEDS_MORE_INPUT
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
SZ_ERROR_DATA - Data error
SZ_ERROR_FAIL - Some unexpected error: internal error of code, memory corruption or hardware failure
*/
SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
/* ---------- Buffer Interface ---------- */
/* It's zlib-like interface.
See LzmaDec_DecodeToDic description for information about STEPS and return results,
but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
to work with CLzmaDec variables manually.
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - Decode just destLen bytes.
LZMA_FINISH_END - Stream must be finished after (*destLen).
*/
SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
/* ---------- One Call Interface ---------- */
/* LzmaDecode
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - Decode just destLen bytes.
LZMA_FINISH_END - Stream must be finished after (*destLen).
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
SZ_ERROR_DATA - Data error
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
SZ_ERROR_FAIL - Some unexpected error: internal error of code, memory corruption or hardware failure
*/
SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
ELzmaStatus *status, ISzAllocPtr alloc);
EXTERN_C_END
#endif
/* LzmaDec.h -- LZMA Decoder
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __LZMA_DEC_H
#define __LZMA_DEC_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* #define _LZMA_PROB32 */
/* _LZMA_PROB32 can increase the speed on some CPUs,
but memory usage for CLzmaDec::probs will be doubled in that case */
#ifdef _LZMA_PROB32
#define CLzmaProb UInt32
#else
#define CLzmaProb UInt16
#endif
/* ---------- LZMA Properties ---------- */
#define LZMA_PROPS_SIZE 5
typedef struct _CLzmaProps {
unsigned lc, lp, pb;
UInt32 dicSize;
} CLzmaProps;
/* LzmaProps_Decode - decodes properties
Returns:
SZ_OK
SZ_ERROR_UNSUPPORTED - Unsupported properties
*/
SRes LzmaProps_Decode(CLzmaProps* p, const Byte* data, unsigned size);
/* ---------- LZMA Decoder state ---------- */
/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
#define LZMA_REQUIRED_INPUT_MAX 20
typedef struct
{
CLzmaProps prop;
CLzmaProb* probs;
Byte* dic;
const Byte* buf;
UInt32 range, code;
SizeT dicPos;
SizeT dicBufSize;
UInt32 processedPos;
UInt32 checkDicSize;
unsigned state;
UInt32 reps[4];
unsigned remainLen;
int needFlush;
int needInitState;
UInt32 numProbs;
unsigned tempBufSize;
Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
} CLzmaDec;
#define LzmaDec_Construct(p) \
{ \
(p)->dic = 0; \
(p)->probs = 0; \
}
void LzmaDec_Init(CLzmaDec* p);
/* There are two types of LZMA streams:
0) Stream with end mark. That end mark adds about 6 bytes to compressed size.
1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */
typedef enum {
LZMA_FINISH_ANY, /* finish at any point */
LZMA_FINISH_END /* block must be finished at the end */
} ELzmaFinishMode;
/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
You must use LZMA_FINISH_END, when you know that current output buffer
covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
and output value of destLen will be less than output buffer size limit.
You can check status result also.
You can use multiple checks to test data integrity after full decompression:
1) Check Result and "status" variable.
2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
You must use correct finish mode in that case. */
typedef enum {
LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
} ELzmaStatus;
/* ELzmaStatus is used only as output value for function call */
/* ---------- Interfaces ---------- */
/* There are 3 levels of interfaces:
1) Dictionary Interface
2) Buffer Interface
3) One Call Interface
You can select any of these interfaces, but don't mix functions from different
groups for same object. */
/* There are two variants to allocate state for Dictionary Interface:
1) LzmaDec_Allocate / LzmaDec_Free
2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
You can use variant 2, if you set dictionary buffer manually.
For Buffer Interface you must always use variant 1.
LzmaDec_Allocate* can return:
SZ_OK
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
*/
SRes LzmaDec_AllocateProbs(CLzmaDec* p, const Byte* props, unsigned propsSize, ISzAlloc* alloc);
void LzmaDec_FreeProbs(CLzmaDec* p, ISzAlloc* alloc);
SRes LzmaDec_Allocate(CLzmaDec* state, const Byte* prop, unsigned propsSize, ISzAlloc* alloc);
void LzmaDec_Free(CLzmaDec* state, ISzAlloc* alloc);
/* ---------- Dictionary Interface ---------- */
/* You can use it, if you want to eliminate the overhead for data copying from
dictionary to some other external buffer.
You must work with CLzmaDec variables directly in this interface.
STEPS:
LzmaDec_Constr()
LzmaDec_Allocate()
for (each new stream)
{
LzmaDec_Init()
while (it needs more decompression)
{
LzmaDec_DecodeToDic()
use data from CLzmaDec::dic and update CLzmaDec::dicPos
}
}
LzmaDec_Free()
*/
/* LzmaDec_DecodeToDic
The decoding to internal dictionary buffer (CLzmaDec::dic).
You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
finishMode:
It has meaning only if the decoding reaches output limit (dicLimit).
LZMA_FINISH_ANY - Decode just dicLimit bytes.
LZMA_FINISH_END - Stream must be finished after dicLimit.
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_NEEDS_MORE_INPUT
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
SZ_ERROR_DATA - Data error
*/
SRes LzmaDec_DecodeToDic(CLzmaDec* p, SizeT dicLimit,
const Byte* src, SizeT* srcLen, ELzmaFinishMode finishMode, ELzmaStatus* status);
/* ---------- Buffer Interface ---------- */
/* It's zlib-like interface.
See LzmaDec_DecodeToDic description for information about STEPS and return results,
but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
to work with CLzmaDec variables manually.
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - Decode just destLen bytes.
LZMA_FINISH_END - Stream must be finished after (*destLen).
*/
SRes LzmaDec_DecodeToBuf(CLzmaDec* p, Byte* dest, SizeT* destLen,
const Byte* src, SizeT* srcLen, ELzmaFinishMode finishMode, ELzmaStatus* status);
/* ---------- One Call Interface ---------- */
/* LzmaDecode
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - Decode just destLen bytes.
LZMA_FINISH_END - Stream must be finished after (*destLen).
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
SZ_ERROR_DATA - Data error
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
*/
SRes LzmaDecode(Byte* dest, SizeT* destLen, const Byte* src, SizeT* srcLen,
const Byte* propData, unsigned propSize, ELzmaFinishMode finishMode,
ELzmaStatus* status, ISzAlloc* alloc);
#ifdef __cplusplus
}
#endif
#endif

93
fex/7z_C/Ppmd.h Normal file
View File

@ -0,0 +1,93 @@
/* Ppmd.h -- PPMD codec common code
2011-01-27 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
#ifndef __PPMD_H
#define __PPMD_H
#include "CpuArch.h"
#include "Types.h"
EXTERN_C_BEGIN
#ifdef MY_CPU_32BIT
#define PPMD_32BIT
#endif
#define PPMD_INT_BITS 7
#define PPMD_PERIOD_BITS 7
#define PPMD_BIN_SCALE (1 << (PPMD_INT_BITS + PPMD_PERIOD_BITS))
#define PPMD_GET_MEAN_SPEC(summ, shift, round) (((summ) + (1 << ((shift) - (round)))) >> (shift))
#define PPMD_GET_MEAN(summ) PPMD_GET_MEAN_SPEC((summ), PPMD_PERIOD_BITS, 2)
#define PPMD_UPDATE_PROB_0(prob) ((prob) + (1 << PPMD_INT_BITS) - PPMD_GET_MEAN(prob))
#define PPMD_UPDATE_PROB_1(prob) ((prob)-PPMD_GET_MEAN(prob))
#define PPMD_N1 4
#define PPMD_N2 4
#define PPMD_N3 4
#define PPMD_N4 ((128 + 3 - 1 * PPMD_N1 - 2 * PPMD_N2 - 3 * PPMD_N3) / 4)
#define PPMD_NUM_INDEXES (PPMD_N1 + PPMD_N2 + PPMD_N3 + PPMD_N4)
#pragma pack(push, 1)
/* Most compilers works OK here even without #pragma pack(push, 1), but some GCC compilers need it. */
/* SEE-contexts for PPM-contexts with masked symbols */
typedef struct
{
UInt16 Summ; /* Freq */
Byte Shift; /* Speed of Freq change; low Shift is for fast change */
Byte Count; /* Count to next change of Shift */
} CPpmd_See;
#define Ppmd_See_Update(p) \
if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) { \
(p)->Summ <<= 1; \
(p)->Count = (Byte)(3 << (p)->Shift++); \
}
typedef struct
{
Byte Symbol;
Byte Freq;
UInt16 SuccessorLow;
UInt16 SuccessorHigh;
} CPpmd_State;
#pragma pack(pop)
typedef
#ifdef PPMD_32BIT
CPpmd_State*
#else
UInt32
#endif
CPpmd_State_Ref;
typedef
#ifdef PPMD_32BIT
void*
#else
UInt32
#endif
CPpmd_Void_Ref;
typedef
#ifdef PPMD_32BIT
Byte*
#else
UInt32
#endif
CPpmd_Byte_Ref;
#define PPMD_SetAllBitsIn256Bytes(p) \
{ \
unsigned i; \
for (i = 0; i < 256 / sizeof(p[0]); i += 8) { \
p[i + 7] = p[i + 6] = p[i + 5] = p[i + 4] = p[i + 3] = p[i + 2] = p[i + 1] = p[i + 0] = ~(size_t)0; \
} \
}
EXTERN_C_END
#endif

667
fex/7z_C/Ppmd7.c Normal file
View File

@ -0,0 +1,667 @@
/* Ppmd7.c -- PPMdH codec
2010-03-12 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
#include <memory.h>
#include "Ppmd7.h"
const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051 };
#define MAX_FREQ 124
#define UNIT_SIZE 12
#define U2B(nu) ((UInt32)(nu)*UNIT_SIZE)
#define U2I(nu) (p->Units2Indx[(nu)-1])
#define I2U(indx) (p->Indx2Units[indx])
#ifdef PPMD_32BIT
#define REF(ptr) (ptr)
#else
#define REF(ptr) ((UInt32)((Byte*)(ptr) - (p)->Base))
#endif
#define STATS_REF(ptr) ((CPpmd_State_Ref)REF(ptr))
#define CTX(ref) ((CPpmd7_Context*)Ppmd7_GetContext(p, ref))
#define STATS(ctx) Ppmd7_GetStats(p, ctx)
#define ONE_STATE(ctx) Ppmd7Context_OneState(ctx)
#define SUFFIX(ctx) CTX((ctx)->Suffix)
typedef CPpmd7_Context* CTX_PTR;
struct CPpmd7_Node_;
typedef
#ifdef PPMD_32BIT
struct CPpmd7_Node_*
#else
UInt32
#endif
CPpmd7_Node_Ref;
typedef struct CPpmd7_Node_ {
UInt16 Stamp; /* must be at offset 0 as CPpmd7_Context::NumStats. Stamp=0 means free */
UInt16 NU;
CPpmd7_Node_Ref Next; /* must be at offset >= 4 */
CPpmd7_Node_Ref Prev;
} CPpmd7_Node;
#ifdef PPMD_32BIT
#define NODE(ptr) (ptr)
#else
#define NODE(offs) ((CPpmd7_Node*)(p->Base + (offs)))
#endif
void Ppmd7_Construct(CPpmd7* p)
{
unsigned i, k, m;
p->Base = 0;
for (i = 0, k = 0; i < PPMD_NUM_INDEXES; i++) {
unsigned step = (i >= 12 ? 4 : (i >> 2) + 1);
do {
p->Units2Indx[k++] = (Byte)i;
} while (--step);
p->Indx2Units[i] = (Byte)k;
}
p->NS2BSIndx[0] = (0 << 1);
p->NS2BSIndx[1] = (1 << 1);
memset(p->NS2BSIndx + 2, (2 << 1), 9);
memset(p->NS2BSIndx + 11, (3 << 1), 256 - 11);
for (i = 0; i < 3; i++)
p->NS2Indx[i] = (Byte)i;
for (m = i, k = 1; i < 256; i++) {
p->NS2Indx[i] = (Byte)m;
if (--k == 0)
k = (++m) - 2;
}
memset(p->HB2Flag, 0, 0x40);
memset(p->HB2Flag + 0x40, 8, 0x100 - 0x40);
}
void Ppmd7_Free(CPpmd7* p, ISzAlloc* alloc)
{
alloc->Free(alloc, p->Base);
p->Size = 0;
p->Base = 0;
}
Bool Ppmd7_Alloc(CPpmd7* p, UInt32 size, ISzAlloc* alloc)
{
if (p->Base == 0 || p->Size != size) {
Ppmd7_Free(p, alloc);
p->AlignOffset =
#ifdef PPMD_32BIT
(4 - size) & 3;
#else
4 - (size & 3);
#endif
if ((p->Base = (Byte*)alloc->Alloc(alloc, p->AlignOffset + size
#ifndef PPMD_32BIT
+ UNIT_SIZE
#endif
))
== 0)
return False;
p->Size = size;
}
return True;
}
static void InsertNode(CPpmd7* p, void* node, unsigned indx)
{
*((CPpmd_Void_Ref*)node) = p->FreeList[indx];
p->FreeList[indx] = REF(node);
}
static void* RemoveNode(CPpmd7* p, unsigned indx)
{
CPpmd_Void_Ref* node = (CPpmd_Void_Ref*)Ppmd7_GetPtr(p, p->FreeList[indx]);
p->FreeList[indx] = *node;
return node;
}
static void SplitBlock(CPpmd7* p, void* ptr, unsigned oldIndx, unsigned newIndx)
{
unsigned i, nu = I2U(oldIndx) - I2U(newIndx);
ptr = (Byte*)ptr + U2B(I2U(newIndx));
if (I2U(i = U2I(nu)) != nu) {
unsigned k = I2U(--i);
InsertNode(p, ((Byte*)ptr) + U2B(k), nu - k - 1);
}
InsertNode(p, ptr, i);
}
static void GlueFreeBlocks(CPpmd7* p)
{
#ifdef PPMD_32BIT
CPpmd7_Node headItem;
CPpmd7_Node_Ref head = &headItem;
#else
CPpmd7_Node_Ref head = p->AlignOffset + p->Size;
#endif
CPpmd7_Node_Ref n = head;
unsigned i;
p->GlueCount = 255;
/* create doubly-linked list of free blocks */
for (i = 0; i < PPMD_NUM_INDEXES; i++) {
UInt16 nu = I2U(i);
CPpmd7_Node_Ref next = (CPpmd7_Node_Ref)p->FreeList[i];
p->FreeList[i] = 0;
while (next != 0) {
CPpmd7_Node* node = NODE(next);
node->Next = n;
n = NODE(n)->Prev = next;
next = *(const CPpmd7_Node_Ref*)node;
node->Stamp = 0;
node->NU = (UInt16)nu;
}
}
NODE(head)
->Stamp
= 1;
NODE(head)
->Next
= n;
NODE(n)
->Prev
= head;
if (p->LoUnit != p->HiUnit)
((CPpmd7_Node*)p->LoUnit)->Stamp = 1;
/* Glue free blocks */
while (n != head) {
CPpmd7_Node* node = NODE(n);
UInt32 nu = (UInt32)node->NU;
for (;;) {
CPpmd7_Node* node2 = NODE(n) + nu;
nu += node2->NU;
if (node2->Stamp != 0 || nu >= 0x10000)
break;
NODE(node2->Prev)
->Next
= node2->Next;
NODE(node2->Next)
->Prev
= node2->Prev;
node->NU = (UInt16)nu;
}
n = node->Next;
}
/* Fill lists of free blocks */
for (n = NODE(head)->Next; n != head;) {
CPpmd7_Node* node = NODE(n);
unsigned nu;
CPpmd7_Node_Ref next = node->Next;
for (nu = node->NU; nu > 128; nu -= 128, node += 128)
InsertNode(p, node, PPMD_NUM_INDEXES - 1);
if (I2U(i = U2I(nu)) != nu) {
unsigned k = I2U(--i);
InsertNode(p, node + k, nu - k - 1);
}
InsertNode(p, node, i);
n = next;
}
}
static void* AllocUnitsRare(CPpmd7* p, unsigned indx)
{
unsigned i;
void* retVal;
if (p->GlueCount == 0) {
GlueFreeBlocks(p);
if (p->FreeList[indx] != 0)
return RemoveNode(p, indx);
}
i = indx;
do {
if (++i == PPMD_NUM_INDEXES) {
UInt32 numBytes = U2B(I2U(indx));
p->GlueCount--;
return ((UInt32)(p->UnitsStart - p->Text) > numBytes) ? (p->UnitsStart -= numBytes) : (NULL);
}
} while (p->FreeList[i] == 0);
retVal = RemoveNode(p, i);
SplitBlock(p, retVal, i, indx);
return retVal;
}
static void* AllocUnits(CPpmd7* p, unsigned indx)
{
UInt32 numBytes;
if (p->FreeList[indx] != 0)
return RemoveNode(p, indx);
numBytes = U2B(I2U(indx));
if (numBytes <= (UInt32)(p->HiUnit - p->LoUnit)) {
void* retVal = p->LoUnit;
p->LoUnit += numBytes;
return retVal;
}
return AllocUnitsRare(p, indx);
}
#define MyMem12Cpy(dest, src, num) \
{ \
UInt32* d = (UInt32*)dest; \
const UInt32* s = (const UInt32*)src; \
UInt32 n = num; \
do { \
d[0] = s[0]; \
d[1] = s[1]; \
d[2] = s[2]; \
s += 3; \
d += 3; \
} while (--n); \
}
static void* ShrinkUnits(CPpmd7* p, void* oldPtr, unsigned oldNU, unsigned newNU)
{
unsigned i0 = U2I(oldNU);
unsigned i1 = U2I(newNU);
if (i0 == i1)
return oldPtr;
if (p->FreeList[i1] != 0) {
void* ptr = RemoveNode(p, i1);
MyMem12Cpy(ptr, oldPtr, newNU);
InsertNode(p, oldPtr, i0);
return ptr;
}
SplitBlock(p, oldPtr, i0, i1);
return oldPtr;
}
#define SUCCESSOR(p) ((CPpmd_Void_Ref)((p)->SuccessorLow | ((UInt32)(p)->SuccessorHigh << 16)))
static void SetSuccessor(CPpmd_State* p, CPpmd_Void_Ref v)
{
(p)->SuccessorLow = (UInt16)((UInt32)(v)&0xFFFF);
(p)->SuccessorHigh = (UInt16)(((UInt32)(v) >> 16) & 0xFFFF);
}
static void RestartModel(CPpmd7* p)
{
unsigned i, k, m;
memset(p->FreeList, 0, sizeof(p->FreeList));
p->Text = p->Base + p->AlignOffset;
p->HiUnit = p->Text + p->Size;
p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE;
p->GlueCount = 0;
p->OrderFall = p->MaxOrder;
p->RunLength = p->InitRL = -(Int32)((p->MaxOrder < 12) ? p->MaxOrder : 12) - 1;
p->PrevSuccess = 0;
p->MinContext = p->MaxContext = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */
p->MinContext->Suffix = 0;
p->MinContext->NumStats = 256;
p->MinContext->SummFreq = 256 + 1;
p->FoundState = (CPpmd_State*)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */
p->LoUnit += U2B(256 / 2);
p->MinContext->Stats = REF(p->FoundState);
for (i = 0; i < 256; i++) {
CPpmd_State* s = &p->FoundState[i];
s->Symbol = (Byte)i;
s->Freq = 1;
SetSuccessor(s, 0);
}
for (i = 0; i < 128; i++)
for (k = 0; k < 8; k++) {
UInt16* dest = p->BinSumm[i] + k;
UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2));
for (m = 0; m < 64; m += 8)
dest[m] = val;
}
for (i = 0; i < 25; i++)
for (k = 0; k < 16; k++) {
CPpmd_See* s = &p->See[i][k];
s->Summ = (UInt16)((5 * i + 10) << (s->Shift = PPMD_PERIOD_BITS - 4));
s->Count = 4;
}
}
void Ppmd7_Init(CPpmd7* p, unsigned maxOrder)
{
p->MaxOrder = maxOrder;
RestartModel(p);
p->DummySee.Shift = PPMD_PERIOD_BITS;
p->DummySee.Summ = 0; /* unused */
p->DummySee.Count = 64; /* unused */
}
static CTX_PTR CreateSuccessors(CPpmd7* p, Bool skip)
{
CPpmd_State upState;
CTX_PTR c = p->MinContext;
CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState);
CPpmd_State* ps[PPMD7_MAX_ORDER];
unsigned numPs = 0;
if (!skip)
ps[numPs++] = p->FoundState;
while (c->Suffix) {
CPpmd_Void_Ref successor;
CPpmd_State* s;
c = SUFFIX(c);
if (c->NumStats != 1) {
for (s = STATS(c); s->Symbol != p->FoundState->Symbol; s++)
;
} else
s = ONE_STATE(c);
successor = SUCCESSOR(s);
if (successor != upBranch) {
c = CTX(successor);
if (numPs == 0)
return c;
break;
}
ps[numPs++] = s;
}
upState.Symbol = *(const Byte*)Ppmd7_GetPtr(p, upBranch);
SetSuccessor(&upState, upBranch + 1);
if (c->NumStats == 1)
upState.Freq = ONE_STATE(c)->Freq;
else {
UInt32 cf, s0;
CPpmd_State* s;
for (s = STATS(c); s->Symbol != upState.Symbol; s++)
;
cf = s->Freq - 1;
s0 = c->SummFreq - c->NumStats - cf;
upState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : ((2 * cf + 3 * s0 - 1) / (2 * s0))));
}
do {
/* Create Child */
CTX_PTR c1; /* = AllocContext(p); */
if (p->HiUnit != p->LoUnit)
c1 = (CTX_PTR)(p->HiUnit -= UNIT_SIZE);
else if (p->FreeList[0] != 0)
c1 = (CTX_PTR)RemoveNode(p, 0);
else {
c1 = (CTX_PTR)AllocUnitsRare(p, 0);
if (!c1)
return NULL;
}
c1->NumStats = 1;
*ONE_STATE(c1) = upState;
c1->Suffix = REF(c);
SetSuccessor(ps[--numPs], REF(c1));
c = c1;
} while (numPs != 0);
return c;
}
static void SwapStates(CPpmd_State* t1, CPpmd_State* t2)
{
CPpmd_State tmp = *t1;
*t1 = *t2;
*t2 = tmp;
}
static void UpdateModel(CPpmd7* p)
{
CPpmd_Void_Ref successor, fSuccessor = SUCCESSOR(p->FoundState);
CTX_PTR c;
unsigned s0, ns;
if (p->FoundState->Freq < MAX_FREQ / 4 && p->MinContext->Suffix != 0) {
c = SUFFIX(p->MinContext);
if (c->NumStats == 1) {
CPpmd_State* s = ONE_STATE(c);
if (s->Freq < 32)
s->Freq++;
} else {
CPpmd_State* s = STATS(c);
if (s->Symbol != p->FoundState->Symbol) {
do {
s++;
} while (s->Symbol != p->FoundState->Symbol);
if (s[0].Freq >= s[-1].Freq) {
SwapStates(&s[0], &s[-1]);
s--;
}
}
if (s->Freq < MAX_FREQ - 9) {
s->Freq += 2;
c->SummFreq += 2;
}
}
}
if (p->OrderFall == 0) {
p->MinContext = p->MaxContext = CreateSuccessors(p, True);
if (p->MinContext == 0) {
RestartModel(p);
return;
}
SetSuccessor(p->FoundState, REF(p->MinContext));
return;
}
*p->Text++ = p->FoundState->Symbol;
successor = REF(p->Text);
if (p->Text >= p->UnitsStart) {
RestartModel(p);
return;
}
if (fSuccessor) {
if (fSuccessor <= successor) {
CTX_PTR cs = CreateSuccessors(p, False);
if (cs == NULL) {
RestartModel(p);
return;
}
fSuccessor = REF(cs);
}
if (--p->OrderFall == 0) {
successor = fSuccessor;
p->Text -= (p->MaxContext != p->MinContext);
}
} else {
SetSuccessor(p->FoundState, successor);
fSuccessor = REF(p->MinContext);
}
s0 = p->MinContext->SummFreq - (ns = p->MinContext->NumStats) - (p->FoundState->Freq - 1);
for (c = p->MaxContext; c != p->MinContext; c = SUFFIX(c)) {
unsigned ns1;
UInt32 cf, sf;
if ((ns1 = c->NumStats) != 1) {
if ((ns1 & 1) == 0) {
/* Expand for one UNIT */
unsigned oldNU = ns1 >> 1;
unsigned i = U2I(oldNU);
if (i != U2I(oldNU + 1)) {
void* ptr = AllocUnits(p, i + 1);
void* oldPtr;
if (!ptr) {
RestartModel(p);
return;
}
oldPtr = STATS(c);
MyMem12Cpy(ptr, oldPtr, oldNU);
InsertNode(p, oldPtr, i);
c->Stats = STATS_REF(ptr);
}
}
c->SummFreq = (UInt16)(c->SummFreq + (2 * ns1 < ns) + 2 * ((4 * ns1 <= ns) & (c->SummFreq <= 8 * ns1)));
} else {
CPpmd_State* s = (CPpmd_State*)AllocUnits(p, 0);
if (!s) {
RestartModel(p);
return;
}
*s = *ONE_STATE(c);
c->Stats = REF(s);
if (s->Freq < MAX_FREQ / 4 - 1)
s->Freq <<= 1;
else
s->Freq = MAX_FREQ - 4;
c->SummFreq = (UInt16)(s->Freq + p->InitEsc + (ns > 3));
}
cf = 2 * (UInt32)p->FoundState->Freq * (c->SummFreq + 6);
sf = (UInt32)s0 + c->SummFreq;
if (cf < 6 * sf) {
cf = 1 + (cf > sf) + (cf >= 4 * sf);
c->SummFreq += 3;
} else {
cf = 4 + (cf >= 9 * sf) + (cf >= 12 * sf) + (cf >= 15 * sf);
c->SummFreq = (UInt16)(c->SummFreq + cf);
}
{
CPpmd_State* s = STATS(c) + ns1;
SetSuccessor(s, successor);
s->Symbol = p->FoundState->Symbol;
s->Freq = (Byte)cf;
c->NumStats = (UInt16)(ns1 + 1);
}
}
p->MaxContext = p->MinContext = CTX(fSuccessor);
}
static void Rescale(CPpmd7* p)
{
unsigned i, adder, sumFreq, escFreq;
CPpmd_State* stats = STATS(p->MinContext);
CPpmd_State* s = p->FoundState;
{
CPpmd_State tmp = *s;
for (; s != stats; s--)
s[0] = s[-1];
*s = tmp;
}
escFreq = p->MinContext->SummFreq - s->Freq;
s->Freq += 4;
adder = (p->OrderFall != 0);
s->Freq = (Byte)((s->Freq + adder) >> 1);
sumFreq = s->Freq;
i = p->MinContext->NumStats - 1;
do {
escFreq -= (++s)->Freq;
s->Freq = (Byte)((s->Freq + adder) >> 1);
sumFreq += s->Freq;
if (s[0].Freq > s[-1].Freq) {
CPpmd_State* s1 = s;
CPpmd_State tmp = *s1;
do
s1[0] = s1[-1];
while (--s1 != stats && tmp.Freq > s1[-1].Freq);
*s1 = tmp;
}
} while (--i);
if (s->Freq == 0) {
unsigned numStats = p->MinContext->NumStats;
unsigned n0, n1;
do {
i++;
} while ((--s)->Freq == 0);
escFreq += i;
p->MinContext->NumStats = (UInt16)(p->MinContext->NumStats - i);
if (p->MinContext->NumStats == 1) {
CPpmd_State tmp = *stats;
do {
tmp.Freq = (Byte)(tmp.Freq - (tmp.Freq >> 1));
escFreq >>= 1;
} while (escFreq > 1);
InsertNode(p, stats, U2I(((numStats + 1) >> 1)));
*(p->FoundState = ONE_STATE(p->MinContext)) = tmp;
return;
}
n0 = (numStats + 1) >> 1;
n1 = (p->MinContext->NumStats + 1) >> 1;
if (n0 != n1)
p->MinContext->Stats = STATS_REF(ShrinkUnits(p, stats, n0, n1));
}
p->MinContext->SummFreq = (UInt16)(sumFreq + escFreq - (escFreq >> 1));
p->FoundState = STATS(p->MinContext);
}
CPpmd_See* Ppmd7_MakeEscFreq(CPpmd7* p, unsigned numMasked, UInt32* escFreq)
{
CPpmd_See* see;
unsigned nonMasked = p->MinContext->NumStats - numMasked;
if (p->MinContext->NumStats != 256) {
see = p->See[p->NS2Indx[nonMasked - 1]] + (nonMasked < (unsigned)SUFFIX(p->MinContext)->NumStats - p->MinContext->NumStats) + 2 * (p->MinContext->SummFreq < 11 * p->MinContext->NumStats) + 4 * (numMasked > nonMasked) + p->HiBitsFlag;
{
unsigned r = (see->Summ >> see->Shift);
see->Summ = (UInt16)(see->Summ - r);
*escFreq = r + (r == 0);
}
} else {
see = &p->DummySee;
*escFreq = 1;
}
return see;
}
static void NextContext(CPpmd7* p)
{
CTX_PTR c = CTX(SUCCESSOR(p->FoundState));
if (p->OrderFall == 0 && (Byte*)c > p->Text)
p->MinContext = p->MaxContext = c;
else
UpdateModel(p);
}
void Ppmd7_Update1(CPpmd7* p)
{
CPpmd_State* s = p->FoundState;
s->Freq += 4;
p->MinContext->SummFreq += 4;
if (s[0].Freq > s[-1].Freq) {
SwapStates(&s[0], &s[-1]);
p->FoundState = --s;
if (s->Freq > MAX_FREQ)
Rescale(p);
}
NextContext(p);
}
void Ppmd7_Update1_0(CPpmd7* p)
{
p->PrevSuccess = (2 * p->FoundState->Freq > p->MinContext->SummFreq);
p->RunLength += p->PrevSuccess;
p->MinContext->SummFreq += 4;
if ((p->FoundState->Freq += 4) > MAX_FREQ)
Rescale(p);
NextContext(p);
}
void Ppmd7_UpdateBin(CPpmd7* p)
{
p->FoundState->Freq = (Byte)(p->FoundState->Freq + (p->FoundState->Freq < 128 ? 1 : 0));
p->PrevSuccess = 1;
p->RunLength++;
NextContext(p);
}
void Ppmd7_Update2(CPpmd7* p)
{
p->MinContext->SummFreq += 4;
if ((p->FoundState->Freq += 4) > MAX_FREQ)
Rescale(p);
p->RunLength = p->InitRL;
UpdateModel(p);
}

132
fex/7z_C/Ppmd7.h Normal file
View File

@ -0,0 +1,132 @@
/* Ppmd7.h -- PPMdH compression codec
2010-03-12 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
/* This code supports virtual RangeDecoder and includes the implementation
of RangeCoder from 7z, instead of RangeCoder from original PPMd var.H.
If you need the compatibility with original PPMd var.H, you can use external RangeDecoder */
#ifndef __PPMD7_H
#define __PPMD7_H
#include "Ppmd.h"
EXTERN_C_BEGIN
#define PPMD7_MIN_ORDER 2
#define PPMD7_MAX_ORDER 64
#define PPMD7_MIN_MEM_SIZE (1 << 11)
#define PPMD7_MAX_MEM_SIZE (0xFFFFFFFF - 12 * 3)
struct CPpmd7_Context_;
typedef
#ifdef PPMD_32BIT
struct CPpmd7_Context_*
#else
UInt32
#endif
CPpmd7_Context_Ref;
typedef struct CPpmd7_Context_ {
UInt16 NumStats;
UInt16 SummFreq;
CPpmd_State_Ref Stats;
CPpmd7_Context_Ref Suffix;
} CPpmd7_Context;
#define Ppmd7Context_OneState(p) ((CPpmd_State*)&(p)->SummFreq)
typedef struct
{
CPpmd7_Context *MinContext, *MaxContext;
CPpmd_State* FoundState;
unsigned OrderFall, InitEsc, PrevSuccess, MaxOrder, HiBitsFlag;
Int32 RunLength, InitRL; /* must be 32-bit at least */
UInt32 Size;
UInt32 GlueCount;
Byte *Base, *LoUnit, *HiUnit, *Text, *UnitsStart;
UInt32 AlignOffset;
Byte Indx2Units[PPMD_NUM_INDEXES];
Byte Units2Indx[128];
CPpmd_Void_Ref FreeList[PPMD_NUM_INDEXES];
Byte NS2Indx[256], NS2BSIndx[256], HB2Flag[256];
CPpmd_See DummySee, See[25][16];
UInt16 BinSumm[128][64];
} CPpmd7;
void Ppmd7_Construct(CPpmd7* p);
Bool Ppmd7_Alloc(CPpmd7* p, UInt32 size, ISzAlloc* alloc);
void Ppmd7_Free(CPpmd7* p, ISzAlloc* alloc);
void Ppmd7_Init(CPpmd7* p, unsigned maxOrder);
#define Ppmd7_WasAllocated(p) ((p)->Base != NULL)
/* ---------- Internal Functions ---------- */
extern const Byte PPMD7_kExpEscape[16];
#ifdef PPMD_32BIT
#define Ppmd7_GetPtr(p, ptr) (ptr)
#define Ppmd7_GetContext(p, ptr) (ptr)
#define Ppmd7_GetStats(p, ctx) ((ctx)->Stats)
#else
#define Ppmd7_GetPtr(p, offs) ((void*)((p)->Base + (offs)))
#define Ppmd7_GetContext(p, offs) ((CPpmd7_Context*)Ppmd7_GetPtr((p), (offs)))
#define Ppmd7_GetStats(p, ctx) ((CPpmd_State*)Ppmd7_GetPtr((p), ((ctx)->Stats)))
#endif
void Ppmd7_Update1(CPpmd7* p);
void Ppmd7_Update1_0(CPpmd7* p);
void Ppmd7_Update2(CPpmd7* p);
void Ppmd7_UpdateBin(CPpmd7* p);
#define Ppmd7_GetBinSumm(p) \
&p->BinSumm[Ppmd7Context_OneState(p->MinContext)->Freq - 1][p->PrevSuccess + p->NS2BSIndx[Ppmd7_GetContext(p, p->MinContext->Suffix)->NumStats - 1] + (p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol]) + 2 * p->HB2Flag[Ppmd7Context_OneState(p->MinContext)->Symbol] + ((p->RunLength >> 26) & 0x20)]
CPpmd_See* Ppmd7_MakeEscFreq(CPpmd7* p, unsigned numMasked, UInt32* scale);
/* ---------- Decode ---------- */
typedef struct
{
UInt32 (*GetThreshold)(void* p, UInt32 total);
void (*Decode)(void* p, UInt32 start, UInt32 size);
UInt32 (*DecodeBit)(void* p, UInt32 size0);
} IPpmd7_RangeDec;
typedef struct
{
IPpmd7_RangeDec p;
UInt32 Range;
UInt32 Code;
IByteIn* Stream;
} CPpmd7z_RangeDec;
void Ppmd7z_RangeDec_CreateVTable(CPpmd7z_RangeDec* p);
Bool Ppmd7z_RangeDec_Init(CPpmd7z_RangeDec* p);
#define Ppmd7z_RangeDec_IsFinishedOK(p) ((p)->Code == 0)
int Ppmd7_DecodeSymbol(CPpmd7* p, IPpmd7_RangeDec* rc);
/* ---------- Encode ---------- */
typedef struct
{
UInt64 Low;
UInt32 Range;
Byte Cache;
UInt64 CacheSize;
IByteOut* Stream;
} CPpmd7z_RangeEnc;
void Ppmd7z_RangeEnc_Init(CPpmd7z_RangeEnc* p);
void Ppmd7z_RangeEnc_FlushData(CPpmd7z_RangeEnc* p);
void Ppmd7_EncodeSymbol(CPpmd7* p, CPpmd7z_RangeEnc* rc, int symbol);
EXTERN_C_END
#endif

172
fex/7z_C/Ppmd7Dec.c Normal file
View File

@ -0,0 +1,172 @@
/* Ppmd7Dec.c -- PPMdH Decoder
2010-03-12 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
#include "Ppmd7.h"
#define kTopValue (1 << 24)
Bool Ppmd7z_RangeDec_Init(CPpmd7z_RangeDec* p)
{
unsigned i;
p->Code = 0;
p->Range = 0xFFFFFFFF;
if (p->Stream->Read((void*)p->Stream) != 0)
return False;
for (i = 0; i < 4; i++)
p->Code = (p->Code << 8) | p->Stream->Read((void*)p->Stream);
return (p->Code < 0xFFFFFFFF);
}
static UInt32 Range_GetThreshold(void* pp, UInt32 total)
{
CPpmd7z_RangeDec* p = (CPpmd7z_RangeDec*)pp;
return (p->Code) / (p->Range /= total);
}
static void Range_Normalize(CPpmd7z_RangeDec* p)
{
if (p->Range < kTopValue) {
p->Code = (p->Code << 8) | p->Stream->Read((void*)p->Stream);
p->Range <<= 8;
if (p->Range < kTopValue) {
p->Code = (p->Code << 8) | p->Stream->Read((void*)p->Stream);
p->Range <<= 8;
}
}
}
static void Range_Decode(void* pp, UInt32 start, UInt32 size)
{
CPpmd7z_RangeDec* p = (CPpmd7z_RangeDec*)pp;
p->Code -= start * p->Range;
p->Range *= size;
Range_Normalize(p);
}
static UInt32 Range_DecodeBit(void* pp, UInt32 size0)
{
CPpmd7z_RangeDec* p = (CPpmd7z_RangeDec*)pp;
UInt32 newBound = (p->Range >> 14) * size0;
UInt32 symbol;
if (p->Code < newBound) {
symbol = 0;
p->Range = newBound;
} else {
symbol = 1;
p->Code -= newBound;
p->Range -= newBound;
}
Range_Normalize(p);
return symbol;
}
void Ppmd7z_RangeDec_CreateVTable(CPpmd7z_RangeDec* p)
{
p->p.GetThreshold = Range_GetThreshold;
p->p.Decode = Range_Decode;
p->p.DecodeBit = Range_DecodeBit;
}
#define MASK(sym) ((signed char*)charMask)[sym]
int Ppmd7_DecodeSymbol(CPpmd7* p, IPpmd7_RangeDec* rc)
{
size_t charMask[256 / sizeof(size_t)];
if (p->MinContext->NumStats != 1) {
CPpmd_State* s = Ppmd7_GetStats(p, p->MinContext);
unsigned i;
UInt32 count, hiCnt;
if ((count = rc->GetThreshold(rc, p->MinContext->SummFreq)) < (hiCnt = s->Freq)) {
Byte symbol;
rc->Decode(rc, 0, s->Freq);
p->FoundState = s;
symbol = s->Symbol;
Ppmd7_Update1_0(p);
return symbol;
}
p->PrevSuccess = 0;
i = p->MinContext->NumStats - 1;
do {
if ((hiCnt += (++s)->Freq) > count) {
Byte symbol;
rc->Decode(rc, hiCnt - s->Freq, s->Freq);
p->FoundState = s;
symbol = s->Symbol;
Ppmd7_Update1(p);
return symbol;
}
} while (--i);
if (count >= p->MinContext->SummFreq)
return -2;
p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol];
rc->Decode(rc, hiCnt, p->MinContext->SummFreq - hiCnt);
PPMD_SetAllBitsIn256Bytes(charMask);
MASK(s->Symbol) = 0;
i = p->MinContext->NumStats - 1;
do {
MASK((--s)->Symbol) = 0;
} while (--i);
} else {
UInt16* prob = Ppmd7_GetBinSumm(p);
if (rc->DecodeBit(rc, *prob) == 0) {
Byte symbol;
*prob = (UInt16)PPMD_UPDATE_PROB_0(*prob);
symbol = (p->FoundState = Ppmd7Context_OneState(p->MinContext))->Symbol;
Ppmd7_UpdateBin(p);
return symbol;
}
*prob = (UInt16)PPMD_UPDATE_PROB_1(*prob);
p->InitEsc = PPMD7_kExpEscape[*prob >> 10];
PPMD_SetAllBitsIn256Bytes(charMask);
MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0;
p->PrevSuccess = 0;
}
for (;;) {
CPpmd_State *ps[256], *s;
UInt32 freqSum, count, hiCnt;
CPpmd_See* see;
unsigned i, num, numMasked = p->MinContext->NumStats;
do {
p->OrderFall++;
if (!p->MinContext->Suffix)
return -1;
p->MinContext = Ppmd7_GetContext(p, p->MinContext->Suffix);
} while (p->MinContext->NumStats == numMasked);
hiCnt = 0;
s = Ppmd7_GetStats(p, p->MinContext);
i = 0;
num = p->MinContext->NumStats - numMasked;
do {
int k = (int)(MASK(s->Symbol));
hiCnt += (s->Freq & k);
ps[i] = s++;
i -= k;
} while (i != num);
see = Ppmd7_MakeEscFreq(p, numMasked, &freqSum);
freqSum += hiCnt;
count = rc->GetThreshold(rc, freqSum);
if (count < hiCnt) {
Byte symbol;
CPpmd_State** pps = ps;
for (hiCnt = 0; (hiCnt += (*pps)->Freq) <= count; pps++)
;
s = *pps;
rc->Decode(rc, hiCnt - s->Freq, s->Freq);
Ppmd_See_Update(see);
p->FoundState = s;
symbol = s->Symbol;
Ppmd7_Update2(p);
return symbol;
}
if (count >= freqSum)
return -2;
rc->Decode(rc, hiCnt, freqSum - hiCnt);
see->Summ = (UInt16)(see->Summ + freqSum);
do {
MASK(ps[--i]->Symbol) = 0;
} while (i != 0);
}
}

256
fex/7z_C/Types.h Normal file
View File

@ -0,0 +1,256 @@
/* Types.h -- Basic types
2010-10-09 : Igor Pavlov : Public domain */
#ifndef __7Z_TYPES_H
#define __7Z_TYPES_H
#include <stddef.h>
#ifdef _WIN32
#include <windows.h>
#endif
#ifndef EXTERN_C_BEGIN
#ifdef __cplusplus
#define EXTERN_C_BEGIN extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C_BEGIN
#define EXTERN_C_END
#endif
#endif
EXTERN_C_BEGIN
#define SZ_OK 0
#define SZ_ERROR_DATA 1
#define SZ_ERROR_MEM 2
#define SZ_ERROR_CRC 3
#define SZ_ERROR_UNSUPPORTED 4
#define SZ_ERROR_PARAM 5
#define SZ_ERROR_INPUT_EOF 6
#define SZ_ERROR_OUTPUT_EOF 7
#define SZ_ERROR_READ 8
#define SZ_ERROR_WRITE 9
#define SZ_ERROR_PROGRESS 10
#define SZ_ERROR_FAIL 11
#define SZ_ERROR_THREAD 12
#define SZ_ERROR_ARCHIVE 16
#define SZ_ERROR_NO_ARCHIVE 17
typedef int SRes;
#ifdef _WIN32
typedef DWORD WRes;
#else
typedef int WRes;
#endif
#ifndef RINOK
#define RINOK(x) \
{ \
int __result__ = (x); \
if (__result__ != 0) \
return __result__; \
}
#endif
typedef unsigned char Byte;
typedef short Int16;
typedef unsigned short UInt16;
#ifdef _LZMA_UINT32_IS_ULONG
typedef long Int32;
typedef unsigned long UInt32;
#else
typedef int Int32;
typedef unsigned int UInt32;
#endif
#ifdef _SZ_NO_INT_64
/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers.
NOTES: Some code will work incorrectly in that case! */
typedef long Int64;
typedef unsigned long UInt64;
#else
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#define UINT64_CONST(n) n
#else
typedef long long int Int64;
typedef unsigned long long int UInt64;
#define UINT64_CONST(n) n##ULL
#endif
#endif
#ifdef _LZMA_NO_SYSTEM_SIZE_T
typedef UInt32 SizeT;
#else
typedef size_t SizeT;
#endif
typedef int Bool;
#define True 1
#define False 0
#ifdef _WIN32
#define MY_STD_CALL __stdcall
#else
#define MY_STD_CALL
#endif
#ifdef _MSC_VER
#if _MSC_VER >= 1300
#define MY_NO_INLINE __declspec(noinline)
#else
#define MY_NO_INLINE
#endif
#define MY_CDECL __cdecl
#define MY_FAST_CALL __fastcall
#else
#define MY_CDECL
#define MY_FAST_CALL
#endif
/* The following interfaces use first parameter as pointer to structure */
typedef struct
{
Byte (*Read)(void* p); /* reads one byte, returns 0 in case of EOF or error */
} IByteIn;
typedef struct
{
void (*Write)(void* p, Byte b);
} IByteOut;
typedef struct
{
SRes (*Read)(void* p, void* buf, size_t* size);
/* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
(output(*size) < input(*size)) is allowed */
} ISeqInStream;
/* it can return SZ_ERROR_INPUT_EOF */
SRes SeqInStream_Read(ISeqInStream* stream, void* buf, size_t size);
SRes SeqInStream_Read2(ISeqInStream* stream, void* buf, size_t size, SRes errorType);
SRes SeqInStream_ReadByte(ISeqInStream* stream, Byte* buf);
typedef struct
{
size_t (*Write)(void* p, const void* buf, size_t size);
/* Returns: result - the number of actually written bytes.
(result < size) means error */
} ISeqOutStream;
typedef enum {
SZ_SEEK_SET = 0,
SZ_SEEK_CUR = 1,
SZ_SEEK_END = 2
} ESzSeek;
typedef struct
{
SRes (*Read)(void* p, void* buf, size_t* size); /* same as ISeqInStream::Read */
SRes (*Seek)(void* p, Int64* pos, ESzSeek origin);
} ISeekInStream;
typedef struct
{
SRes (*Look)(void* p, const void** buf, size_t* size);
/* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
(output(*size) > input(*size)) is not allowed
(output(*size) < input(*size)) is allowed */
SRes (*Skip)(void* p, size_t offset);
/* offset must be <= output(*size) of Look */
SRes (*Read)(void* p, void* buf, size_t* size);
/* reads directly (without buffer). It's same as ISeqInStream::Read */
SRes (*Seek)(void* p, Int64* pos, ESzSeek origin);
} ILookInStream;
SRes LookInStream_LookRead(ILookInStream* stream, void* buf, size_t* size);
SRes LookInStream_SeekTo(ILookInStream* stream, UInt64 offset);
/* reads via ILookInStream::Read */
SRes LookInStream_Read2(ILookInStream* stream, void* buf, size_t size, SRes errorType);
SRes LookInStream_Read(ILookInStream* stream, void* buf, size_t size);
#define LookToRead_BUF_SIZE (1 << 14)
typedef struct
{
ILookInStream s;
ISeekInStream* realStream;
size_t pos;
size_t size;
Byte buf[LookToRead_BUF_SIZE];
} CLookToRead;
void LookToRead_CreateVTable(CLookToRead* p, int lookahead);
void LookToRead_Init(CLookToRead* p);
typedef struct
{
ISeqInStream s;
ILookInStream* realStream;
} CSecToLook;
void SecToLook_CreateVTable(CSecToLook* p);
typedef struct
{
ISeqInStream s;
ILookInStream* realStream;
} CSecToRead;
void SecToRead_CreateVTable(CSecToRead* p);
typedef struct
{
SRes (*Progress)(void* p, UInt64 inSize, UInt64 outSize);
/* Returns: result. (result != SZ_OK) means break.
Value (UInt64)(Int64)-1 for size means unknown value. */
} ICompressProgress;
typedef struct
{
void* (*Alloc)(void* p, size_t size);
void (*Free)(void* p, void* address); /* address can be 0 */
} ISzAlloc;
#define IAlloc_Alloc(p, size) (p)->Alloc((p), size)
#define IAlloc_Free(p, a) (p)->Free((p), a)
#ifdef _WIN32
#define CHAR_PATH_SEPARATOR '\\'
#define WCHAR_PATH_SEPARATOR L'\\'
#define STRING_PATH_SEPARATOR "\\"
#define WSTRING_PATH_SEPARATOR L"\\"
#else
#define CHAR_PATH_SEPARATOR '/'
#define WCHAR_PATH_SEPARATOR L'/'
#define STRING_PATH_SEPARATOR "/"
#define WSTRING_PATH_SEPARATOR L"/"
#endif
EXTERN_C_END
#endif

Some files were not shown because too many files have changed in this diff Show More