diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..2d31f95 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "fake-cli": { + "version": "5.19.0", + "commands": [ + "fake" + ] + } + } +} \ No newline at end of file diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 1ff0c42..0000000 --- a/.gitattributes +++ /dev/null @@ -1,63 +0,0 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### -* text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore index 593f090..f7b314d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,66 +1,10 @@ - -# Created by https://www.gitignore.io/api/vim,osx,linux,macos,emacs,fsharp,csharp,windows,android,monodevelop,intellij+all,visualstudio,xamarinstudio,visualstudiocode - -### Android ### -# Built application files -*.apk -*.ap_ - -# Files for the ART/Dalvik VM -*.dex - -# Java class files -*.class - -# Generated files -bin/ -gen/ -out/ - -# Gradle files -.gradle/ - -# Local configuration file (sdk path, etc) -local.properties - -# Proguard folder generated by Eclipse -proguard/ - -# Log Files -*.log - -# Android Studio Navigation editor temp files -.navigation/ - -# Android Studio captures folder -captures/ - -# Intellij -*.iml -.idea/workspace.xml -.idea/tasks.xml -.idea/gradle.xml -.idea/dictionaries -.idea/libraries - -# External native build folder generated in Android Studio 2.2 and later -.externalNativeBuild - -# Freeline -freeline.py -freeline/ -freeline_project_description.json - -### Android Patch ### -gen-external-apklibs - -### Csharp ### ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files +*.rsuser *.suo *.user *.userosscache @@ -69,6 +13,9 @@ gen-external-apklibs # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# Mono auto generated files +mono_crash.* + # Build results [Dd]ebug/ [Dd]ebugPublic/ @@ -76,43 +23,62 @@ gen-external-apklibs [Rr]eleases/ x64/ x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ +[Ll]ogs/ -# Visual Studio 2015 cache/options directory +# Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ +# Visual Studio 2017 auto generated files +Generated\ Files/ + # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* -# NUNIT +# NUnit *.VisualState.xml TestResult.xml +nunit-*.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c +# Benchmark Results +BenchmarkDotNet.Artifacts/ + # .NET Core project.lock.json project.fragment.lock.json artifacts/ -**/Properties/launchSettings.json +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio *_i.c *_p.c -*_i.h +*_h.h *.ilk *.meta *.obj +*.iobj *.pch *.pdb +*.ipdb *.pgc *.pgd *.rsp @@ -122,6 +88,8 @@ artifacts/ *.tlh *.tmp *.tmp_proj +*_wpftmp.csproj +*.log *.vspscc *.vssscc .builds @@ -149,6 +117,9 @@ ipch/ *.vspx *.sap +# Visual Studio Trace Files +*.e2e + # TFS 2012 Local Workspace $tf/ @@ -160,15 +131,21 @@ _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user -# JustCode is a .NET coding add-in -.JustCode - # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + # Visual Studio code coverage results *.coverage *.coveragexml @@ -204,11 +181,9 @@ publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml -# TODO: Uncomment the next line to ignore your web deploy settings. -# By default, sensitive information, such as encrypted password -# should be stored in the .pubxml.user file. -#*.pubxml -*.pubxml.user +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to @@ -218,12 +193,14 @@ PublishScripts/ # NuGet Packages *.nupkg +# NuGet Symbol Packages +*.snupkg # The packages folder can be ignored because of Package Restore -**/packages/* +**/[Pp]ackages/* # except build/, which is used as an MSBuild target. -!**/packages/build/ +!**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config +#!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets @@ -241,12 +218,15 @@ AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt +*.appx +*.appxbundle +*.appxupload # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache -!*.[Cc]ache/ +!?*.[Cc]ache/ # Others ClientBin/ @@ -259,6 +239,10 @@ ClientBin/ *.publishsettings orleans.codegen.cs +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ @@ -273,6 +257,8 @@ _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak # SQL Server files *.mdf @@ -283,6 +269,10 @@ UpgradeLog*.htm *.rdl.data *.bim.layout *.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl # Microsoft Fakes FakesAssemblies/ @@ -294,9 +284,6 @@ FakesAssemblies/ .ntvs_analysis.dat node_modules/ -# Typescript v1 declaration files -typings/ - # Visual Studio 6 build log *.plg @@ -317,17 +304,12 @@ _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ -*.Restore.targets # FAKE - F# Make .fake/ -# JetBrains Rider -.idea/ -*.sln.iml - -# CodeRush -.cr/ +# CodeRush personal settings +.cr/personal # Python Tools for Visual Studio (PTVS) __pycache__/ @@ -337,6 +319,9 @@ __pycache__/ # tools/** # !tools/packages.config +# Tabs Studio +*.tss + # Telerik's JustMock configuration file *.jmconfig @@ -346,492 +331,36 @@ __pycache__/ *.odx.cs *.xsd.cs -### Emacs ### -# -*- mode: gitignore; -*- -\#*\# -/.emacs.desktop -/.emacs.desktop.lock -*.elc -auto-save-list -tramp -.\#* - -# Org-mode -.org-id-locations -*_archive - -# flymake-mode -*_flymake.* - -# eshell files -/eshell/history -/eshell/lastdir - -# elpa packages -/elpa/ - -# reftex files -*.rel - -# AUCTeX auto folder -/auto/ - -# cask packages -.cask/ -dist/ - -# Flycheck -flycheck_*.el - -# server auth directory -/server/ - -# projectiles files -.projectile -projectile-bookmarks.eld - -# directory configuration -.dir-locals.el - -# saveplace -places - -# url cache -url/cache/ - -# cedet -ede-projects.el - -# smex -smex-items - -# company-statistics -company-statistics-cache.el - -# anaconda-mode -anaconda-mode/ - -### fsharp ### -lib/debug -lib/release -*.exe -!.paket/paket.bootstrapper.exe - -### Intellij+all ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff: -.idea/**/workspace.xml -.idea/**/tasks.xml - -# Sensitive or high-churn files: -.idea/**/dataSources/ -.idea/**/dataSources.ids -.idea/**/dataSources.xml -.idea/**/dataSources.local.xml -.idea/**/sqlDataSources.xml -.idea/**/dynamic.xml -.idea/**/uiDesigner.xml - -# Gradle: -.idea/**/gradle.xml -.idea/**/libraries - -# CMake -cmake-build-debug/ - -# Mongo Explorer plugin: -.idea/**/mongoSettings.xml - -## File-based project format: -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Cursive Clojure plugin -.idea/replstate.xml - -# Ruby plugin and RubyMine -/.rakeTasks - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -### Linux ### - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* - -# .nfs files are created when an open file is removed but is still being accessed -.nfs* - -### macOS ### -*.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -### MonoDevelop ### -#User Specific -*.usertasks - -#Mono Project Files -*.resources -test-results/ - -### OSX ### - -# Icon must end with two \r - -# Thumbnails - -# Files that might appear in the root of a volume - -# Directories potentially created on remote AFP share - -### Vim ### -# swap -[._]*.s[a-v][a-z] -[._]*.sw[a-p] -[._]s[a-v][a-z] -[._]sw[a-p] -# session -Session.vim -# temporary -.netrwhist -# auto-generated tag files -tags - -### VisualStudioCode ### -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -.history - -### Windows ### -# Windows thumbnail cache files -Thumbs.db -ehthumbs.db -ehthumbs_vista.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp - -# Windows shortcuts -*.lnk - -### XamarinStudio ### -.packages - -### Mono Code Coverage ### -TestResults.xml - -### OpenTK Binding files ### -.bindingsGenerated -src/OpenTK/Graphics/ES10/Enums -src/OpenTK/Graphics/ES10/Wrappers -src/OpenTK/Graphics/ES11/Enums -src/OpenTK/Graphics/ES11/Wrappers -src/OpenTK/Graphics/ES20/Enums -src/OpenTK/Graphics/ES20/Wrappers -src/OpenTK/Graphics/ES30/Enums -src/OpenTK/Graphics/ES30/Wrappers -src/OpenTK/Graphics/ES31/Enums -src/OpenTK/Graphics/ES31/Wrappers -src/OpenTK/Graphics/OpenGL/Enums -src/OpenTK/Graphics/OpenGL/Wrappers -src/OpenTK/Graphics/OpenGL4/Enums -src/OpenTK/Graphics/OpenGL4/Wrappers - -### OpenTK AssemblyInfo files ### -**/AssemblyInfo.cs -**/AssemblyInfo.fs - -### Tooling files "" -tools/ - -### LaTeX ### -## Core latex/pdflatex auxiliary files: -*.aux -*.lof -*.lot -*.fls -*.out -*.toc -*.fmt -*.fot -*.cb -*.cb2 -.*.lb - -## Intermediate documents: -*.dvi -*.xdv -*-converted-to.* -# these rules might exclude image files for figures etc. -# *.ps -# *.eps -# *.pdf - -## Generated if empty string is given at "Please type another file name for output:" -.pdf - -## Bibliography auxiliary files (bibtex/biblatex/biber): -*.bbl -*.bcf -*.blg -*-blx.aux -*-blx.bib -*.run.xml - -## Build tool auxiliary files: -*.fdb_latexmk -*.synctex -*.synctex(busy) -*.synctex.gz -*.synctex.gz(busy) -*.pdfsync - -## Build tool directories for auxiliary files -# latexrun -latex.out/ - -## Auxiliary and intermediate files from other packages: -# algorithms -*.alg -*.loa - -# achemso -acs-*.bib - -# amsthm -*.thm - -# beamer -*.nav -*.pre -*.snm -*.vrb - -# changes -*.soc - -# cprotect -*.cpt - -# elsarticle (documentclass of Elsevier journals) -*.spl - -# endnotes -*.ent - -# fixme -*.lox - -# feynmf/feynmp -*.mf -*.mp -*.t[1-9] -*.t[1-9][0-9] -*.tfm - -# glossaries -*.acn -*.acr -*.glg -*.glo -*.gls -*.glsdefs - -# gnuplottex -*-gnuplottex-* - -# gregoriotex -*.gaux -*.gtex - -# htlatex -*.4ct -*.4tc -*.idv -*.lg -*.trc -*.xref - -# hyperref -*.brf - -# knitr -*-concordance.tex -# TODO Comment the next line if you want to keep your tikz graphics files -*.tikz -*-tikzDictionary - -# listings -*.lol - -# makeidx -*.idx -*.ilg -*.ind -*.ist - -# minitoc -*.maf -*.mlf -*.mlt -*.mtc[0-9]* -*.slf[0-9]* -*.slt[0-9]* -*.stc[0-9]* - -# minted -_minted* -*.pyg - -# morewrites -*.mw - -# nomencl -*.nlg -*.nlo -*.nls - -# pax -*.pax - -# pdfpcnotes -*.pdfpc - -# sagetex -*.sagetex.sage -*.sagetex.py -*.sagetex.scmd - -# scrwfile -*.wrt - -# sympy -*.sout -*.sympy -sympy-plots-for-*.tex/ - -# pdfcomment -*.upa -*.upb - -# pythontex -*.pytxcode -pythontex-files-*/ - -# thmtools -*.loe - -# TikZ & PGF -*.dpth -*.md5 -*.auxlock - -# todonotes -*.tdo - -# easy-todo -*.lod - -# xmpincl -*.xmpi - -# xindy -*.xdy - -# xypic precompiled matrices -*.xyc - -# endfloat -*.ttt -*.fff +# OpenCover UI analysis results +OpenCover/ -# Latexian -TSWLatexianTemp* +# Azure Stream Analytics local run output +ASALocalRun/ -## Editors: -# WinEdt -*.bak -*.sav +# MSBuild Binary and Structured Log +*.binlog -# Texpad -.texpadtmp +# NVidia Nsight GPU debugger configuration file +*.nvuser -# LyX -*.lyx~ +# MFractors (Xamarin productivity tool) working folder +.mfractor/ -# Kile -*.backup +# Local History for Visual Studio +.localhistory/ -# KBibTeX -*~[0-9]* +# BeatPulse healthcheck temp database +healthchecksdb -# auto folder when using emacs and auctex -auto/* -*.el +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ -# expex forward references with \gathertags -*-tags.tex +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ -# standalone packages -*.sta +# Fody - auto-generated XML schema +FodyWeavers.xsd +.idea -### LaTeX Patch ### -# glossaries -*.glstex +# packet.template files are autogenerated +paket.template diff --git a/.paket/Paket.Restore.targets b/.paket/Paket.Restore.targets new file mode 100644 index 0000000..072e852 --- /dev/null +++ b/.paket/Paket.Restore.targets @@ -0,0 +1,276 @@ +<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <!-- Prevent dotnet template engine to parse this file --> + <!--/-:cnd:noEmit--> + <PropertyGroup> + <!-- make MSBuild track this file for incremental builds. --> + <!-- ref https://blogs.msdn.microsoft.com/msbuild/2005/09/26/how-to-ensure-changes-to-a-custom-target-file-prompt-a-rebuild/ --> + <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> + <!-- Mark that this target file has been loaded. --> + <IsPaketRestoreTargetsFileLoaded>true</IsPaketRestoreTargetsFileLoaded> + <PaketToolsPath>$(MSBuildThisFileDirectory)</PaketToolsPath> + <PaketRootPath>$(MSBuildThisFileDirectory)..\</PaketRootPath> + <PaketRestoreCacheFile>$(PaketRootPath)paket-files\paket.restore.cached</PaketRestoreCacheFile> + <PaketLockFilePath>$(PaketRootPath)paket.lock</PaketLockFilePath> + <MonoPath Condition="'$(MonoPath)' == '' And Exists('/Library/Frameworks/Mono.framework/Commands/mono')">/Library/Frameworks/Mono.framework/Commands/mono</MonoPath> + <MonoPath Condition="'$(MonoPath)' == ''">mono</MonoPath> + <!-- Paket command --> + <PaketExePath Condition=" '$(PaketExePath)' == '' AND Exists('$(PaketRootPath)paket.exe')">$(PaketRootPath)paket.exe</PaketExePath> + <PaketExePath Condition=" '$(PaketExePath)' == '' ">$(PaketToolsPath)paket.exe</PaketExePath> + <PaketCommand Condition=" '$(OS)' == 'Windows_NT'">"$(PaketExePath)"</PaketCommand> + <PaketCommand Condition=" '$(OS)' != 'Windows_NT' ">$(MonoPath) --runtime=v4.0.30319 "$(PaketExePath)"</PaketCommand> + + <!-- .net core fdd --> + <_PaketExeExtension>$([System.IO.Path]::GetExtension("$(PaketExePath)"))</_PaketExeExtension> + <PaketCommand Condition=" '$(_PaketExeExtension)' == '.dll' ">dotnet "$(PaketExePath)"</PaketCommand> + + <!-- no extension is a shell script --> + <PaketCommand Condition=" '$(_PaketExeExtension)' == '' ">"$(PaketExePath)"</PaketCommand> + + <PaketBootStrapperExePath Condition=" '$(PaketBootStrapperExePath)' == '' AND Exists('$(PaketRootPath)paket.bootstrapper.exe')">$(PaketRootPath)paket.bootstrapper.exe</PaketBootStrapperExePath> + <PaketBootStrapperExePath Condition=" '$(PaketBootStrapperExePath)' == '' ">$(PaketToolsPath)paket.bootstrapper.exe</PaketBootStrapperExePath> + <PaketBootStrapperCommand Condition=" '$(OS)' == 'Windows_NT'">"$(PaketBootStrapperExePath)"</PaketBootStrapperCommand> + <PaketBootStrapperCommand Condition=" '$(OS)' != 'Windows_NT' ">$(MonoPath) --runtime=v4.0.30319 "$(PaketBootStrapperExePath)"</PaketBootStrapperCommand> + + <!-- Disable automagic references for F# dotnet sdk --> + <!-- This will not do anything for other project types --> + <!-- see https://github.com/fsharp/fslang-design/blob/master/RFCs/FS-1032-fsharp-in-dotnet-sdk.md --> + <DisableImplicitFSharpCoreReference>true</DisableImplicitFSharpCoreReference> + <DisableImplicitSystemValueTupleReference>true</DisableImplicitSystemValueTupleReference> + </PropertyGroup> + + <Target Name="PaketRestore" Condition="'$(PaketRestoreDisabled)' != 'True'" BeforeTargets="_GenerateDotnetCliToolReferenceSpecs;_GenerateProjectRestoreGraphPerFramework;_GenerateRestoreGraphWalkPerFramework;CollectPackageReferences" > + + <!-- Step 1 Check if lockfile is properly restored --> + <PropertyGroup> + <PaketRestoreRequired>true</PaketRestoreRequired> + <NoWarn>$(NoWarn);NU1603</NoWarn> + </PropertyGroup> + + <!-- Because ReadAllText is slow on osx/linux, try to find shasum and awk --> + <PropertyGroup> + <PaketRestoreCachedHasher Condition="'$(OS)' != 'Windows_NT' And '$(PaketRestoreCachedHasher)' == '' And Exists('/usr/bin/shasum') And Exists('/usr/bin/awk')">/usr/bin/shasum $(PaketRestoreCacheFile) | /usr/bin/awk '{ print $1 }'</PaketRestoreCachedHasher> + <PaketRestoreLockFileHasher Condition="'$(OS)' != 'Windows_NT' And '$(PaketRestoreLockFileHash)' == '' And Exists('/usr/bin/shasum') And Exists('/usr/bin/awk')">/usr/bin/shasum $(PaketLockFilePath) | /usr/bin/awk '{ print $1 }'</PaketRestoreLockFileHasher> + </PropertyGroup> + + <!-- If shasum and awk exist get the hashes --> + <Exec Condition=" '$(PaketRestoreCachedHasher)' != '' " Command="$(PaketRestoreCachedHasher)" ConsoleToMSBuild='true'> + <Output TaskParameter="ConsoleOutput" PropertyName="PaketRestoreCachedHash" /> + </Exec> + <Exec Condition=" '$(PaketRestoreLockFileHasher)' != '' " Command="$(PaketRestoreLockFileHasher)" ConsoleToMSBuild='true'> + <Output TaskParameter="ConsoleOutput" PropertyName="PaketRestoreLockFileHash" /> + </Exec> + + <PropertyGroup Condition="Exists('$(PaketRestoreCacheFile)') "> + <!-- if no hash has been done yet fall back to just reading in the files and comparing them --> + <PaketRestoreCachedHash Condition=" '$(PaketRestoreCachedHash)' == '' ">$([System.IO.File]::ReadAllText('$(PaketRestoreCacheFile)'))</PaketRestoreCachedHash> + <PaketRestoreLockFileHash Condition=" '$(PaketRestoreLockFileHash)' == '' ">$([System.IO.File]::ReadAllText('$(PaketLockFilePath)'))</PaketRestoreLockFileHash> + <PaketRestoreRequired>true</PaketRestoreRequired> + <PaketRestoreRequired Condition=" '$(PaketRestoreLockFileHash)' == '$(PaketRestoreCachedHash)' ">false</PaketRestoreRequired> + <PaketRestoreRequired Condition=" '$(PaketRestoreLockFileHash)' == '' ">true</PaketRestoreRequired> + </PropertyGroup> + + <!-- Do a global restore if required --> + <Exec Command='$(PaketBootStrapperCommand)' Condition="Exists('$(PaketBootStrapperExePath)') AND !(Exists('$(PaketExePath)'))" ContinueOnError="false" /> + <Exec Command='$(PaketCommand) restore' Condition=" '$(PaketRestoreRequired)' == 'true' " ContinueOnError="false" /> + + <!-- Step 2 Detect project specific changes --> + <PropertyGroup> + <PaketReferencesCachedFilePath>$(MSBuildProjectDirectory)\obj\$(MSBuildProjectFile).paket.references.cached</PaketReferencesCachedFilePath> + <!-- MyProject.fsproj.paket.references has the highest precedence --> + <PaketOriginalReferencesFilePath>$(MSBuildProjectFullPath).paket.references</PaketOriginalReferencesFilePath> + <!-- MyProject.paket.references --> + <PaketOriginalReferencesFilePath Condition=" !Exists('$(PaketOriginalReferencesFilePath)')">$(MSBuildProjectDirectory)\$(MSBuildProjectName).paket.references</PaketOriginalReferencesFilePath> + <!-- paket.references --> + <PaketOriginalReferencesFilePath Condition=" !Exists('$(PaketOriginalReferencesFilePath)')">$(MSBuildProjectDirectory)\paket.references</PaketOriginalReferencesFilePath> + <PaketResolvedFilePath>$(MSBuildProjectDirectory)\obj\$(MSBuildProjectFile).$(TargetFramework).paket.resolved</PaketResolvedFilePath> + <PaketRestoreRequired>true</PaketRestoreRequired> + <PaketRestoreRequiredReason>references-file-or-cache-not-found</PaketRestoreRequiredReason> + </PropertyGroup> + + <!-- Step 2 a Detect changes in references file --> + <PropertyGroup Condition="Exists('$(PaketOriginalReferencesFilePath)') AND Exists('$(PaketReferencesCachedFilePath)') "> + <PaketRestoreCachedHash>$([System.IO.File]::ReadAllText('$(PaketReferencesCachedFilePath)'))</PaketRestoreCachedHash> + <PaketRestoreReferencesFileHash>$([System.IO.File]::ReadAllText('$(PaketOriginalReferencesFilePath)'))</PaketRestoreReferencesFileHash> + <PaketRestoreRequiredReason>references-file</PaketRestoreRequiredReason> + <PaketRestoreRequired Condition=" '$(PaketRestoreReferencesFileHash)' == '$(PaketRestoreCachedHash)' ">false</PaketRestoreRequired> + </PropertyGroup> + + <PropertyGroup Condition="!Exists('$(PaketOriginalReferencesFilePath)') AND !Exists('$(PaketReferencesCachedFilePath)') "> + <!-- If both don't exist there is nothing to do. --> + <PaketRestoreRequired>false</PaketRestoreRequired> + </PropertyGroup> + + <!-- Step 2 b detect relevant changes in project file (new targetframework) --> + <PropertyGroup Condition=" !Exists('$(PaketResolvedFilePath)') AND '$(TargetFramework)' != '' "> + <PaketRestoreRequired>true</PaketRestoreRequired> + <PaketRestoreRequiredReason>target-framework '$(TargetFramework)'</PaketRestoreRequiredReason> + </PropertyGroup> + + <!-- Step 3 Restore project specific stuff if required --> + <Message Condition=" '$(PaketRestoreRequired)' == 'true' " Importance="low" Text="Detected a change ('$(PaketRestoreRequiredReason)') in the project file '$(MSBuildProjectFullPath)', calling paket restore" /> + <Exec Command='$(PaketCommand) restore --project "$(MSBuildProjectFullPath)"' Condition=" '$(PaketRestoreRequired)' == 'true' " ContinueOnError="false" /> + + <!-- This shouldn't actually happen, but just to be sure. --> + <Error Condition=" !Exists('$(PaketResolvedFilePath)') AND '$(TargetFramework)' != '' AND '$(ResolveNuGetPackages)' != 'False' " Text="Paket file '$(PaketResolvedFilePath)' is missing while restoring $(MSBuildProjectFile). Please delete 'paket-files/paket.restore.cached' and call 'paket restore'." /> + + <!-- Step 4 forward all msbuild properties (PackageReference, DotNetCliToolReference) to msbuild --> + <ReadLinesFromFile Condition="Exists('$(PaketResolvedFilePath)')" File="$(PaketResolvedFilePath)" > + <Output TaskParameter="Lines" ItemName="PaketReferencesFileLines"/> + </ReadLinesFromFile> + + <ItemGroup Condition=" Exists('$(PaketResolvedFilePath)') AND '@(PaketReferencesFileLines)' != '' " > + <PaketReferencesFileLinesInfo Include="@(PaketReferencesFileLines)" > + <PackageName>$([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',')[0])</PackageName> + <PackageVersion>$([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',')[1])</PackageVersion> + <AllPrivateAssets>$([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',')[4])</AllPrivateAssets> + </PaketReferencesFileLinesInfo> + <PackageReference Include="%(PaketReferencesFileLinesInfo.PackageName)"> + <Version>%(PaketReferencesFileLinesInfo.PackageVersion)</Version> + <PrivateAssets Condition="%(PaketReferencesFileLinesInfo.AllPrivateAssets) == 'true'">All</PrivateAssets> + </PackageReference> + </ItemGroup> + + <PropertyGroup> + <PaketCliToolFilePath>$(MSBuildProjectDirectory)/obj/$(MSBuildProjectFile).paket.clitools</PaketCliToolFilePath> + </PropertyGroup> + + <ReadLinesFromFile File="$(PaketCliToolFilePath)" > + <Output TaskParameter="Lines" ItemName="PaketCliToolFileLines"/> + </ReadLinesFromFile> + + <ItemGroup Condition=" '@(PaketCliToolFileLines)' != '' " > + <PaketCliToolFileLinesInfo Include="@(PaketCliToolFileLines)" > + <PackageName>$([System.String]::Copy('%(PaketCliToolFileLines.Identity)').Split(',')[0])</PackageName> + <PackageVersion>$([System.String]::Copy('%(PaketCliToolFileLines.Identity)').Split(',')[1])</PackageVersion> + </PaketCliToolFileLinesInfo> + <DotNetCliToolReference Include="%(PaketCliToolFileLinesInfo.PackageName)"> + <Version>%(PaketCliToolFileLinesInfo.PackageVersion)</Version> + </DotNetCliToolReference> + </ItemGroup> + + <!-- Disabled for now until we know what to do with runtime deps - https://github.com/fsprojects/Paket/issues/2964 + <PropertyGroup> + <RestoreConfigFile>$(MSBuildProjectDirectory)/obj/$(MSBuildProjectFile).NuGet.Config</RestoreConfigFile> + </PropertyGroup> --> + + </Target> + + <Target Name="PaketDisableDirectPack" AfterTargets="_IntermediatePack" BeforeTargets="GenerateNuspec" Condition="('$(IsPackable)' == '' Or '$(IsPackable)' == 'true') And Exists('$(MSBuildProjectDirectory)/obj/$(MSBuildProjectFile).references')" > + <PropertyGroup> + <ContinuePackingAfterGeneratingNuspec>false</ContinuePackingAfterGeneratingNuspec> + </PropertyGroup> + </Target> + + <Target Name="PaketOverrideNuspec" AfterTargets="GenerateNuspec" Condition="('$(IsPackable)' == '' Or '$(IsPackable)' == 'true') And Exists('$(MSBuildProjectDirectory)/obj/$(MSBuildProjectFile).references')" > + <ItemGroup> + <_NuspecFilesNewLocation Include="$(BaseIntermediateOutputPath)$(Configuration)\*.nuspec"/> + </ItemGroup> + + <PropertyGroup> + <PaketProjectFile>$(MSBuildProjectDirectory)/$(MSBuildProjectFile)</PaketProjectFile> + <ContinuePackingAfterGeneratingNuspec>true</ContinuePackingAfterGeneratingNuspec> + <UseNewPack>false</UseNewPack> + <UseNewPack Condition=" '$(NuGetToolVersion)' != '4.0.0' ">true</UseNewPack> + <AdjustedNuspecOutputPath>$(BaseIntermediateOutputPath)$(Configuration)</AdjustedNuspecOutputPath> + <AdjustedNuspecOutputPath Condition="@(_NuspecFilesNewLocation) == ''">$(BaseIntermediateOutputPath)</AdjustedNuspecOutputPath> + </PropertyGroup> + + <ItemGroup> + <_NuspecFiles Include="$(AdjustedNuspecOutputPath)\*.nuspec"/> + </ItemGroup> + + <Exec Command='$(PaketCommand) fix-nuspecs files "@(_NuspecFiles)" project-file "$(PaketProjectFile)" ' Condition="@(_NuspecFiles) != ''" /> + + <ConvertToAbsolutePath Condition="@(_NuspecFiles) != ''" Paths="@(_NuspecFiles)"> + <Output TaskParameter="AbsolutePaths" PropertyName="NuspecFileAbsolutePath" /> + </ConvertToAbsolutePath> + + + <!-- Call Pack --> + <PackTask Condition="$(UseNewPack)" + PackItem="$(PackProjectInputFile)" + PackageFiles="@(_PackageFiles)" + PackageFilesToExclude="@(_PackageFilesToExclude)" + PackageVersion="$(PackageVersion)" + PackageId="$(PackageId)" + Title="$(Title)" + Authors="$(Authors)" + Description="$(Description)" + Copyright="$(Copyright)" + RequireLicenseAcceptance="$(PackageRequireLicenseAcceptance)" + LicenseUrl="$(PackageLicenseUrl)" + ProjectUrl="$(PackageProjectUrl)" + IconUrl="$(PackageIconUrl)" + ReleaseNotes="$(PackageReleaseNotes)" + Tags="$(PackageTags)" + DevelopmentDependency="$(DevelopmentDependency)" + BuildOutputInPackage="@(_BuildOutputInPackage)" + TargetPathsToSymbols="@(_TargetPathsToSymbols)" + TargetFrameworks="@(_TargetFrameworks)" + AssemblyName="$(AssemblyName)" + PackageOutputPath="$(PackageOutputAbsolutePath)" + IncludeSymbols="$(IncludeSymbols)" + IncludeSource="$(IncludeSource)" + PackageTypes="$(PackageType)" + IsTool="$(IsTool)" + RepositoryUrl="$(RepositoryUrl)" + RepositoryType="$(RepositoryType)" + SourceFiles="@(_SourceFiles->Distinct())" + NoPackageAnalysis="$(NoPackageAnalysis)" + MinClientVersion="$(MinClientVersion)" + Serviceable="$(Serviceable)" + FrameworkAssemblyReferences="@(_FrameworkAssemblyReferences)" + ContinuePackingAfterGeneratingNuspec="$(ContinuePackingAfterGeneratingNuspec)" + NuspecOutputPath="$(AdjustedNuspecOutputPath)" + IncludeBuildOutput="$(IncludeBuildOutput)" + BuildOutputFolder="$(BuildOutputTargetFolder)" + ContentTargetFolders="$(ContentTargetFolders)" + RestoreOutputPath="$(RestoreOutputAbsolutePath)" + NuspecFile="$(NuspecFileAbsolutePath)" + NuspecBasePath="$(NuspecBasePath)" + NuspecProperties="$(NuspecProperties)"/> + + <PackTask Condition="! $(UseNewPack)" + PackItem="$(PackProjectInputFile)" + PackageFiles="@(_PackageFiles)" + PackageFilesToExclude="@(_PackageFilesToExclude)" + PackageVersion="$(PackageVersion)" + PackageId="$(PackageId)" + Title="$(Title)" + Authors="$(Authors)" + Description="$(Description)" + Copyright="$(Copyright)" + RequireLicenseAcceptance="$(PackageRequireLicenseAcceptance)" + LicenseUrl="$(PackageLicenseUrl)" + ProjectUrl="$(PackageProjectUrl)" + IconUrl="$(PackageIconUrl)" + ReleaseNotes="$(PackageReleaseNotes)" + Tags="$(PackageTags)" + TargetPathsToAssemblies="@(_TargetPathsToAssemblies->'%(FinalOutputPath)')" + TargetPathsToSymbols="@(_TargetPathsToSymbols)" + TargetFrameworks="@(_TargetFrameworks)" + AssemblyName="$(AssemblyName)" + PackageOutputPath="$(PackageOutputAbsolutePath)" + IncludeSymbols="$(IncludeSymbols)" + IncludeSource="$(IncludeSource)" + PackageTypes="$(PackageType)" + IsTool="$(IsTool)" + RepositoryUrl="$(RepositoryUrl)" + RepositoryType="$(RepositoryType)" + SourceFiles="@(_SourceFiles->Distinct())" + NoPackageAnalysis="$(NoPackageAnalysis)" + MinClientVersion="$(MinClientVersion)" + Serviceable="$(Serviceable)" + AssemblyReferences="@(_References)" + ContinuePackingAfterGeneratingNuspec="$(ContinuePackingAfterGeneratingNuspec)" + NuspecOutputPath="$(AdjustedNuspecOutputPath)" + IncludeBuildOutput="$(IncludeBuildOutput)" + BuildOutputFolder="$(BuildOutputTargetFolder)" + ContentTargetFolders="$(ContentTargetFolders)" + RestoreOutputPath="$(RestoreOutputAbsolutePath)" + NuspecFile="$(NuspecFileAbsolutePath)" + NuspecBasePath="$(NuspecBasePath)" + NuspecProperties="$(NuspecProperties)"/> + </Target> + <!--/+:cnd:noEmit--> +</Project> diff --git a/.paket/paket.bootstrapper.exe b/.paket/paket.bootstrapper.exe new file mode 100644 index 0000000..81df15f Binary files /dev/null and b/.paket/paket.bootstrapper.exe differ diff --git a/.paket/paket.targets b/.paket/paket.targets new file mode 100644 index 0000000..ad11fac --- /dev/null +++ b/.paket/paket.targets @@ -0,0 +1,130 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + + <PropertyGroup> + <!-- Enable the restore command to run before builds --> + <RestorePackages Condition=" '$(RestorePackages)' == '' ">true</RestorePackages> + <PaketToolsPath>$(MSBuildThisFileDirectory)</PaketToolsPath> + <PaketRootPath>$(MSBuildThisFileDirectory)..\</PaketRootPath> + <PaketLockFilePath>$(PaketRootPath)paket.lock</PaketLockFilePath> + <PaketRestoreCacheFile>$(PaketRootPath)paket-files\paket.restore.cached</PaketRestoreCacheFile> + <MonoPath Condition="'$(MonoPath)' == '' And Exists('/Library/Frameworks/Mono.framework/Commands/mono')">/Library/Frameworks/Mono.framework/Commands/mono</MonoPath> + <MonoPath Condition="'$(MonoPath)' == ''">mono</MonoPath> + + <!-- Disable test for CLI tool completely - overrideable via properties in projects or via environment variables --> + <PaketDisableCliTest Condition=" '$(PaketDisableCliTest)' == '' ">False</PaketDisableCliTest> + </PropertyGroup> + + <!-- Resolve how paket should be called --> + <!-- Current priority is: local (1: repo root, 2: .paket folder) => 3: as CLI tool => as bootstrapper (4: proj Bootstrapper style, 5: BootstrapperExeDir) => 6: global path variable --> + <Target Name="SetPaketCommand" > + <!-- Test if paket is available in the standard locations. If so, that takes priority. Case 1/2 - non-windows specific --> + <PropertyGroup Condition=" '$(OS)' != 'Windows_NT' "> + <!-- no windows, try native paket as default, root => tool --> + <PaketExePath Condition=" '$(PaketExePath)' == '' AND Exists('$(PaketRootPath)paket') ">$(PaketRootPath)paket</PaketExePath> + <PaketExePath Condition=" '$(PaketExePath)' == '' AND Exists('$(PaketToolsPath)paket') ">$(PaketToolsPath)paket</PaketExePath> + </PropertyGroup> + + <!-- Test if paket is available in the standard locations. If so, that takes priority. Case 2/2 - same across platforms --> + <PropertyGroup> + <!-- root => tool --> + <PaketExePath Condition=" '$(PaketExePath)' == '' AND Exists('$(PaketRootPath)paket.exe') ">$(PaketRootPath)paket.exe</PaketExePath> + <PaketExePath Condition=" '$(PaketExePath)' == '' AND Exists('$(PaketToolsPath)paket.exe') ">$(PaketToolsPath)paket.exe</PaketExePath> + </PropertyGroup> + + <!-- If paket hasn't be found in standard locations, test for CLI tool usage. --> + <!-- First test: Is CLI configured to be used in "dotnet-tools.json"? - can result in a false negative; only a positive outcome is reliable. --> + <PropertyGroup Condition=" '$(PaketExePath)' == '' "> + <_DotnetToolsJson Condition="Exists('$(PaketRootPath)/.config/dotnet-tools.json')">$([System.IO.File]::ReadAllText("$(PaketRootPath)/.config/dotnet-tools.json"))</_DotnetToolsJson> + <_ConfigContainsPaket Condition=" '$(_DotnetToolsJson)' != ''">$(_DotnetToolsJson.Contains('"paket"'))</_ConfigContainsPaket> + <_ConfigContainsPaket Condition=" '$(_ConfigContainsPaket)' == ''">false</_ConfigContainsPaket> + </PropertyGroup> + + <!-- Second test: Call 'dotnet paket' and see if it returns without an error. Mute all the output. Only run if previous test failed and the test has not been disabled. --> + <!-- WARNING: This method can lead to processes hanging forever, and should be used as little as possible. See https://github.com/fsprojects/Paket/issues/3705 for details. --> + <Exec Condition=" '$(PaketExePath)' == '' AND !$(PaketDisableCliTest) AND !$(_ConfigContainsPaket)" Command="dotnet paket --version" IgnoreExitCode="true" StandardOutputImportance="low" StandardErrorImportance="low" > + <Output TaskParameter="ExitCode" PropertyName="LocalPaketToolExitCode" /> + </Exec> + + <!-- If paket is installed as CLI use that. Again, only if paket haven't already been found in standard locations. --> + <PropertyGroup Condition=" '$(PaketExePath)' == '' AND ($(_ConfigContainsPaket) OR '$(LocalPaketToolExitCode)' == '0') "> + <_PaketCommand>dotnet paket</_PaketCommand> + </PropertyGroup> + + <!-- If neither local files nor CLI tool can be found, final attempt is searching for boostrapper config before falling back to global path variable. --> + <PropertyGroup Condition=" '$(PaketExePath)' == '' AND '$(_PaketCommand)' == '' "> + <!-- Test for bootstrapper setup --> + <PaketExePath Condition=" '$(PaketExePath)' == '' AND '$(PaketBootstrapperStyle)' == 'proj' ">$(PaketToolsPath)paket</PaketExePath> + <PaketExePath Condition=" '$(PaketExePath)' == '' AND Exists('$(PaketBootStrapperExeDir)') ">$(PaketBootStrapperExeDir)paket</PaketExePath> + + <!-- If all else fails, use global path approach. --> + <PaketExePath Condition=" '$(PaketExePath)' == ''">paket</PaketExePath> + </PropertyGroup> + + <!-- If not using CLI, setup correct execution command. --> + <PropertyGroup Condition=" '$(_PaketCommand)' == '' "> + <_PaketExeExtension>$([System.IO.Path]::GetExtension("$(PaketExePath)"))</_PaketExeExtension> + <_PaketCommand Condition=" '$(_PaketCommand)' == '' AND '$(_PaketExeExtension)' == '.dll' ">dotnet "$(PaketExePath)"</_PaketCommand> + <_PaketCommand Condition=" '$(_PaketCommand)' == '' AND '$(OS)' != 'Windows_NT' AND '$(_PaketExeExtension)' == '.exe' ">$(MonoPath) --runtime=v4.0.30319 "$(PaketExePath)"</_PaketCommand> + <_PaketCommand Condition=" '$(_PaketCommand)' == '' ">"$(PaketExePath)"</_PaketCommand> + </PropertyGroup> + + <!-- The way to get a property to be available outside the target is to use this task. --> + <CreateProperty Value="$(_PaketCommand)"> + <Output TaskParameter="Value" PropertyName="PaketCommand"/> + </CreateProperty> + + </Target> + + <Choose> <!-- MyProject.fsproj.paket.references has the highest precedence --> + <When Condition="Exists('$(MSBuildProjectFullPath).paket.references')"> + <PropertyGroup> + <PaketReferences>$(MSBuildProjectFullPath).paket.references</PaketReferences> + </PropertyGroup> + </When> <!-- MyProject.paket.references --> + <When Condition="Exists('$(MSBuildProjectDirectory)\$(MSBuildProjectName).paket.references')"> + <PropertyGroup> + <PaketReferences>$(MSBuildProjectDirectory)\$(MSBuildProjectName).paket.references</PaketReferences> + </PropertyGroup> + </When> <!-- paket.references --> + <When Condition="Exists('$(MSBuildProjectDirectory)\paket.references')"> + <PropertyGroup> + <PaketReferences>$(MSBuildProjectDirectory)\paket.references</PaketReferences> + </PropertyGroup> + </When> <!-- Set to empty if a reference file isn't found matching one of the 3 format options --> + <Otherwise> + <PropertyGroup> + <PaketReferences></PaketReferences> + </PropertyGroup> + </Otherwise> + </Choose> + + <PropertyGroup> + <!-- We need to ensure packages are restored prior to assembly resolve --> + <BuildDependsOn Condition="$(RestorePackages) == 'true'">RestorePackages; $(BuildDependsOn);</BuildDependsOn> + </PropertyGroup> + + <Target Name="RestorePackages" DependsOnTargets="SetPaketCommand"> + + <PropertyGroup> + <!-- Commands --> + <RestoreCommand>$(PaketCommand) restore --references-file "$(PaketReferences)"</RestoreCommand> + <PaketRestoreRequired>true</PaketRestoreRequired> + </PropertyGroup> + + <PropertyGroup Condition="Exists('$(PaketRestoreCacheFile)') "> + <PaketRestoreCachedHash>$([System.IO.File]::ReadAllText('$(PaketRestoreCacheFile)'))</PaketRestoreCachedHash> + <PaketRestoreLockFileHash>$([System.IO.File]::ReadAllText('$(PaketLockFilePath)'))</PaketRestoreLockFileHash> + <PaketRestoreRequired>true</PaketRestoreRequired> + <PaketRestoreRequired Condition=" '$(PaketRestoreLockFileHash)' == '$(PaketRestoreCachedHash)' ">false</PaketRestoreRequired> + <PaketRestoreRequired Condition=" '$(PaketRestoreLockFileHash)' == '' ">true</PaketRestoreRequired> + </PropertyGroup> + + <Exec Command="$(RestoreCommand)" + IgnoreStandardErrorWarningFormat="true" + WorkingDirectory="$(PaketRootPath)" + ContinueOnError="false" + Condition=" '$(PaketRestoreRequired)' == 'true' AND Exists('$(PaketReferences)') AND '$(PaketReferences)' != '' " + /> + </Target> +</Project> \ No newline at end of file diff --git a/Examples/AdvancedExamples/FeedbackGravityExample.cs b/Examples/AdvancedExamples/FeedbackGravityExample.cs deleted file mode 100644 index 4a2c58e..0000000 --- a/Examples/AdvancedExamples/FeedbackGravityExample.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.Drawing; -using System.Runtime.InteropServices; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.AdvancedExamples -{ - [ExampleProject("Transform feedback with gravity simulation")] - public class FeedbackGravityExample - : ExampleWindow - { - [StructLayout(LayoutKind.Sequential)] - private struct Particle - { - public Vector3 Position; - private float _padding0; - public Vector3 Velocity; - private float _padding1; - } - - private readonly Random _random; - private GravityProgram _program; - private VertexArray _vao; - private BufferPod<Particle> _buffers; - private TransformFeedback _feedback; - - // simulation parameters - private float _centerMass = 0.8309f; //0.65f; - private int _particleCount = 64000; - - public FeedbackGravityExample() - { - _random = new Random(); - Load += OnLoad; - RenderFrame += OnRenderFrame; - Keyboard.KeyDown += OnKeyDown; - } - - private float Rand(float range) - { - return (float)(_random.NextDouble() * 2 * range - range); - } - - private void OnLoad(object sender, EventArgs e) - { - // initialize shader (load sources, create/compile/link shader program, error checking) - // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes - _program = ProgramFactory.Create<GravityProgram>(); - // this program will be used all the time so just activate it once and for all - _program.Use(); - - // create and bind a vertex array - _vao = new VertexArray(); - _vao.Bind(); - - // create and bind transform feedback object - _feedback = new TransformFeedback(); - _feedback.Bind(); - - // Writing to a buffer while reading from it is not allowed - // so we need two buffer objects here, which can be achieved by using the BufferPod<T> type. - // It contains two buffers, Ping and Pong, to simplify this process. - _buffers = new BufferPod<Particle>(); - InitializeParticles(_particleCount); - - // enable point sprite rendering - GL.Enable(EnableCap.PointSprite); - // enable modification of the point sprite size from the program (vertex shader in this case) - GL.Enable(EnableCap.ProgramPointSize); - // enable depth testing - GL.Enable(EnableCap.DepthTest); - // set a nice clear color - GL.ClearColor(Color.Black); - - // set a nice camera angle - Camera.DefaultState.Position = new Vector3(0,2,-8); - Camera.ResetToDefault(); - } - - private void InitializeParticles(int n) - { - var particles = new Particle[n]; - for (var i = 0; i < particles.Length; i++) - { - // generate a flat random cube - particles[i].Position.X = Rand(0.2f); - particles[i].Position.Y = Rand(0.02f); - particles[i].Position.Z = Rand(0.2f); - // move particles outwards - particles[i].Position += particles[i].Position.Normalized()*0.8f; - // calculate velocity perpendicular to the direction towards the gravity center and the y-axis - particles[i].Velocity = Vector3.Cross(particles[i].Position, -Vector3.UnitY); - } - // upload data into the Ping buffer and initialize the pong buffer to the same size - _buffers.Init(BufferTarget.ArrayBuffer, particles); - } - - private void OnRenderFrame(object sender, FrameEventArgs e) - { - // set up viewport - GL.Viewport(0, 0, Width, Height); - // clear the back buffer - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - // set up modelview and perspective matrix - SetupPerspective(); - - // set uniforms - _program.CenterMass.Set(_centerMass); - _program.TimeStep.Set((float)e.Time); - _program.ModelViewProjectionMatrix.Set(ModelView * Projection); - - // set up binding of the shader variable to the buffer object - _vao.BindAttribute(_program.InPosition, _buffers.Ping); - _vao.BindAttribute(_program.InVelocity, _buffers.Ping, 16); - - // set target buffer for transform feedback - // the two outputs are interleaved into the same buffer - // so we only have to bind one of them as both binding indices are equal: - // _program.OutPosition.Index == _program.OutVelocity.Index - // when you choose to write into different buffers you need to bind all of them - _feedback.BindOutput(_program.OutPosition, _buffers.Pong); - - // render the buffer and capture transform feedback outputs - _feedback.Begin(TransformFeedbackPrimitiveType.Points); - _vao.DrawArrays(PrimitiveType.Points, 0, _buffers.Ping.ElementCount); - _feedback.End(); - - // swap all the buffers! - _buffers.Swap(); - SwapBuffers(); - } - - private void OnKeyDown(object sender, KeyboardKeyEventArgs e) - { - const float up = 1.1f; - const float down = 0.9f; - var reinitialize = false; - switch (e.Key) - { - case Key.Up: _centerMass *= up; break; - case Key.Down: _centerMass *= down; break; - case Key.Space: - case Key.Right: - case Key.Left: - if (e.Key == Key.Right) _particleCount = (int)(_particleCount * up); - if (e.Key == Key.Left) _particleCount = (int)(_particleCount * down); - reinitialize = true; - break; - } - if (reinitialize) InitializeParticles(_particleCount); - } - } -} \ No newline at end of file diff --git a/Examples/AdvancedExamples/LoaderDDS.cs b/Examples/AdvancedExamples/LoaderDDS.cs deleted file mode 100644 index ef64f1d..0000000 --- a/Examples/AdvancedExamples/LoaderDDS.cs +++ /dev/null @@ -1,708 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -// #define READALL -// uncomment so ALL fields read from file are interpreted and filled. Necessary to implement uncompressed DDS - -// TODO: Find app that can build compressed dds cubemaps and verify that the import code works. - -using System; -using System.Diagnostics; -using System.IO; -using OpenTK.Graphics.OpenGL; - -namespace Examples.AdvancedExamples -{ - /// <summary> - /// Expects the presence of a valid OpenGL Context and Texture Compression Extensions (GL 1.5) and Cube Maps (GL 1.3). - /// You will get what you give. No automatic Mipmap generation or automatic compression is done. (both bad quality) - /// Textures are never rescaled or checked if Power of 2, but you should make the Width and Height a multiple of 4 because DXTn uses 4x4 blocks. - /// (Image displays correctly but runs extremely slow with non-power-of-two Textures on FX5600, Cache misses?) - /// CubeMap support is experimental and the file must specify all 6 faces to work at all. - /// </summary> - public static class ImageDDS - { - #region Constants - private const byte HeaderSizeInBytes = 128; // all non-image data together is 128 Bytes - private const uint BitMask = 0x00000007; // bits = 00 00 01 11 - - - private static NotImplementedException Unfinished = new NotImplementedException( "ERROR: Only 2 Dimensional DXT1/3/5 compressed images for now. 1D/3D Textures may not be compressed according to spec." ); - #endregion Constants - - #region Simplified In-Memory representation of the Image - private static bool _IsCompressed; - private static int _Width, _Height, _Depth, _MipMapCount; - private static int _BytesForMainSurface; // must be handled with care when implementing uncompressed formats! - private static byte _BytesPerBlock; - private static PixelInternalFormat _PixelInternalFormat; - #endregion Simplified In-Memory representation of the Image - - #region Flag Enums - [Flags] // Surface Description - private enum eDDSD: uint - { - CAPS = 0x00000001, // is always present - HEIGHT = 0x00000002, // is always present - WIDTH = 0x00000004, // is always present - PITCH = 0x00000008, // is set if the image is uncompressed - PIXELFORMAT = 0x00001000, // is always present - MIPMAPCOUNT = 0x00020000, // is set if the image contains MipMaps - LINEARSIZE = 0x00080000, // is set if the image is compressed - DEPTH = 0x00800000 // is set for 3D Volume Textures - } - - [Flags] // Pixelformat - private enum eDDPF: uint - { - NONE = 0x00000000, // not part of DX, added for convenience - ALPHAPIXELS = 0x00000001, - FOURCC = 0x00000004, - RGB = 0x00000040, - RGBA = 0x00000041 - } - - /// <summary>This list was derived from nVidia OpenGL SDK</summary> - [Flags] // Texture types - private enum eFOURCC: uint - { - UNKNOWN = 0, -#if READALL - R8G8B8 = 20, - A8R8G8B8 = 21, - X8R8G8B8 = 22, - R5G6B5 = 23, - X1R5G5B5 = 24, - A1R5G5B5 = 25, - A4R4G4B4 = 26, - R3G3B2 = 27, - A8 = 28, - A8R3G3B2 = 29, - X4R4G4B4 = 30, - A2B10G10R10 = 31, - A8B8G8R8 = 32, - X8B8G8R8 = 33, - G16R16 = 34, - A2R10G10B10 = 35, - A16B16G16R16 = 36, - - L8 = 50, - A8L8 = 51, - A4L4 = 52, - - D16_LOCKABLE = 70, - D32 = 71, - D24X8 = 77, - D16 = 80, - - D32F_LOCKABLE = 82, - L16 = 81, - - // s10e5 formats (16-bits per channel) - R16F = 111, - G16R16F = 112, - A16B16G16R16F = 113, - - // IEEE s23e8 formats (32-bits per channel) - R32F = 114, - G32R32F = 115, - A32B32G32R32F = 116 -#endif - DXT1 = 0x31545844, - DXT2 = 0x32545844, - DXT3 = 0x33545844, - DXT4 = 0x34545844, - DXT5 = 0x35545844, - } - - [Flags] // dwCaps1 - private enum eDDSCAPS: uint - { - NONE = 0x00000000, // not part of DX, added for convenience - COMPLEX = 0x00000008, // should be set for any DDS file with more than one main surface - TEXTURE = 0x00001000, // should always be set - MIPMAP = 0x00400000 // only for files with MipMaps - } - - [Flags] // dwCaps2 - private enum eDDSCAPS2: uint - { - NONE = 0x00000000, // not part of DX, added for convenience - CUBEMAP = 0x00000200, - CUBEMAP_POSITIVEX = 0x00000400, - CUBEMAP_NEGATIVEX = 0x00000800, - CUBEMAP_POSITIVEY = 0x00001000, - CUBEMAP_NEGATIVEY = 0x00002000, - CUBEMAP_POSITIVEZ = 0x00004000, - CUBEMAP_NEGATIVEZ = 0x00008000, - CUBEMAP_ALL_FACES = 0x0000FC00, - VOLUME = 0x00200000 // for 3D Textures - } - #endregion Flag Enums - - #region Private Members - private static string idString; // 4 bytes, must be "DDS " - private static UInt32 dwSize; // Size of structure is 124 bytes, 128 including all sub-structs and the header - private static UInt32 dwFlags; // Flags to indicate valid fields. - private static UInt32 dwHeight; // Height of the main image in pixels - private static UInt32 dwWidth; // Width of the main image in pixels - private static UInt32 dwPitchOrLinearSize; // For compressed formats, this is the total number of bytes for the main image. - private static UInt32 dwDepth; // For volume textures, this is the depth of the volume. - private static UInt32 dwMipMapCount; // total number of levels in the mipmap chain of the main image. -#if READALL - private static UInt32[] dwReserved1; // 11 UInt32s -#endif - // Pixelformat sub-struct, 32 bytes - private static UInt32 pfSize; // Size of Pixelformat structure. This member must be set to 32. - private static UInt32 pfFlags; // Flags to indicate valid fields. - private static UInt32 pfFourCC; // This is the four-character code for compressed formats. -#if READALL - private static UInt32 pfRGBBitCount; // For RGB formats, this is the total number of bits in the format. dwFlags should include DDpf_RGB in this case. This value is usually 16, 24, or 32. For A8R8G8B8, this value would be 32. - private static UInt32 pfRBitMask; // For RGB formats, these three fields contain the masks for the red, green, and blue channels. For A8R8G8B8, these values would be 0x00ff0000, 0x0000ff00, and 0x000000ff respectively. - private static UInt32 pfGBitMask; // .. - private static UInt32 pfBBitMask; // .. - private static UInt32 pfABitMask; // For RGB formats, this contains the mask for the alpha channel, if any. dwFlags should include DDpf_ALPHAPIXELS in this case. For A8R8G8B8, this value would be 0xff000000. -#endif - // Capabilities sub-struct, 16 bytes - private static UInt32 dwCaps1; // always includes DDSCAPS_TEXTURE. with more than one main surface DDSCAPS_COMPLEX should also be set. - private static UInt32 dwCaps2; // For cubic environment maps, DDSCAPS2_CUBEMAP should be included as well as one or more faces of the map (DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, DDSCAPS2_CUBEMAP_NEGATIVEY, DDSCAPS2_CUBEMAP_POSITIVEZ, DDSCAPS2_CUBEMAP_NEGATIVEZ). For volume textures, DDSCAPS2_VOLUME should be included. -#if READALL - private static UInt32[] dwReserved2; // 3 = 2 + 1 UInt32 -#endif - #endregion Private Members - - /// <summary> - /// This function will generate, bind and fill a Texture Object with a DXT1/3/5 compressed Texture in .dds Format. - /// MipMaps below 4x4 Pixel Size are discarded, because DXTn's smallest unit is a 4x4 block of Pixel data. - /// It will set correct MipMap parameters, Filtering, Wrapping and EnvMode for the Texture. - /// The only call inside this function affecting OpenGL State is GL.BindTexture(); - /// </summary> - /// <param name="filename">The name of the file you wish to load, including path and file extension.</param> - /// <param name="texturehandle">0 if invalid, otherwise a Texture Object usable with GL.BindTexture().</param> - /// <param name="dimension">0 if invalid, will output what was loaded (typically Texture1D/2D/3D or Cubemap)</param> - public static void LoadFromDisk( string filename, out uint texturehandle, out TextureTarget dimension ) - { - #region Prep data - // invalidate whatever it was before - dimension = (TextureTarget) 0; - texturehandle = TextureLoaderParameters.OpenGLDefaultTexture; - ErrorCode GLError = ErrorCode.NoError; - - _IsCompressed = false; - _Width = 0; - _Height = 0; - _Depth = 0; - _MipMapCount = 0; - _BytesForMainSurface = 0; - _BytesPerBlock = 0; - _PixelInternalFormat = PixelInternalFormat.Rgba8; - byte[] _RawDataFromFile; - #endregion - - #region Try - try // Exceptions will be thrown if any Problem occurs while working on the file. - { - _RawDataFromFile = File.ReadAllBytes( @filename ); - - #region Translate Header to less cryptic representation - ConvertDX9Header( ref _RawDataFromFile ); // The first 128 Bytes of the file is non-image data - - // start by checking if all forced flags are present. Flags indicate valid fields, but aren't written by every tool ..... - if ( idString != "DDS " || // magic key - dwSize != 124 || // constant size of struct, never reused - pfSize != 32 || // constant size of struct, never reused - !CheckFlag( dwFlags, (uint) eDDSD.CAPS ) || // must know it's caps - !CheckFlag( dwFlags, (uint) eDDSD.PIXELFORMAT ) || // must know it's format - !CheckFlag( dwCaps1, (uint) eDDSCAPS.TEXTURE ) // must be a Texture - ) - throw new ArgumentException( "ERROR: File has invalid signature or missing Flags." ); - - #region Examine Flags - if ( CheckFlag( dwFlags, (uint) eDDSD.WIDTH ) ) - _Width = (int) dwWidth; - else - throw new ArgumentException( "ERROR: Flag for Width not set." ); - - if ( CheckFlag( dwFlags, (uint) eDDSD.HEIGHT ) ) - _Height = (int) dwHeight; - else - throw new ArgumentException( "ERROR: Flag for Height not set." ); - - if ( CheckFlag( dwFlags, (uint) eDDSD.DEPTH ) && CheckFlag( dwCaps2, (uint) eDDSCAPS2.VOLUME ) ) - { - dimension = TextureTarget.Texture3D; // image is 3D Volume - _Depth = (int) dwDepth; - throw Unfinished; - } else - {// image is 2D or Cube - if ( CheckFlag( dwCaps2, (uint) eDDSCAPS2.CUBEMAP ) ) - { - dimension = TextureTarget.TextureCubeMap; - _Depth = 6; - } else - { - dimension = TextureTarget.Texture2D; - _Depth = 1; - } - } - - // these flags must be set for mipmaps to be included - if ( CheckFlag( dwCaps1, (uint) eDDSCAPS.MIPMAP ) && CheckFlag( dwFlags, (uint) eDDSD.MIPMAPCOUNT ) ) - _MipMapCount = (int) dwMipMapCount; // image contains MipMaps - else - _MipMapCount = 1; // only 1 main image - - // Should never happen - if ( CheckFlag( dwFlags, (uint) eDDSD.PITCH ) && CheckFlag( dwFlags, (uint) eDDSD.LINEARSIZE ) ) - throw new ArgumentException( "INVALID: Pitch AND Linear Flags both set. Image cannot be uncompressed and DTXn compressed at the same time." ); - - // This flag is set if format is uncompressed RGB RGBA etc. - if ( CheckFlag( dwFlags, (uint) eDDSD.PITCH ) ) - { - // _BytesForMainSurface = (int) dwPitchOrLinearSize; // holds bytes-per-scanline for uncompressed - _IsCompressed = false; - throw Unfinished; - } - - // This flag is set if format is compressed DXTn. - if ( CheckFlag( dwFlags, (uint) eDDSD.LINEARSIZE ) ) - { - _BytesForMainSurface = (int) dwPitchOrLinearSize; - _IsCompressed = true; - } - #endregion Examine Flags - - #region Examine Pixel Format, anything but DXTn will fail atm. - if ( CheckFlag( pfFlags, (uint) eDDPF.FOURCC ) ) - switch ( (eFOURCC) pfFourCC ) - { - case eFOURCC.DXT1: - _PixelInternalFormat = (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbS3tcDxt1Ext; - _BytesPerBlock = 8; - _IsCompressed = true; - break; - //case eFOURCC.DXT2: - case eFOURCC.DXT3: - _PixelInternalFormat = (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt3Ext; - _BytesPerBlock = 16; - _IsCompressed = true; - break; - //case eFOURCC.DXT4: - case eFOURCC.DXT5: - _PixelInternalFormat = (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt5Ext; - _BytesPerBlock = 16; - _IsCompressed = true; - break; - default: - throw Unfinished; // handle uncompressed formats - } else - throw Unfinished; - // pf*Bitmasks should be examined here - #endregion - - // Works, but commented out because some texture authoring tools don't set this flag. - /* Safety Check, if file is only 1x 2D surface without mipmaps, eDDSCAPS.COMPLEX should not be set - if ( CheckFlag( dwCaps1, (uint) eDDSCAPS.COMPLEX ) ) - { - if ( result == eTextureDimension.Texture2D && _MipMapCount == 1 ) // catch potential problem - Trace.WriteLine( "Warning: Image is declared complex, but contains only 1 surface." ); - }*/ - - if ( TextureLoaderParameters.Verbose ) - Trace.WriteLine( "\n" + GetDescriptionFromMemory( filename, dimension ) ); - #endregion Translate Header to less cryptic representation - - #region send the Texture to GL - #region Generate and Bind Handle - GL.GenTextures( 1, out texturehandle ); - GL.BindTexture( dimension, texturehandle ); - #endregion Generate and Bind Handle - - int Cursor = HeaderSizeInBytes; - // foreach face in the cubemap, get all it's mipmaps levels. Only one iteration for Texture2D - for ( int Slices = 0 ; Slices < _Depth ; Slices++ ) - { - int trueMipMapCount = _MipMapCount - 1; // TODO: triplecheck correctness - int Width = _Width; - int Height = _Height; - for ( int Level = 0 ; Level < _MipMapCount ; Level++ ) // start at base image - { - #region determine Dimensions - int BlocksPerRow = ( Width + 3 ) >> 2; - int BlocksPerColumn = ( Height + 3 ) >> 2; - int SurfaceBlockCount = BlocksPerRow * BlocksPerColumn; // // DXTn stores Texels in 4x4 blocks, a Color block is 8 Bytes, an Alpha block is 8 Bytes for DXT3/5 - int SurfaceSizeInBytes = SurfaceBlockCount * _BytesPerBlock; - - // this check must evaluate to false for 2D and Cube maps, or it's impossible to determine MipMap sizes. - if ( TextureLoaderParameters.Verbose && Level == 0 && _IsCompressed && _BytesForMainSurface != SurfaceSizeInBytes ) - Trace.WriteLine( "Warning: Calculated byte-count of main image differs from what was read from file." ); - #endregion determine Dimensions - - // skip mipmaps smaller than a 4x4 Pixels block, which is the smallest DXTn unit. - if ( Width > 2 && Height > 2 ) - { // Note: there could be a potential problem with non-power-of-two cube maps - #region Prepare Array for TexImage - byte[] RawDataOfSurface = new byte[SurfaceSizeInBytes]; - if ( !TextureLoaderParameters.FlipImages ) - { // no changes to the image, copy as is - Array.Copy( _RawDataFromFile, Cursor, RawDataOfSurface, 0, SurfaceSizeInBytes ); - } else - { // Turn the blocks upside down and the rows aswell, done in a single pass through all blocks - for ( int sourceColumn = 0 ; sourceColumn < BlocksPerColumn ; sourceColumn++ ) - { - int targetColumn = BlocksPerColumn - sourceColumn - 1; - for ( int row = 0 ; row < BlocksPerRow ; row++ ) - { - int target = ( targetColumn * BlocksPerRow + row ) * _BytesPerBlock; - int source = ( sourceColumn * BlocksPerRow + row ) * _BytesPerBlock + Cursor; - #region Swap Bytes - switch ( _PixelInternalFormat ) - { - case (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbS3tcDxt1Ext: - // Color only - RawDataOfSurface[target + 0] = _RawDataFromFile[source + 0]; - RawDataOfSurface[target + 1] = _RawDataFromFile[source + 1]; - RawDataOfSurface[target + 2] = _RawDataFromFile[source + 2]; - RawDataOfSurface[target + 3] = _RawDataFromFile[source + 3]; - RawDataOfSurface[target + 4] = _RawDataFromFile[source + 7]; - RawDataOfSurface[target + 5] = _RawDataFromFile[source + 6]; - RawDataOfSurface[target + 6] = _RawDataFromFile[source + 5]; - RawDataOfSurface[target + 7] = _RawDataFromFile[source + 4]; - break; - case (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt3Ext: - // Alpha - RawDataOfSurface[target + 0] = _RawDataFromFile[source + 6]; - RawDataOfSurface[target + 1] = _RawDataFromFile[source + 7]; - RawDataOfSurface[target + 2] = _RawDataFromFile[source + 4]; - RawDataOfSurface[target + 3] = _RawDataFromFile[source + 5]; - RawDataOfSurface[target + 4] = _RawDataFromFile[source + 2]; - RawDataOfSurface[target + 5] = _RawDataFromFile[source + 3]; - RawDataOfSurface[target + 6] = _RawDataFromFile[source + 0]; - RawDataOfSurface[target + 7] = _RawDataFromFile[source + 1]; - - // Color - RawDataOfSurface[target + 8] = _RawDataFromFile[source + 8]; - RawDataOfSurface[target + 9] = _RawDataFromFile[source + 9]; - RawDataOfSurface[target + 10] = _RawDataFromFile[source + 10]; - RawDataOfSurface[target + 11] = _RawDataFromFile[source + 11]; - RawDataOfSurface[target + 12] = _RawDataFromFile[source + 15]; - RawDataOfSurface[target + 13] = _RawDataFromFile[source + 14]; - RawDataOfSurface[target + 14] = _RawDataFromFile[source + 13]; - RawDataOfSurface[target + 15] = _RawDataFromFile[source + 12]; - break; - case (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt5Ext: - // Alpha, the first 2 bytes remain - RawDataOfSurface[target + 0] = _RawDataFromFile[source + 0]; - RawDataOfSurface[target + 1] = _RawDataFromFile[source + 1]; - - // extract 3 bits each and flip them - GetBytesFromUInt24( ref RawDataOfSurface, (uint) target + 5, FlipUInt24( GetUInt24( ref _RawDataFromFile, (uint) source + 2 ) ) ); - GetBytesFromUInt24( ref RawDataOfSurface, (uint) target + 2, FlipUInt24( GetUInt24( ref _RawDataFromFile, (uint) source + 5 ) ) ); - - // Color - RawDataOfSurface[target + 8] = _RawDataFromFile[source + 8]; - RawDataOfSurface[target + 9] = _RawDataFromFile[source + 9]; - RawDataOfSurface[target + 10] = _RawDataFromFile[source + 10]; - RawDataOfSurface[target + 11] = _RawDataFromFile[source + 11]; - RawDataOfSurface[target + 12] = _RawDataFromFile[source + 15]; - RawDataOfSurface[target + 13] = _RawDataFromFile[source + 14]; - RawDataOfSurface[target + 14] = _RawDataFromFile[source + 13]; - RawDataOfSurface[target + 15] = _RawDataFromFile[source + 12]; - break; - default: - throw new ArgumentException( "ERROR: Should have never arrived here! Bad _PixelInternalFormat! Should have been dealt with much earlier." ); - } - #endregion Swap Bytes - } - } - } - #endregion Prepare Array for TexImage - - #region Create TexImage - switch ( dimension ) - { - case TextureTarget.Texture2D: - GL.CompressedTexImage2D( TextureTarget.Texture2D, - Level, - _PixelInternalFormat, - Width, - Height, - TextureLoaderParameters.Border, - SurfaceSizeInBytes, - RawDataOfSurface ); - break; - case TextureTarget.TextureCubeMap: - GL.CompressedTexImage2D( TextureTarget.TextureCubeMapPositiveX + Slices, - Level, - _PixelInternalFormat, - Width, - Height, - TextureLoaderParameters.Border, - SurfaceSizeInBytes, - RawDataOfSurface ); - break; - case TextureTarget.Texture1D: // Untested - case TextureTarget.Texture3D: // Untested - default: - throw new ArgumentException( "ERROR: Use DXT for 2D Images only. Cannot evaluate " + dimension ); - } - GL.Finish( ); - #endregion Create TexImage - - #region Query Success - int width, height, internalformat, compressed; - switch ( dimension ) - { - case TextureTarget.Texture1D: - case TextureTarget.Texture2D: - case TextureTarget.Texture3D: - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureWidth, out width ); - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureHeight, out height ); - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureInternalFormat, out internalformat ); - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureCompressed, out compressed ); - break; - case TextureTarget.TextureCubeMap: - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureWidth, out width ); - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureHeight, out height ); - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureInternalFormat, out internalformat ); - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureCompressed, out compressed ); - break; - default: - throw Unfinished; - } - GLError = GL.GetError( ); - if ( TextureLoaderParameters.Verbose ) - Trace.WriteLine( "GL: " + GLError.ToString( ) + " Level: " + Level + " DXTn: " + ( ( compressed == 1 ) ? "Yes" : "No" ) + " Frmt:" + (ExtTextureCompressionS3tc) internalformat + " " + width + "*" + height ); - if ( GLError != ErrorCode.NoError || compressed == 0 || width == 0 || height == 0 || internalformat == 0 ) - { - GL.DeleteTextures( 1, ref texturehandle ); - throw new ArgumentException( "ERROR: Something went wrong after GL.CompressedTexImage(); Last GL Error: " + GLError.ToString( ) ); - } - #endregion Query Success - } else - { - if ( trueMipMapCount > Level ) - trueMipMapCount = Level - 1; // The current Level is invalid - } - - #region Prepare the next MipMap level - Width /= 2; - if ( Width < 1 ) - Width = 1; - Height /= 2; - if ( Height < 1 ) - Height = 1; - Cursor += SurfaceSizeInBytes; - #endregion Prepare the next MipMap level - } - - #region Set States properly - GL.TexParameter( dimension, (TextureParameterName) All.TextureBaseLevel, 0 ); - GL.TexParameter( dimension, (TextureParameterName) All.TextureMaxLevel, trueMipMapCount ); - - int TexMaxLevel; - GL.GetTexParameter( dimension, GetTextureParameter.TextureMaxLevel, out TexMaxLevel ); - - if ( TextureLoaderParameters.Verbose ) - Trace.WriteLine( "Verification: GL: " + GL.GetError( ).ToString( ) + " TextureMaxLevel: " + TexMaxLevel + ( ( TexMaxLevel == trueMipMapCount ) ? " (Correct.)" : " (Wrong!)" ) ); - #endregion Set States properly - } - - #region Set Texture Parameters - GL.TexParameter( dimension, TextureParameterName.TextureMinFilter, (int) TextureLoaderParameters.MinificationFilter ); - GL.TexParameter( dimension, TextureParameterName.TextureMagFilter, (int) TextureLoaderParameters.MagnificationFilter ); - - GL.TexParameter( dimension, TextureParameterName.TextureWrapS, (int) TextureLoaderParameters.WrapModeS ); - GL.TexParameter( dimension, TextureParameterName.TextureWrapT, (int) TextureLoaderParameters.WrapModeT ); - - GL.TexEnv( TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (int) TextureLoaderParameters.EnvMode ); - - GLError = GL.GetError( ); - if ( GLError != ErrorCode.NoError ) - { - throw new ArgumentException( "Error setting Texture Parameters. GL Error: " + GLError ); - } - #endregion Set Texture Parameters - - // If it made it here without throwing any Exception the result is a valid Texture. - return; // success - #endregion send the Texture to GL - } catch ( Exception e ) - { - dimension = (TextureTarget) 0; - texturehandle = TextureLoaderParameters.OpenGLDefaultTexture; - throw new ArgumentException( "ERROR: Exception caught when attempting to load file " + filename + ".\n" + e + "\n" + GetDescriptionFromFile( filename ) ); - // return; // failure - } finally - { - _RawDataFromFile = null; // clarity, not really needed - } - #endregion Try - } - - #region Helpers - private static void ConvertDX9Header( ref byte[] input ) - { - UInt32 offset = 0; - idString = GetString( ref input, offset ); - offset += 4; - dwSize = GetUInt32( ref input, offset ); - offset += 4; - dwFlags = GetUInt32( ref input, offset ); - offset += 4; - dwHeight = GetUInt32( ref input, offset ); - offset += 4; - dwWidth = GetUInt32( ref input, offset ); - offset += 4; - dwPitchOrLinearSize = GetUInt32( ref input, offset ); - offset += 4; - dwDepth = GetUInt32( ref input, offset ); - offset += 4; - dwMipMapCount = GetUInt32( ref input, offset ); - offset += 4; -#if READALL - dwReserved1 = new UInt32[11]; // reserved -#endif - offset += 4 * 11; - pfSize = GetUInt32( ref input, offset ); - offset += 4; - pfFlags = GetUInt32( ref input, offset ); - offset += 4; - pfFourCC = GetUInt32( ref input, offset ); - offset += 4; -#if READALL - pfRGBBitCount = GetUInt32( ref input, offset ); - offset += 4; - pfRBitMask = GetUInt32( ref input, offset ); - offset += 4; - pfGBitMask = GetUInt32( ref input, offset ); - offset += 4; - pfBBitMask = GetUInt32( ref input, offset ); - offset += 4; - pfABitMask = GetUInt32( ref input, offset ); - offset += 4; -#else - offset += 20; -#endif - dwCaps1 = GetUInt32( ref input, offset ); - offset += 4; - dwCaps2 = GetUInt32( ref input, offset ); - offset += 4; -#if READALL - dwReserved2 = new UInt32[3]; // offset is 4+112 here, + 12 = 4+124 -#endif - offset += 4 * 3; - } - - /// <summary> Returns true if the flag is set, false otherwise</summary> - private static bool CheckFlag( uint variable, uint flag ) - { - return ( variable & flag ) > 0 ? true : false; - } - - private static string GetString( ref byte[] input, uint offset ) - { - return "" + (char) input[offset + 0] + (char) input[offset + 1] + (char) input[offset + 2] + (char) input[offset + 3]; - } - - private static uint GetUInt32( ref byte[] input, uint offset ) - { - return (uint) ( ( ( input[offset + 3] * 256 + input[offset + 2] ) * 256 + input[offset + 1] ) * 256 + input[offset + 0] ); - } - - private static uint GetUInt24( ref byte[] input, uint offset ) - { - return (uint) ( ( input[offset + 2] * 256 + input[offset + 1] ) * 256 + input[offset + 0] ); - } - - private static void GetBytesFromUInt24( ref byte[] input, uint offset, uint splitme ) - { - input[offset + 0] = (byte) ( splitme & 0x000000ff ); - input[offset + 1] = (byte) ( ( splitme & 0x0000ff00 ) >> 8 ); - input[offset + 2] = (byte) ( ( splitme & 0x00ff0000 ) >> 16 ); - return; - } - - /// <summary>DXT5 Alpha block flipping, inspired by code from Evan Hart (nVidia SDK)</summary> - private static uint FlipUInt24( uint inputUInt24 ) - { - byte[][] ThreeBits = new byte[2][]; - for ( int i = 0 ; i < 2 ; i++ ) - ThreeBits[i] = new byte[4]; - - // extract 3 bits each into the array - ThreeBits[0][0] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[0][1] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[0][2] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[0][3] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][0] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][1] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][2] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][3] = (byte) ( inputUInt24 & BitMask ); - - // stuff 8x 3bits into 3 bytes - uint Result = 0; - Result = Result | (uint) ( ThreeBits[1][0] << 0 ); - Result = Result | (uint) ( ThreeBits[1][1] << 3 ); - Result = Result | (uint) ( ThreeBits[1][2] << 6 ); - Result = Result | (uint) ( ThreeBits[1][3] << 9 ); - Result = Result | (uint) ( ThreeBits[0][0] << 12 ); - Result = Result | (uint) ( ThreeBits[0][1] << 15 ); - Result = Result | (uint) ( ThreeBits[0][2] << 18 ); - Result = Result | (uint) ( ThreeBits[0][3] << 21 ); - return Result; - } - #endregion Helpers - - #region String Representations - private static string GetDescriptionFromFile( string filename ) - { - return "\n--> Header of " + filename + - "\nID: " + idString + - "\nSize: " + dwSize + - "\nFlags: " + dwFlags + " (" + (eDDSD) dwFlags + ")" + - "\nHeight: " + dwHeight + - "\nWidth: " + dwWidth + - "\nPitch: " + dwPitchOrLinearSize + - "\nDepth: " + dwDepth + - "\nMipMaps: " + dwMipMapCount + - "\n\n---PixelFormat---" + filename + - "\nSize: " + pfSize + - "\nFlags: " + pfFlags + " (" + (eDDPF) pfFlags + ")" + - "\nFourCC: " + pfFourCC + " (" + (eFOURCC) pfFourCC + ")" + -#if READALL - "\nBitcount: " + pfRGBBitCount + - "\nBitMask Red: " + pfRBitMask + - "\nBitMask Green: " + pfGBitMask + - "\nBitMask Blue: " + pfBBitMask + - "\nBitMask Alpha: " + pfABitMask + -#endif - "\n\n---Capabilities---" + filename + - "\nCaps1: " + dwCaps1 + " (" + (eDDSCAPS) dwCaps1 + ")" + - "\nCaps2: " + dwCaps2 + " (" + (eDDSCAPS2) dwCaps2 + ")"; - } - - private static string GetDescriptionFromMemory( string filename, TextureTarget Dimension ) - { - return "\nFile: " + filename + - "\nDimension: " + Dimension + - "\nSize: " + _Width + " * " + _Height + " * " + _Depth + - "\nCompressed: " + _IsCompressed + - "\nBytes for Main Image: " + _BytesForMainSurface + - "\nMipMaps: " + _MipMapCount; - } - #endregion String Representations - } -} diff --git a/Examples/AdvancedExamples/LoaderStatics.cs b/Examples/AdvancedExamples/LoaderStatics.cs deleted file mode 100644 index fa74751..0000000 --- a/Examples/AdvancedExamples/LoaderStatics.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -using OpenTK.Graphics.OpenGL; - -namespace Examples.AdvancedExamples -{ - - /// <summary>The parameters in this class have only effect on the following Texture loads.</summary> - public static class TextureLoaderParameters - { - /// <summary>(Debug Aid, should be set to false) If set to false only Errors will be printed. If set to true, debug information (Warnings and Queries) will be printed in addition to Errors.</summary> - public static bool Verbose = false; - - /// <summary>Always-valid fallback parameter for GL.BindTexture (Default: 0). This number will be returned if loading the Texture failed. You can set this to a checkerboard texture or similar, which you have already loaded.</summary> - public static uint OpenGLDefaultTexture = 0; - - /// <summary>Compressed formats must have a border of 0, so this is constant.</summary> - public const int Border = 0; - - /// <summary>false==DirectX TexCoords, true==OpenGL TexCoords (Default: true)</summary> - public static bool FlipImages = true; - - /// <summary>When enabled, will use Glu to create MipMaps for images loaded with GDI+ (Default: false)</summary> - public static bool BuildMipmapsForUncompressed = false; - - /// <summary>Selects the Magnification filter for following Textures to be loaded. (Default: Nearest)</summary> - public static TextureMagFilter MagnificationFilter = TextureMagFilter.Nearest; - - /// <summary>Selects the Minification filter for following Textures to be loaded. (Default: Nearest)</summary> - public static TextureMinFilter MinificationFilter = TextureMinFilter.Nearest; - - /// <summary>Selects the S Wrapping for following Textures to be loaded. (Default: Repeat)</summary> - public static TextureWrapMode WrapModeS = TextureWrapMode.Repeat; - - /// <summary>Selects the T Wrapping for following Textures to be loaded. (Default: Repeat)</summary> - public static TextureWrapMode WrapModeT = TextureWrapMode.Repeat; - - /// <summary>Selects the Texture Environment Mode for the following Textures to be loaded. Default: Modulate)</summary> - public static TextureEnvMode EnvMode = TextureEnvMode.Modulate; - } - -} diff --git a/Examples/AdvancedExamples/ParallaxMappingExample.cs b/Examples/AdvancedExamples/ParallaxMappingExample.cs deleted file mode 100644 index ce299d6..0000000 --- a/Examples/AdvancedExamples/ParallaxMappingExample.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using ObjectTK.Textures; -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.AdvancedExamples -{ - [ExampleProject("Swizzled Parallax Mapping (ported from OpenTK examples)")] - public class ParallaxMappingExample - : ExampleWindow - { - [StructLayout(LayoutKind.Sequential)] - private struct Vertex - { - public Vector3 Position; - public Vector3 Normal; - public Vector3 Tangent; - public Vector2 TexCoord; - } - - private VertexArray _vao; - private Buffer<Vertex> _buffer; - private ParallaxProgram _program; - private Texture2D _textureDiffuseHeight; - private Texture2D _textureNormalGloss; - - const string TextureDiffuseHeightFilename = "Data/Textures/swizzled-rock-diffuse-height.dds"; - const string TextureNormalGlossFilename = "Data/Textures/swizzled-rock-normal-gloss.dds"; - - Vector3 _lightPosition = new Vector3(0.0f, 1.0f, 1.0f); - Vector3 _lightDiffuse = new Vector3(0.5f, 0.5f, 0.5f); - Vector3 _lightSpecular = new Vector3(1f, 1f, 1f); - - // Material parameter - //private Vector3 _materialScaleAndBiasAndShininess = new Vector3( 0.07f, 0.0f, 38.0f ); // for Metal tex - private Vector3 _materialScaleAndBiasAndShininess = new Vector3(0.04f, 0.0f, 92.0f); // for Rock tex - - public ParallaxMappingExample() - { - Load += OnLoad; - Resize += OnResize; - UpdateFrame += OnUpdateFrame; - RenderFrame += OnRenderFrame; - } - - protected void OnLoad(object sender, EventArgs eventArgs) - { - VSync = VSyncMode.Off; - - // Check for necessary capabilities: - var extensions = GL.GetString(StringName.Extensions); - if (!GL.GetString(StringName.Extensions).Contains("GL_ARB_shading_language")) - { - throw new NotSupportedException(String.Format("This example requires OpenGL 2.0. Found {0}. Aborting.", - GL.GetString(StringName.Version).Substring(0, 3))); - } - - if (!extensions.Contains("GL_ARB_texture_compression") || - !extensions.Contains("GL_EXT_texture_compression_s3tc")) - { - throw new NotSupportedException("This example requires support for texture compression. Aborting."); - } - - var temp = new int[1]; - GL.GetInteger(GetPName.MaxTextureImageUnits, out temp[0]); - Trace.WriteLine(temp[0] + " TMU's for Fragment Shaders found. (2 required)"); - - GL.GetInteger(GetPName.MaxVaryingFloats, out temp[0]); - Trace.WriteLine(temp[0] + " varying floats between VS and FS allowed. (6 required)"); - - GL.GetInteger(GetPName.MaxVertexUniformComponents, out temp[0]); - Trace.WriteLine(temp[0] + " uniform components allowed in Vertex Shader. (6 required)"); - - GL.GetInteger(GetPName.MaxFragmentUniformComponents, out temp[0]); - Trace.WriteLine(temp[0] + " uniform components allowed in Fragment Shader. (11 required)"); - Trace.WriteLine(""); - - // load textures - TextureLoaderParameters.MagnificationFilter = TextureMagFilter.Linear; - TextureLoaderParameters.MinificationFilter = TextureMinFilter.LinearMipmapLinear; - TextureLoaderParameters.WrapModeS = TextureWrapMode.ClampToBorder; - TextureLoaderParameters.WrapModeT = TextureWrapMode.ClampToBorder; - TextureLoaderParameters.EnvMode = TextureEnvMode.Modulate; - - uint handle; - TextureTarget target; - ImageDDS.LoadFromDisk(TextureDiffuseHeightFilename, out handle, out target); - _textureDiffuseHeight = TextureFactory.AquireTexture2D((int) handle); - Trace.WriteLine("Loaded " + TextureDiffuseHeightFilename + " with handle " + handle + " as " + target); - - ImageDDS.LoadFromDisk(TextureNormalGlossFilename, out handle, out target); - _textureNormalGloss = TextureFactory.AquireTexture2D((int) handle); - Trace.WriteLine("Loaded " + TextureNormalGlossFilename + " with handle " + handle + " as " + target); - - Trace.WriteLine("End of Texture Loading. GL Error: " + GL.GetError()); - Trace.WriteLine(""); - - // initialize buffer - var normal = Vector3.UnitZ; - var tangent = Vector3.UnitX; - var vertices = new[] - { - new Vertex - { - Position = new Vector3(-1,-1,0), - TexCoord = new Vector2(0,0), - Normal = normal, - Tangent = tangent - }, - new Vertex - { - Position = new Vector3(1,-1,0), - TexCoord = new Vector2(1,0), - Normal = normal, - Tangent = tangent - }, - new Vertex - { - Position = new Vector3(-1,1,0), - TexCoord = new Vector2(0,1), - Normal = normal, - Tangent = tangent - }, - new Vertex - { - Position = new Vector3(1,1,0), - TexCoord = new Vector2(1,1), - Normal = normal, - Tangent = tangent - } - }; - _buffer = new Buffer<Vertex>(); - _buffer.Init(BufferTarget.ArrayBuffer, vertices); - - // load shader - _program = ProgramFactory.Create<ParallaxProgram>(); - _program.Use(); - - // set up vertex array - _vao = new VertexArray(); - _vao.Bind(); - // bind vertex attributes - // the buffer layout is defined by the Vertex struct: - // data X Y Z NX NY NZ TX TY TZ U V *next vertex* - // offset 0 4 8 12 16 20 24 28 32 36 40 44 - // having to work with offsets could be prevented by using seperate buffer objects for each attribute, - // but that might reduce performance and can get annoying as well. - // performance increase could also be achieved by improving coherent read access - // by padding the struct so that each attribute begins at a multiple of 16 bytes, i.e. 4-floats - // because the GPU can then read all 4 floats at once. I did not do that here to keep it simple. - _vao.BindAttribute(_program.InPosition, _buffer); - _vao.BindAttribute(_program.InNormal, _buffer, 12); - _vao.BindAttribute(_program.InTangent, _buffer, 24); - _vao.BindAttribute(_program.InTexCoord, _buffer, 36); - - // set camera position - Camera.DefaultState.Position = new Vector3(0,0,3); - Camera.ResetToDefault(); - - // set state - GL.ClearColor(0.2f, 0f, 0.4f, 0f); - GL.PointSize(10f); - GL.Disable(EnableCap.Dither); - GL.FrontFace(FrontFaceDirection.Ccw); - GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill); - GL.PolygonMode(MaterialFace.Back, PolygonMode.Line); - } - - protected void OnResize(object sender, EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - } - - protected void OnUpdateFrame(object sender, FrameEventArgs e) - { - if (Keyboard[Key.Space]) Trace.WriteLine("GL: " + GL.GetError()); - var factor = (float)e.Time; - if (Keyboard[Key.Q]) - { - _materialScaleAndBiasAndShininess.X += factor; - Trace.WriteLine("Scale: " + _materialScaleAndBiasAndShininess.X + " Bias: " + _materialScaleAndBiasAndShininess.Y); - } - if (Keyboard[Key.A]) - { - _materialScaleAndBiasAndShininess.X -= factor; - Trace.WriteLine("Scale: " + _materialScaleAndBiasAndShininess.X + " Bias: " + _materialScaleAndBiasAndShininess.Y); - } - if (Keyboard[Key.W]) - { - _materialScaleAndBiasAndShininess.Y += factor; - Trace.WriteLine("Scale: " + _materialScaleAndBiasAndShininess.X + " Bias: " + _materialScaleAndBiasAndShininess.Y); - } - if (Keyboard[Key.S]) - { - _materialScaleAndBiasAndShininess.Y -= factor; - Trace.WriteLine("Scale: " + _materialScaleAndBiasAndShininess.X + " Bias: " + _materialScaleAndBiasAndShininess.Y); - } - if (Keyboard[Key.E]) - { - _materialScaleAndBiasAndShininess.Z += factor*100; - Trace.WriteLine("Shininess: " + _materialScaleAndBiasAndShininess.Z); - } - if (Keyboard[Key.D]) - { - _materialScaleAndBiasAndShininess.Z -= factor*100; - Trace.WriteLine("Shininess: " + _materialScaleAndBiasAndShininess.Z); - } - - _lightPosition.X = (-(Width / 2) + Mouse.X) / 100f; - _lightPosition.Y = ((Height / 2) - Mouse.Y) / 100f; - } - - protected void OnRenderFrame(object sender, FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - // first Material's uniforms - _program.Material_DiffuseAndHeight.BindTexture(TextureUnit.Texture0, _textureDiffuseHeight); - _program.Material_NormalAndGloss.BindTexture(TextureUnit.Texture1, _textureNormalGloss); - _program.Material_ScaleBiasShininess.Set(_materialScaleAndBiasAndShininess); - - // the rest are vectors - _program.Camera_Position.Set(Camera.State.Position); - _program.Light_Position.Set(_lightPosition); - _program.Light_DiffuseColor.Set(_lightDiffuse); - _program.Light_SpecularColor.Set(_lightSpecular); - - // set up matrices - SetupPerspective(); - var normalMatrix = new Matrix3(ModelView).Inverted(); - normalMatrix.Transpose(); - _program.NormalMatrix.Set(normalMatrix); - _program.ModelViewMatrix.Set(ModelView); - _program.ModelViewProjectionMatrix.Set(ModelView * Projection); - - // render - _vao.DrawArrays(PrimitiveType.TriangleStrip, 0, _buffer.ElementCount); - - SwapBuffers(); - } - } -} diff --git a/Examples/AdvancedExamples/RenderToTextureExample.cs b/Examples/AdvancedExamples/RenderToTextureExample.cs deleted file mode 100644 index e4e196e..0000000 --- a/Examples/AdvancedExamples/RenderToTextureExample.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Drawing; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using ObjectTK.Textures; -using ObjectTK.Tools.Shapes; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.AdvancedExamples -{ - [ExampleProject("Render to texture")] - public class RenderToTextureExample - : ExampleWindow - { - private const int FramebufferWidth = 400; - private const int FramebufferHeight = 400; - - private Framebuffer _framebuffer; - private Renderbuffer _depthBuffer; - private Texture2D _texture; - - private SimpleColorProgram _colorProgram; - private SimpleTextureProgram _textureProgram; - - private ColorCube _cube; - private TexturedQuad _quad; - - private VertexArray _cubeVao; - private VertexArray _quadVao; - - public RenderToTextureExample() - { - Load += OnLoad; - RenderFrame += OnRenderFrame; - } - - private void OnLoad(object sender, EventArgs e) - { - // initialize and bind framebuffer - _framebuffer = new Framebuffer(); - _framebuffer.Bind(FramebufferTarget.Framebuffer); - - // initialize a renderbuffer and bind it to the depth attachment - // to support depth testing while rendering to the texture - _depthBuffer = new Renderbuffer(); - _depthBuffer.Init(RenderbufferStorage.DepthComponent, FramebufferWidth, FramebufferHeight); - _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, _depthBuffer); - - // initialize texture and bind it to the color attachment - _texture = new Texture2D(SizedInternalFormat.Rgba8, FramebufferWidth, FramebufferHeight, 1); - _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, _texture); - Framebuffer.Unbind(FramebufferTarget.Framebuffer); - - // initialize demonstration geometry - _cube = new ColorCube(); - _cube.UpdateBuffers(); - _quad = new TexturedQuad(); - _quad.UpdateBuffers(); - - // initialize shaders - _colorProgram = ProgramFactory.Create<SimpleColorProgram>(); - _textureProgram = ProgramFactory.Create<SimpleTextureProgram>(); - - // set up vertex attributes for the cube - _cubeVao = new VertexArray(); - _cubeVao.Bind(); - _cubeVao.BindAttribute(_colorProgram.InPosition, _cube.VertexBuffer); - _cubeVao.BindAttribute(_colorProgram.InColor, _cube.ColorBuffer); - _cubeVao.BindElementBuffer(_cube.IndexBuffer); - - // set up vertex attributes for the quad - _quadVao = new VertexArray(); - _quadVao.Bind(); - _quadVao.BindAttribute(_textureProgram.InPosition, _quad.VertexBuffer); - _quadVao.BindAttribute(_textureProgram.InTexCoord, _quad.TexCoordBuffer); - - // set camera position - Camera.DefaultState.Position = new Vector3(0,0,3); - Camera.ResetToDefault(); - - // enable depth testing - GL.Enable(EnableCap.DepthTest); - } - - private void OnRenderFrame(object sender, FrameEventArgs e) - { - // set up render to texture - _framebuffer.Bind(FramebufferTarget.Framebuffer); - GL.Viewport(0, 0, FramebufferWidth, FramebufferHeight); - GL.ClearColor(Color.Black); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - // render rotating cube to texture - _colorProgram.Use(); - _colorProgram.ModelViewProjectionMatrix.Set( - Matrix4.CreateRotationX((float) FrameTimer.TimeRunning/1000) - * Matrix4.CreateRotationY((float) FrameTimer.TimeRunning/1000) - * Matrix4.CreateTranslation(0,0,-5) - * Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, FramebufferWidth/(float)FramebufferHeight, 0.1f, 100)); - _cubeVao.Bind(); - _cubeVao.DrawElements(PrimitiveType.Triangles, _cube.IndexBuffer.ElementCount); - - // reset to default framebuffer - Framebuffer.Unbind(FramebufferTarget.Framebuffer); - - // set up viewport for the window - GL.Viewport(0, 0, Width, Height); - GL.ClearColor(Color.MidnightBlue); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - SetupPerspective(); - - // render quad with texture - _textureProgram.Use(); - _textureProgram.ModelViewProjectionMatrix.Set(ModelView * Projection); - _quadVao.Bind(); - _quadVao.DrawArrays(PrimitiveType.TriangleStrip, 0, _quad.VertexBuffer.ElementCount); - - // swap buffers - SwapBuffers(); - } - } -} \ No newline at end of file diff --git a/Examples/BasicExamples/BufferLayoutTexturingExample.cs b/Examples/BasicExamples/BufferLayoutTexturingExample.cs deleted file mode 100644 index 3cb316b..0000000 --- a/Examples/BasicExamples/BufferLayoutTexturingExample.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Drawing; -using System.Runtime.InteropServices; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using ObjectTK.Textures; -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.BasicExamples -{ - [ExampleProject("Custom buffer memory layout and simple texturing")] - public class BufferLayoutTexturingExample - : ExampleWindow - { - /// <summary> - /// Defines a custom struct which is uploaded to a buffer object. - /// The StructLayout attributes makes sure that the order of data in memory is like it is defined here. - /// To prevent errors with byte-offsets read up on "packing". - /// </summary> - [StructLayout(LayoutKind.Sequential)] - private struct Vertex - { - public Vector3 Position; - public Vector2 TexCoord; - - public Vertex(float x, float y, float z, float u, float v) - { - Position = new Vector3(x,y,z); - TexCoord = new Vector2(u,v); - } - } - - private Texture2D _texture; - private Sampler _sampler; - private SimpleTextureProgram _program; - private Buffer<Vertex> _vbo; - private VertexArray _vao; - private bool _enableMipmapping; - - public BufferLayoutTexturingExample() - { - Load += OnLoad; - RenderFrame += OnRenderFrame; - KeyDown += OnKeyDown; - _enableMipmapping = true; - } - - private void OnKeyDown(object sender, KeyboardKeyEventArgs e) - { - switch (e.Key) - { - case Key.Space: _enableMipmapping = !_enableMipmapping; break; - } - } - - private void OnLoad(object sender, EventArgs e) - { - // load texture from file - using (var bitmap = new Bitmap("Data/Textures/checker.jpg")) - { - BitmapTexture.CreateCompatible(bitmap, out _texture); - _texture.LoadBitmap(bitmap); - } - _texture.GenerateMipMaps(); - - // initialize sampler - _sampler = new Sampler(); - _sampler.SetWrapMode(TextureWrapMode.Repeat); - - // create vertex data for a big plane - const int a = 10; - const int b = 10; - var vertices = new[] - { - new Vertex(-a, 0,-a, 0, 0), - new Vertex( a, 0,-a, b, 0), - new Vertex(-a, 0, a, 0, b), - new Vertex( a, 0, a, b, b) - }; - - // create buffer object and upload vertex data - _vbo = new Buffer<Vertex>(); - _vbo.Init(BufferTarget.ArrayBuffer, vertices); - - // initialize shader - _program = ProgramFactory.Create<SimpleTextureProgram>(); - // activate shader program - _program.Use(); - // bind sampler - _sampler.Bind(TextureUnit.Texture0); - // bind texture - _program.Texture.BindTexture(TextureUnit.Texture0, _texture); - // which is equivalent to - //_program.Texture.Set(TextureUnit.Texture0); - //_texture.Bind(TextureUnit.Texture0); - - // set up vertex array and attributes - _vao = new VertexArray(); - _vao.Bind(); - // memory layout of our data is XYZUVXYZUV... - // the buffer abstraction knows the total size of one "pack" of vertex data - // and if a vertex attribute is bound without further arguments the first N elements are taken from each pack - // where N is provided via the VertexAttribAttribute on the program property: - _vao.BindAttribute(_program.InPosition, _vbo); - // if data should not be taken from the start of each pack, the offset must be given in bytes - // to reach the texture coordinates UV the XYZ coordinates must be skipped, that is 3 floats, i.e. an offset of 12 bytes is needed - _vao.BindAttribute(_program.InTexCoord, _vbo, 12); - // if needed all the available arguments can be specified manually, e.g. - //_vao.BindAttribute(_program.InTexCoord, _vbo, 2, VertexAttribPointerType.Float, Marshal.SizeOf(typeof(Vertex)), 12, false); - - // set default camera - Camera.DefaultState.Position = new Vector3(0, 0.5f, 3); - Camera.ResetToDefault(); - - // set a nice clear color - GL.ClearColor(Color.MidnightBlue); - } - - private void OnRenderFrame(object sender, FrameEventArgs e) - { - // set up viewport - GL.Viewport(0, 0, Width, Height); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - SetupPerspective(); - - // enable/disable mipmapping on the sampler - _sampler.SetParameter(SamplerParameterName.TextureMinFilter, - (int)(_enableMipmapping ? TextureMinFilter.NearestMipmapLinear : TextureMinFilter.Nearest)); - - // set transformation matrix - _program.ModelViewProjectionMatrix.Set(ModelView*Projection); - // render vertex data - _vao.DrawArrays(PrimitiveType.TriangleStrip, 0, _vbo.ElementCount); - - // swap buffers - SwapBuffers(); - } - } -} \ No newline at end of file diff --git a/Examples/BasicExamples/MinimalExample.cs b/Examples/BasicExamples/MinimalExample.cs deleted file mode 100644 index 17dc7c1..0000000 --- a/Examples/BasicExamples/MinimalExample.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Drawing; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.BasicExamples -{ - [ExampleProject("Minimal example on shader and buffer usage")] - public class MinimalExample - : ExampleWindow - { - private ExampleProgram _program; - private VertexArray _vao; - private Buffer<Vector3> _vbo; - - public MinimalExample() - { - Load += OnLoad; - Unload += OnUnload; - RenderFrame += OnRenderFrame; - } - - private void OnLoad(object sender, EventArgs e) - { - // initialize shader (load sources, create/compile/link shader program, error checking) - // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes - _program = ProgramFactory.Create<ExampleProgram>(); - // this program will be used all the time so just activate it once and for all - _program.Use(); - - // create vertices for a triangle - var vertices = new[] { new Vector3(-1,-1,0), new Vector3(1,-1,0), new Vector3(0,1,0) }; - - // create buffer object and upload vertex data - _vbo = new Buffer<Vector3>(); - _vbo.Init(BufferTarget.ArrayBuffer, vertices); - - // create and bind a vertex array - _vao = new VertexArray(); - _vao.Bind(); - // set up binding of the shader variable to the buffer object - _vao.BindAttribute(_program.InPosition, _vbo); - - // set camera position - Camera.DefaultState.Position = new Vector3(0,0,3); - Camera.ResetToDefault(); - - // set a nice clear color - GL.ClearColor(Color.MidnightBlue); - } - - private void OnUnload(object sender, EventArgs e) - { - // Always make sure to properly dispose gl resources to prevent memory leaks. - // Most of the examples do not explicitly dispose resources, because - // the base class (ExampleWindow) calls GLResource.DisposeAll(this). - // This will automatically dispose all objects referenced by class fields - // which derive from GLResource. Everything else still has to be disposed manually. - _program.Dispose(); - _vao.Dispose(); - _vbo.Dispose(); - } - - private void OnRenderFrame(object sender, FrameEventArgs e) - { - // set up viewport - GL.Viewport(0, 0, Width, Height); - // clear the back buffer - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - // set up modelview and perspective matrix - SetupPerspective(); - - // calculate the MVP matrix and set it to the shaders uniform - _program.ModelViewProjectionMatrix.Set(ModelView*Projection); - // draw the buffer which contains the triangle - _vao.DrawArrays(PrimitiveType.Triangles, 0, _vbo.ElementCount); - - // swap buffers - SwapBuffers(); - } - } -} \ No newline at end of file diff --git a/Examples/BasicExamples/RotatingTexturedCubeExample.cs b/Examples/BasicExamples/RotatingTexturedCubeExample.cs deleted file mode 100644 index 739f4d3..0000000 --- a/Examples/BasicExamples/RotatingTexturedCubeExample.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Diagnostics; -using System.Drawing; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using ObjectTK.Textures; -using ObjectTK.Tools.Shapes; -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.BasicExamples -{ - [ExampleProject("Rotating textured cube rendering")] - public class RotatingTexturedCubeExample - : ExampleWindow - { - private Texture2D _texture; - - private SimpleTextureProgram _textureProgram; - - private TexturedCube _cube; - private VertexArray _cubeVao; - - private Matrix4 _baseView; - private Matrix4 _objectView; - - private Vector3[] _rotateVectors = new[] { Vector3.Zero, Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ, Vector3.One }; - private const int _defaultRotateIndex = 4; - - private int _rotateIndex = _defaultRotateIndex; - private readonly Stopwatch _stopwatch = new Stopwatch(); - - public RotatingTexturedCubeExample() - { - Load += OnLoad; - RenderFrame += OnRenderFrame; - KeyDown += OnKeyDown; - } - - private void OnKeyDown(object sender, KeyboardKeyEventArgs e) - { - switch (e.Key) - { - case Key.R: - _objectView = _baseView = Matrix4.Identity; - _rotateIndex = _defaultRotateIndex; - _stopwatch.Restart(); - break; - - case Key.Space: - _baseView = _objectView; - _rotateIndex = (_rotateIndex + 1) % _rotateVectors.Length; - _stopwatch.Restart(); - break; - - case Key.Number0: - case Key.Number1: - case Key.Number2: - case Key.Number3: - case Key.Number4: - _baseView = _objectView; - _rotateIndex = (e.Key - Key.Number0) % _rotateVectors.Length; - _stopwatch.Restart(); - break; - } - } - - private void OnLoad(object sender, EventArgs e) - { - // load texture from file - using (var bitmap = new Bitmap("Data/Textures/crate.png")) - { - BitmapTexture.CreateCompatible(bitmap, out _texture); - _texture.LoadBitmap(bitmap); - } - - // initialize shaders - _textureProgram = ProgramFactory.Create<SimpleTextureProgram>(); - - // initialize cube object and base view matrix - _objectView = _baseView = Matrix4.Identity; - - // initialize demonstration geometry - _cube = new TexturedCube(); - _cube.UpdateBuffers(); - - // set up vertex attributes for the quad - _cubeVao = new VertexArray(); - _cubeVao.Bind(); - _cubeVao.BindAttribute(_textureProgram.InPosition, _cube.VertexBuffer); - _cubeVao.BindAttribute(_textureProgram.InTexCoord, _cube.TexCoordBuffer); - - // Enable culling, our cube vertices are defined inside out, so we flip them - GL.Enable(EnableCap.CullFace); - GL.CullFace(CullFaceMode.Back); - - // initialize camera position - Camera.DefaultState.Position = new Vector3(0, 0, 4); - Camera.ResetToDefault(); - - // set nice clear color - GL.ClearColor(Color.MidnightBlue); - - _stopwatch.Restart(); - } - - private void OnRenderFrame(object sender, OpenTK.FrameEventArgs e) - { - // set up viewport - GL.Viewport(0, 0, Width, Height); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - SetupPerspective(); - - // determinate object view rotation vectors and apply them - _objectView = _baseView; - var rotation = _rotateVectors[_rotateIndex]; - if (rotation != Vector3.Zero) - _objectView *= Matrix4.CreateFromAxisAngle(_rotateVectors[_rotateIndex], (float)(_stopwatch.Elapsed.TotalSeconds * 1.0)); - - // set transformation matrix - _textureProgram.Use(); - _textureProgram.ModelViewProjectionMatrix.Set(_objectView * ModelView * Projection); - - // render cube with texture - _cubeVao.Bind(); - _cubeVao.DrawArrays(_cube.DefaultMode, 0, _cube.VertexBuffer.ElementCount); - - // swap buffers - SwapBuffers(); - } - } -} diff --git a/Examples/BasicExamples/SkyboxExample.cs b/Examples/BasicExamples/SkyboxExample.cs deleted file mode 100644 index 59d20c7..0000000 --- a/Examples/BasicExamples/SkyboxExample.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Drawing; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using ObjectTK.Textures; -using ObjectTK.Tools.Shapes; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.BasicExamples -{ - [ExampleProject("Skybox rendering with cube map texture")] - public class SkyboxExample - : ExampleWindow - { - private SkyboxProgram _program; - private TextureCubemap _skybox; - private VertexArray _vao; - private Cube _cube; - - public SkyboxExample() - { - Load += OnLoad; - Unload += OnUnload; - RenderFrame += OnRender; - } - - private void OnLoad(object sender, EventArgs e) - { - // initialize shader - _program = ProgramFactory.Create<SkyboxProgram>(); - // initialize cube shape - _cube = new Cube(); - _cube.UpdateBuffers(); - // initialize vertex array and attributes - _vao = new VertexArray(); - _vao.Bind(); - _vao.BindAttribute(_program.InPosition, _cube.VertexBuffer); - _vao.BindElementBuffer(_cube.IndexBuffer); - // create cubemap texture and load all faces - for (var i = 0; i < 6; i++) - { - using (var bitmap = new Bitmap(string.Format("Data/Textures/city{0}.jpg", i))) - { - bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); - if (_skybox == null) BitmapTexture.CreateCompatible(bitmap, out _skybox, 1); - _skybox.LoadBitmap(bitmap, i); - } - } - // activate shader and bind texture to it - _program.Use(); - _program.Texture.BindTexture(TextureUnit.Texture0, _skybox); - // enable seamless filtering to reduce artifacts at the edges of the cube faces - GL.Enable(EnableCap.TextureCubeMapSeamless); - // cull front faces because we are inside the cube - // this is not really necessary but removes some artifacts when the user leaves the cube - // which should be impossible for a real skybox, but in this demonstration it is possible by zooming out - GL.Enable(EnableCap.CullFace); - GL.CullFace(CullFaceMode.Front); - // set a nice clear color - GL.ClearColor(Color.MidnightBlue); - } - - private void OnUnload(object sender, EventArgs e) - { - _cube.VertexBuffer.Dispose(); - _cube.IndexBuffer.Dispose(); - } - - private void OnRender(object sender, FrameEventArgs e) - { - // set up viewport - GL.Viewport(0, 0, Width, Height); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - SetupPerspective(); - - // note: normally you want to clear the translation part of the ModelView matrix to prevent the user from leaving the cube - // to do that you can use ModelView.ClearTranslation() instead of the unmodified ModelView matrix - _program.ModelViewProjectionMatrix.Set(Matrix4.CreateScale(10) * ModelView * Projection); - // draw cube - _vao.DrawElements(_cube.DefaultMode, _cube.IndexBuffer.ElementCount); - - // swap buffers - SwapBuffers(); - } - } -} diff --git a/Examples/BasicExamples/TextureGridExample.cs b/Examples/BasicExamples/TextureGridExample.cs deleted file mode 100644 index 32fa4cc..0000000 --- a/Examples/BasicExamples/TextureGridExample.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System; -using System.Drawing; -using System.IO; -using System.Runtime.InteropServices; -using Examples.Shaders; -using ObjectTK.Buffers; -using ObjectTK.Shaders; -using ObjectTK.Textures; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.BasicExamples -{ - [ExampleProject("Textured grid rendering")] - public class TextureGridExample - : ExampleWindow - { - [StructLayout(LayoutKind.Sequential)] - public struct Minefield - { - public Vector2 Position; - public int State; - - public Minefield(float x, float y, int texture) - { - Position = new Vector2(x, y); - State = texture; - } - } - - private TextureGridProgram _gridProgram; - private Texture2DArray _textureArray; - private Buffer<Minefield> _buffer; - private VertexArray _vao; - - private readonly string[] _stateTextures = { "empty.png", "flag.png", "mine.png" }; - - const int FieldWidth = 100; - const int FieldHeight = 100; - - public TextureGridExample() - { - Load += OnLoad; - RenderFrame += OnRenderFrame; - } - - protected void OnLoad(object sender, EventArgs e) - { - // load textures into array - for (var i = 0; i < _stateTextures.Length; i++) - { - using (var bitmap = new Bitmap(Path.Combine("Data/Textures/", _stateTextures[i]))) - { - bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); - if (_textureArray == null) BitmapTexture.CreateCompatible(bitmap, out _textureArray, _stateTextures.Length, 1); - _textureArray.LoadBitmap(bitmap, i); - } - } - // initialize buffer - var field = new Minefield[FieldWidth*FieldHeight]; - for (var i = 0; i < field.Length; i++) - { - field[i] = new Minefield(i%FieldWidth, i/FieldHeight, i%_stateTextures.Length); - } - _buffer = new Buffer<Minefield>(); - _buffer.Init(BufferTarget.ArrayBuffer, field); - // load program - _gridProgram = ProgramFactory.Create<TextureGridProgram>(); - _gridProgram.Use(); - // bind the texture and set uniform - _gridProgram.TextureData.BindTexture(TextureUnit.Texture0, _textureArray); - // set up vertex array and attributes - _vao = new VertexArray(); - _vao.Bind(); - _vao.BindAttribute(_gridProgram.InPosition, _buffer); - _vao.BindAttribute(_gridProgram.InTexture, _buffer, 8); - // set nice clear color - GL.ClearColor(Color.MidnightBlue); - // initialize camera position - Camera.DefaultState.Position = new Vector3(0, 5, 15); - Camera.ResetToDefault(); - } - - protected void OnRenderFrame(object sender, FrameEventArgs frameEventArgs) - { - // setup stuff - GL.Viewport(0, 0, Width, Height); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - SetupPerspective(); - - // update MVP matrix and render grid - // also move camera rotation center to the center of the plane - // and rotate the plane from the x-y plane to the x-z plane - _gridProgram.ModelViewProjectionMatrix.Set( - Matrix4.CreateTranslation(-FieldWidth/2, -FieldHeight/2, 0) - * Matrix4.CreateRotationX(-(float)Math.PI/2) - * ModelView * Projection); - _vao.DrawArrays(PrimitiveType.Points, 0, _buffer.ElementCount); - - // swap buffers - SwapBuffers(); - } - } -} \ No newline at end of file diff --git a/Examples/Data/Shaders/Gravity.glsl b/Examples/Data/Shaders/Gravity.glsl deleted file mode 100644 index ef99a0d..0000000 --- a/Examples/Data/Shaders/Gravity.glsl +++ /dev/null @@ -1,51 +0,0 @@ --- Vertex -#version 140 -in vec3 InPosition; -in vec3 InVelocity; - -out vec3 OutPosition; -out vec3 OutVelocity; - -uniform float CenterMass; -uniform float TimeStep; -uniform mat4 ModelViewProjectionMatrix; - -void main() -{ - // calculate acceleration by gravity G*m/r^2 - // define G to be 1 or include it in CenterMass, doesn't matter - float acceleration = CenterMass / dot(InPosition, InPosition); - - // perform simple forward euler integration and - // stream position and velocity via transform feedback into the pong buffer - OutVelocity = InVelocity + acceleration * TimeStep * -normalize(InPosition); - OutPosition = InPosition + OutVelocity * TimeStep; - - // pass through current position - gl_Position = ModelViewProjectionMatrix * vec4(OutPosition,1); - gl_PointSize = clamp(length(acceleration)*2, 4, 10); -} - --- Fragment -#version 140 -out vec4 FragColor; - -in vec3 OutVelocity; - -//note: could use uniforms to set the colors from the application -const vec3 ColorFast = vec3(1.0, 0.0, 0.0); -const vec3 ColorSlow = vec3(0.0, 0.0, 1.0); - -void main() -{ - // calculate position within the point sprite - vec2 spritePosition = gl_PointCoord * 2 - vec2(1); - float r2 = dot(spritePosition, spritePosition); - - // skip pixels outside the circle - if (r2 > 1) discard; - - // draw fragment using a color gradient controlled by the total speed of the particle - // and darken the color the closer the current fragment is to the edge of the particles circle - FragColor = vec4(mix(ColorSlow, ColorFast, length(OutVelocity)) * (1.0 - r2), 1.0); -} \ No newline at end of file diff --git a/Examples/Data/Shaders/Parallax.glsl b/Examples/Data/Shaders/Parallax.glsl deleted file mode 100644 index c8424bf..0000000 --- a/Examples/Data/Shaders/Parallax.glsl +++ /dev/null @@ -1,107 +0,0 @@ --- Vertex -#version 150 -// Copyright (c) 2008 the OpenTK Team. See license.txt for legal bla - -// custom vertex attribute -in vec3 InPosition; -in vec3 InNormal; -in vec3 InTangent; -in vec2 InTexCoord; - -// transformation matrix -uniform mat4 ModelViewMatrix; -uniform mat4 ModelViewProjectionMatrix; -uniform mat3 NormalMatrix; - -// world uniforms -uniform vec3 Light_Position; -uniform vec3 Camera_Position; - -// MUST be written to for FS -out vec2 TexCoord; -out vec3 VaryingLightVector; -out vec3 VaryingEyeVector; - -void main() -{ - gl_Position = ModelViewProjectionMatrix * vec4(InPosition,1); - TexCoord = InTexCoord; - - vec3 nor = normalize(NormalMatrix * InNormal); - vec3 tan = normalize(NormalMatrix * InTangent); - vec3 bi = cross(nor, tan); - - // need positions in tangent space - vec3 vertex = vec3(ModelViewMatrix * vec4(InPosition,1)); - - vec3 temp = Light_Position - vertex; - VaryingLightVector.x = dot(temp, tan); // optimization, calculate dot products rather than building TBN matrix - VaryingLightVector.y = dot(temp, bi); - VaryingLightVector.z = dot(temp, nor); - - temp = Camera_Position - vertex; - VaryingEyeVector.x = dot(temp, tan); - VaryingEyeVector.y = dot(temp, bi); - VaryingEyeVector.z = dot(temp, nor); -} - --- Fragment -#version 150 -// Copyright (c) 2008 the OpenTK Team. See license.txt for legal bla - -// Material uniforms -uniform sampler2D Material_DiffuseAndHeight; -uniform sampler2D Material_NormalAndGloss; -uniform vec3 Material_ScaleBiasShininess; // x=Scale, y=Bias, z=Shininess - -// Light uniforms -uniform vec3 Light_DiffuseColor; -uniform vec3 Light_SpecularColor; - -// from VS -in vec2 TexCoord; -in vec3 VaryingLightVector; -in vec3 VaryingEyeVector; - -vec3 normal; - -void main() -{ - vec3 lightVector = normalize( VaryingLightVector ); - vec3 eyeVector = normalize( VaryingEyeVector ); - - // first, find the parallax displacement by reading only the height map - float parallaxOffset = texture2D( Material_DiffuseAndHeight, TexCoord.st ).a * - Material_ScaleBiasShininess.x - Material_ScaleBiasShininess.y; - // displace texcoords according to viewer - vec2 newTexCoords = TexCoord.st + ( parallaxOffset * eyeVector.xy ); - - // knowing the displacement, read RGB, Normal and Gloss - vec3 diffuseColor = texture2D( Material_DiffuseAndHeight, newTexCoords.st ).rgb; - vec4 temp = texture2D( Material_NormalAndGloss, newTexCoords.st ); - - // build a usable normal vector - normal.xy = temp.ag * 2.0 - 1.0; // swizzle alpha and green to x/y and scale to [-1..+1] - normal.z = sqrt( 1.0 - normal.x*normal.x - normal.y*normal.y ); // z = sqrt(1-x^2-y^2) - - // move other properties to be better readable - float gloss = temp.r; - - // float alpha = temp.b; - // if ( alpha < 0.2 ) // optimization: should move this test before reading RGB texture - // discard; - - // tweaked phong lighting - float lambert = max( dot( lightVector, normal ), 0.0 ); - - gl_FragColor = vec4( Light_DiffuseColor * diffuseColor, 1.0 ) * - lambert; - - if ( lambert > 0.0 ) - { - float specular = pow(clamp(dot(reflect(-lightVector, normal), eyeVector), 0.0, 1.0), - Material_ScaleBiasShininess.z ); - - gl_FragColor += vec4( Light_SpecularColor * diffuseColor, 1.0 ) * ( specular * gloss ); - } -} \ No newline at end of file diff --git a/Examples/Data/Shaders/SimpleColor.glsl b/Examples/Data/Shaders/SimpleColor.glsl deleted file mode 100644 index 33cd23c..0000000 --- a/Examples/Data/Shaders/SimpleColor.glsl +++ /dev/null @@ -1,25 +0,0 @@ --- Vertex -#version 140 -in vec3 InPosition; -in vec4 InColor; - -smooth out vec4 Color; - -uniform mat4 ModelViewProjectionMatrix; - -void main() -{ - gl_Position = ModelViewProjectionMatrix * vec4(InPosition,1); - Color = InColor; -} - --- Fragment -#version 140 -smooth in vec4 Color; - -out vec4 FragColor; - -void main() -{ - FragColor = Color; -} \ No newline at end of file diff --git a/Examples/Data/Shaders/SimpleTexture.glsl b/Examples/Data/Shaders/SimpleTexture.glsl deleted file mode 100644 index 5027b43..0000000 --- a/Examples/Data/Shaders/SimpleTexture.glsl +++ /dev/null @@ -1,31 +0,0 @@ --- Vertex -#version 140 -in vec3 InPosition; -in vec2 InTexCoord; - -smooth out vec2 TexCoord; - -uniform mat4 ModelViewProjectionMatrix; - -void main() -{ - // transform vertex position - gl_Position = ModelViewProjectionMatrix * vec4(InPosition,1); - // pass through texture coordinate - TexCoord = InTexCoord; -} - --- Fragment -#version 140 -smooth in vec2 TexCoord; - -out vec4 FragColor; - -uniform sampler2D Texture; -uniform bool RenderTexCoords = false; - -void main() -{ - if (RenderTexCoords) FragColor = vec4(TexCoord, 0, 1); - else FragColor = texture(Texture, TexCoord); -} \ No newline at end of file diff --git a/Examples/Data/Shaders/Skybox.glsl b/Examples/Data/Shaders/Skybox.glsl deleted file mode 100644 index 270b481..0000000 --- a/Examples/Data/Shaders/Skybox.glsl +++ /dev/null @@ -1,34 +0,0 @@ --- Vertex -#version 330 -in vec3 InPosition; - -smooth out vec3 TexCoord; - -uniform mat4 ModelViewProjectionMatrix; - -void main() -{ - vec4 position = ModelViewProjectionMatrix * vec4(InPosition, 1.0); - // setting the z coordinate to w forces the position to be on the far clipping-plane - // because after perspective divide, which is a division by w, the result is 1 - gl_Position = position.xyww; - // interpolate the positions between the vertices - // after rasterization we in fact get the position on the cubes surface for each fragment - TexCoord = InPosition; -} - --- Fragment -#version 330 -smooth in vec3 TexCoord; - -out vec4 FragColor; - -uniform samplerCube Texture; - -void main() -{ - // visualize the interpolated position, i.e. texture coordinate - //FragColor = vec4(TexCoord, 1); - // sample from the cube map texture - FragColor = texture(Texture, TexCoord); -} \ No newline at end of file diff --git a/Examples/Data/Shaders/TextureGrid.glsl b/Examples/Data/Shaders/TextureGrid.glsl deleted file mode 100644 index df95cca..0000000 --- a/Examples/Data/Shaders/TextureGrid.glsl +++ /dev/null @@ -1,63 +0,0 @@ --- Vertex -#version 140 -in vec2 InPosition; -in int InTexture; - -flat out vec2 Position; -flat out int Texture; - -void main() -{ - Position = InPosition; - Texture = InTexture; -} - --- Geometry -#version 150 - -// this shader processes points and outputs two triangles (a quad) -layout (points) in; -layout (triangle_strip, max_vertices = 4) out; - -flat in vec2 Position[1]; -flat in int Texture[1]; - -smooth out vec2 TextureCoordinates; -flat out int TextureLayer; - -uniform mat4 ModelViewProjectionMatrix; - -void main() -{ - TextureLayer = Texture[0]; - vec4 p = vec4(Position[0], 0, 1); - float d = 0.5; - gl_Position = ModelViewProjectionMatrix * (p + vec4(-d,-d, 0, 0)); - TextureCoordinates = vec2(0,0); - EmitVertex(); - gl_Position = ModelViewProjectionMatrix * (p + vec4( d,-d, 0, 0)); - TextureCoordinates = vec2(1,0); - EmitVertex(); - gl_Position = ModelViewProjectionMatrix * (p + vec4(-d, d, 0, 0)); - TextureCoordinates = vec2(0,1); - EmitVertex(); - gl_Position = ModelViewProjectionMatrix * (p + vec4( d, d, 0, 0)); - TextureCoordinates = vec2(1,1); - EmitVertex(); - EndPrimitive(); -} - --- Fragment -#version 140 -smooth in vec2 TextureCoordinates; -flat in int TextureLayer; - -out vec4 FragColor; - -uniform sampler2DArray TextureData; - -void main() -{ - FragColor = texture(TextureData, vec3(TextureCoordinates, TextureLayer)); - //FragColor = vec4(TextureCoordinates.rg, TextureLayer/220.0, 1); -} \ No newline at end of file diff --git a/Examples/Data/Textures/checker.jpg b/Examples/Data/Textures/checker.jpg deleted file mode 100644 index bf439b9..0000000 Binary files a/Examples/Data/Textures/checker.jpg and /dev/null differ diff --git a/Examples/Data/Textures/city0.jpg b/Examples/Data/Textures/city0.jpg deleted file mode 100644 index 80d32d6..0000000 Binary files a/Examples/Data/Textures/city0.jpg and /dev/null differ diff --git a/Examples/Data/Textures/city1.jpg b/Examples/Data/Textures/city1.jpg deleted file mode 100644 index 7dd1345..0000000 Binary files a/Examples/Data/Textures/city1.jpg and /dev/null differ diff --git a/Examples/Data/Textures/city2.jpg b/Examples/Data/Textures/city2.jpg deleted file mode 100644 index eb8ea7a..0000000 Binary files a/Examples/Data/Textures/city2.jpg and /dev/null differ diff --git a/Examples/Data/Textures/city3.jpg b/Examples/Data/Textures/city3.jpg deleted file mode 100644 index 7106e93..0000000 Binary files a/Examples/Data/Textures/city3.jpg and /dev/null differ diff --git a/Examples/Data/Textures/city4.jpg b/Examples/Data/Textures/city4.jpg deleted file mode 100644 index 2b5b017..0000000 Binary files a/Examples/Data/Textures/city4.jpg and /dev/null differ diff --git a/Examples/Data/Textures/city5.jpg b/Examples/Data/Textures/city5.jpg deleted file mode 100644 index 159d942..0000000 Binary files a/Examples/Data/Textures/city5.jpg and /dev/null differ diff --git a/Examples/Data/Textures/crate.png b/Examples/Data/Textures/crate.png deleted file mode 100644 index 819d8d4..0000000 Binary files a/Examples/Data/Textures/crate.png and /dev/null differ diff --git a/Examples/Data/Textures/empty.png b/Examples/Data/Textures/empty.png deleted file mode 100644 index 3b332df..0000000 Binary files a/Examples/Data/Textures/empty.png and /dev/null differ diff --git a/Examples/Data/Textures/flag.png b/Examples/Data/Textures/flag.png deleted file mode 100644 index 648432d..0000000 Binary files a/Examples/Data/Textures/flag.png and /dev/null differ diff --git a/Examples/Data/Textures/mine.png b/Examples/Data/Textures/mine.png deleted file mode 100644 index 6d3fab9..0000000 Binary files a/Examples/Data/Textures/mine.png and /dev/null differ diff --git a/Examples/Data/Textures/swizzled-rock-diffuse-height.dds b/Examples/Data/Textures/swizzled-rock-diffuse-height.dds deleted file mode 100644 index c7557fa..0000000 Binary files a/Examples/Data/Textures/swizzled-rock-diffuse-height.dds and /dev/null differ diff --git a/Examples/Data/Textures/swizzled-rock-normal-gloss.dds b/Examples/Data/Textures/swizzled-rock-normal-gloss.dds deleted file mode 100644 index 5ca89a8..0000000 Binary files a/Examples/Data/Textures/swizzled-rock-normal-gloss.dds and /dev/null differ diff --git a/Examples/ExampleBrowser.Designer.cs b/Examples/ExampleBrowser.Designer.cs deleted file mode 100644 index 5537c3d..0000000 --- a/Examples/ExampleBrowser.Designer.cs +++ /dev/null @@ -1,78 +0,0 @@ -namespace Examples -{ - partial class ExampleBrowser - { - /// <summary> - /// Required designer variable. - /// </summary> - private System.ComponentModel.IContainer components = null; - - /// <summary> - /// Clean up any resources being used. - /// </summary> - /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// <summary> - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// </summary> - private void InitializeComponent() - { - this.treeViewExamples = new System.Windows.Forms.TreeView(); - this.label1 = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // treeViewExamples - // - this.treeViewExamples.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.treeViewExamples.Location = new System.Drawing.Point(12, 25); - this.treeViewExamples.Name = "treeViewExamples"; - this.treeViewExamples.Size = new System.Drawing.Size(344, 297); - this.treeViewExamples.TabIndex = 1; - this.treeViewExamples.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.TreeViewExamples_NodeMouseDoubleClick); - this.treeViewExamples.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TreeViewExamples_KeyDown); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(12, 9); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(185, 13); - this.label1.TabIndex = 0; - this.label1.Text = "Example projects: Double-click to run."; - // - // ExampleBrowser - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(368, 334); - this.Controls.Add(this.label1); - this.Controls.Add(this.treeViewExamples); - this.KeyPreview = true; - this.Name = "ExampleBrowser"; - this.Text = "ObjectTK example projects"; - this.Load += new System.EventHandler(this.ExampleBrowser_Load); - this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ExampleBrowser_KeyDown); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.TreeView treeViewExamples; - private System.Windows.Forms.Label label1; - } -} \ No newline at end of file diff --git a/Examples/ExampleBrowser.cs b/Examples/ExampleBrowser.cs deleted file mode 100644 index 9bb31d1..0000000 --- a/Examples/ExampleBrowser.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Windows.Forms; -using ObjectTK; -using OpenTK; - -namespace Examples -{ - public partial class ExampleBrowser - : Form - { - private Dictionary<string, Type> _examples; - - public ExampleBrowser() - { - InitializeComponent(); - } - - private void ExampleBrowser_Load(object sender, EventArgs e) - { - // find example projects - var baseType = typeof (ExampleWindow); - var types = Assembly.GetExecutingAssembly().GetTypes().Where(_ => _ != baseType && baseType.IsAssignableFrom(_)); - // add tree nodes for example projects - _examples = new Dictionary<string, Type>(); - foreach (var type in types) - { - // find or create node for namespace - var existingNodes = treeViewExamples.Nodes.Find(type.Namespace, false); - var node = existingNodes.Length > 0 - ? existingNodes[0] - : treeViewExamples.Nodes.Add(type.Namespace, type.Namespace); - // add node for this example and get the caption from the attribute - var captionAttribute = type.GetCustomAttributes<ExampleProjectAttribute>(false).FirstOrDefault(); - node.Nodes.Add(type.Name, captionAttribute == null ? type.Name : captionAttribute.Caption); - // remember example type - _examples.Add(type.Name, type); - } - // show all examples - treeViewExamples.ExpandAll(); - } - - private void ExampleBrowser_KeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Escape) Close(); - } - - private void TreeViewExamples_KeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Enter) RunExample(treeViewExamples.SelectedNode); - } - - private void TreeViewExamples_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) - { - RunExample(e.Node); - } - - private void RunExample(TreeNode node) - { - Type type; - if (!_examples.TryGetValue(node.Name, out type)) return; - // hide browser - Hide(); - // run the example - using (var exampleWindow = (GameWindow)Activator.CreateInstance(type)) - { - exampleWindow.Title = node.Text; - exampleWindow.Run(); - } - // show the browser again - Show(); - } - } -} diff --git a/Examples/ExampleBrowserEntry.cs b/Examples/ExampleBrowserEntry.cs deleted file mode 100644 index 34f7011..0000000 --- a/Examples/ExampleBrowserEntry.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Windows.Forms; -using log4net.Config; - -namespace Examples -{ - public static class ExampleBrowserEntry - { - [STAThread] - public static void Main() - { - // initialize log4net via app.config if available - if (ObjectTK.Logging.LogFactory.IsAvailable) - ConfigureLogging(); - - // show example browser - using (var browser = new ExampleBrowser()) - { - Application.Run(browser); - } - } - - public static void ConfigureLogging() - { - XmlConfigurator.Configure(); - } - } -} diff --git a/Examples/ExampleProjectAttribute.cs b/Examples/ExampleProjectAttribute.cs deleted file mode 100644 index 77e1e92..0000000 --- a/Examples/ExampleProjectAttribute.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace Examples -{ - [AttributeUsage(AttributeTargets.Class)] - public class ExampleProjectAttribute - : Attribute - { - public readonly string Caption; - - public ExampleProjectAttribute(string caption) - { - Caption = caption; - } - } -} \ No newline at end of file diff --git a/Examples/ExampleWindow.cs b/Examples/ExampleWindow.cs deleted file mode 100644 index b36e148..0000000 --- a/Examples/ExampleWindow.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using ObjectTK; -using ObjectTK.Shaders; -using ObjectTK.Tools; -using ObjectTK.Tools.Cameras; -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Input; - -namespace Examples -{ - /// <summary> - /// Provides common functionality for the examples. - /// </summary> - public class ExampleWindow - : DerpWindow - { - protected Camera Camera; - protected Matrix4 ModelView; - protected Matrix4 Projection; - protected string OriginalTitle { get; private set; } - - public ExampleWindow() - : base(800, 600, GraphicsMode.Default, "") - { - // disable vsync - VSync = VSyncMode.Off; - // set up camera - Camera = new Camera(); - Camera.SetBehavior(new ThirdPersonBehavior()); - Camera.DefaultState.Position.Z = 5; - Camera.ResetToDefault(); - Camera.Enable(this); - ResetMatrices(); - // hook up events - Load += OnLoad; - Unload += OnUnload; - KeyDown += OnKeyDown; - RenderFrame += OnRenderFrame; - } - - private void OnLoad(object sender, EventArgs e) - { - // maximize window - WindowState = WindowState.Maximized; - // remember original title - OriginalTitle = Title; - // set search path for shader files and extension - ProgramFactory.BasePath = "Data/Shaders/"; - ProgramFactory.Extension = "glsl"; - } - - private void OnUnload(object sender, EventArgs e) - { - // release all gl resources on unload - GLResource.DisposeAll(this); - } - - private void OnRenderFrame(object sender, FrameEventArgs e) - { - // display FPS in the window title - Title = string.Format("ObjectTK example: {0} - FPS {1}", OriginalTitle, FrameTimer.FpsBasedOnFramesRendered); - } - - private void OnKeyDown(object sender, KeyboardKeyEventArgs e) - { - // close window on escape press - if (e.Key == Key.Escape) Close(); - // reset camera to default position and orientation on R press - if (e.Key == Key.R) Camera.ResetToDefault(); - } - - /// <summary> - /// Resets the ModelView and Projection matrices to the identity. - /// </summary> - protected void ResetMatrices() - { - ModelView = Matrix4.Identity; - Projection = Matrix4.Identity; - } - - /// <summary> - /// Sets a perspective projection matrix and applies the camera transformation on the modelview matrix. - /// </summary> - protected void SetupPerspective() - { - // setup perspective projection - var aspectRatio = Width / (float)Height; - Projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 0.1f, 1000); - ModelView = Matrix4.Identity; - // apply camera transform - ModelView = Camera.GetCameraTransform(); - } - } -} \ No newline at end of file diff --git a/Examples/Examples.csproj b/Examples/Examples.csproj deleted file mode 100644 index 2490c61..0000000 --- a/Examples/Examples.csproj +++ /dev/null @@ -1,130 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> - <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> - <PropertyGroup> - <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> - <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProjectGuid>{B05720A6-8E0A-4D53-96D1-AA341AE0D0D5}</ProjectGuid> - <OutputType>WinExe</OutputType> - <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>Examples</RootNamespace> - <AssemblyName>Examples</AssemblyName> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <FileAlignment>512</FileAlignment> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <PlatformTarget>AnyCPU</PlatformTarget> - <DebugSymbols>true</DebugSymbols> - <DebugType>full</DebugType> - <Optimize>false</Optimize> - <OutputPath>bin\Debug\</OutputPath> - <DefineConstants>DEBUG;TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <PlatformTarget>AnyCPU</PlatformTarget> - <DebugType>pdbonly</DebugType> - <Optimize>true</Optimize> - <OutputPath>bin\Release\</OutputPath> - <DefineConstants>TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - </PropertyGroup> - <ItemGroup> - <Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\log4net.2.0.3\lib\net40-full\log4net.dll</HintPath> - </Reference> - <Reference Include="OpenTK, Version=1.1.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\OpenTK.1.1.1589.5942\lib\NET40\OpenTK.dll</HintPath> - </Reference> - <Reference Include="System" /> - <Reference Include="System.Core" /> - <Reference Include="System.Drawing" /> - <Reference Include="System.Windows.Forms" /> - </ItemGroup> - <ItemGroup> - <Compile Include="AdvancedExamples\FeedbackGravityExample.cs" /> - <Compile Include="AdvancedExamples\LoaderDDS.cs" /> - <Compile Include="AdvancedExamples\LoaderStatics.cs" /> - <Compile Include="AdvancedExamples\ParallaxMappingExample.cs" /> - <Compile Include="BasicExamples\RotatingTexturedCubeExample.cs" /> - <Compile Include="BasicExamples\TextureGridExample.cs" /> - <Compile Include="BasicExamples\SkyboxExample.cs" /> - <Compile Include="ExampleProjectAttribute.cs" /> - <Compile Include="Shaders\ParallaxProgram.cs" /> - <Compile Include="Shaders\SimpleColorProgram.cs" /> - <Compile Include="Shaders\SimpleTextureProgram.cs" /> - <Compile Include="Shaders\ExampleProgram.cs" /> - <Compile Include="AdvancedExamples\RenderToTextureExample.cs" /> - <Compile Include="BasicExamples\BufferLayoutTexturingExample.cs" /> - <Compile Include="BasicExamples\MinimalExample.cs" /> - <Compile Include="ExampleBrowser.cs"> - <SubType>Form</SubType> - </Compile> - <Compile Include="ExampleBrowser.Designer.cs"> - <DependentUpon>ExampleBrowser.cs</DependentUpon> - </Compile> - <Compile Include="ExampleWindow.cs" /> - <Compile Include="ExampleBrowserEntry.cs" /> - <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Shaders\SkyboxProgram.cs" /> - <Compile Include="Shaders\GravityProgram.cs" /> - <Compile Include="Shaders\TextureGridProgram.cs" /> - </ItemGroup> - <ItemGroup> - <None Include="Data\Shaders\ExampleShader.glsl" /> - <None Include="Data\Shaders\Gravity.glsl" /> - <None Include="Data\Shaders\Parallax.glsl" /> - <None Include="Data\Shaders\SimpleColor.glsl" /> - <None Include="Data\Shaders\SimpleTexture.glsl" /> - <None Include="app.config" /> - <None Include="Data\Shaders\Skybox.glsl" /> - <None Include="Data\Shaders\TextureGrid.glsl" /> - <None Include="packages.config" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\ObjectTK.Compiler\ObjectTK.Compiler.csproj"> - <Project>{abd0be84-792d-4f52-82e2-c869585b3c29}</Project> - <Name>ObjectTK.Compiler</Name> - </ProjectReference> - <ProjectReference Include="..\ObjectTK.Tools\ObjectTK.Tools.csproj"> - <Project>{E38997F8-7ECE-4B35-BB94-7E609F68D217}</Project> - <Name>ObjectTK.Tools</Name> - </ProjectReference> - <ProjectReference Include="..\ObjectTK\ObjectTK.csproj"> - <Project>{0ee3347b-1bbe-44ca-8295-22da13ae914a}</Project> - <Name>ObjectTK</Name> - </ProjectReference> - </ItemGroup> - <ItemGroup> - <Content Include="Data\Textures\checker.jpg" /> - <Content Include="Data\Textures\city0.jpg" /> - <Content Include="Data\Textures\city1.jpg" /> - <Content Include="Data\Textures\city2.jpg" /> - <Content Include="Data\Textures\city3.jpg" /> - <Content Include="Data\Textures\city4.jpg" /> - <Content Include="Data\Textures\city5.jpg" /> - <Content Include="Data\Textures\crate.png" /> - <Content Include="Data\Textures\empty.png" /> - <Content Include="Data\Textures\flag.png" /> - <Content Include="Data\Textures\mine.png" /> - <Content Include="Data\Textures\swizzled-rock-diffuse-height.dds" /> - <Content Include="Data\Textures\swizzled-rock-normal-gloss.dds" /> - </ItemGroup> - <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> - <PropertyGroup> - <PostBuildEvent>rd /Q /S "$(TargetDir)Data" -xcopy "$(ProjectDir)Data" "$(TargetDir)Data" /E /R /K /Y /I /D /H -"$(TargetDir)ObjectTKC.exe" "$(TargetPath)"</PostBuildEvent> - </PropertyGroup> - <!-- To modify your build process, add your task inside one of the targets below and uncomment it. - Other similar extension points exist, see Microsoft.Common.targets. - <Target Name="BeforeBuild"> - </Target> - <Target Name="AfterBuild"> - </Target> - --> -</Project> \ No newline at end of file diff --git a/Examples/Properties/AssemblyInfo.cs b/Examples/Properties/AssemblyInfo.cs deleted file mode 100644 index 820304a..0000000 --- a/Examples/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ObjectTK examples")] -[assembly: AssemblyDescription("Examples to demonstrate usage of ObjectTK")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("JcBernack")] -[assembly: AssemblyProduct("ObjectTK")] -[assembly: AssemblyCopyright("Copyright © 2014-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("eb0408f7-0a84-44e6-8118-8fd02e0c5243")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.*")] diff --git a/Examples/Shaders/ExampleProgram.cs b/Examples/Shaders/ExampleProgram.cs deleted file mode 100644 index 3d15ad6..0000000 --- a/Examples/Shaders/ExampleProgram.cs +++ /dev/null @@ -1,19 +0,0 @@ -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using ObjectTK.Shaders.Variables; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shaders -{ - [VertexShaderSource("ExampleShader.Vertex")] - [FragmentShaderSource("ExampleShader.Fragment")] - public class ExampleProgram - : Program - { - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InPosition { get; protected set; } - - public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; } - } -} \ No newline at end of file diff --git a/Examples/Shaders/GravityProgram.cs b/Examples/Shaders/GravityProgram.cs deleted file mode 100644 index 7efd1ff..0000000 --- a/Examples/Shaders/GravityProgram.cs +++ /dev/null @@ -1,32 +0,0 @@ -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using ObjectTK.Shaders.Variables; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shaders -{ - [VertexShaderSource("Gravity.Vertex")] - [FragmentShaderSource("Gravity.Fragment")] - public class GravityProgram - : TransformProgram - { - public GravityProgram() - { - // define transform feedback varyings and add padding to achieve 16-byte alignment with 3-component vectors - FeedbackVaryings(TransformFeedbackMode.InterleavedAttribs, OutPosition, SkipComponents1, OutVelocity, SkipComponents1); - } - - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InPosition { get; protected set; } - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InVelocity { get; protected set; } - - public TransformOut OutPosition { get; protected set; } - public TransformOut OutVelocity { get; protected set; } - - public Uniform<float> CenterMass { get; protected set; } - public Uniform<float> TimeStep { get; protected set; } - public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; } - } -} \ No newline at end of file diff --git a/Examples/Shaders/ParallaxProgram.cs b/Examples/Shaders/ParallaxProgram.cs deleted file mode 100644 index 737d617..0000000 --- a/Examples/Shaders/ParallaxProgram.cs +++ /dev/null @@ -1,38 +0,0 @@ -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using ObjectTK.Shaders.Variables; -using ObjectTK.Textures; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shaders -{ - [VertexShaderSource("Parallax.Vertex")] - [FragmentShaderSource("Parallax.Fragment")] - public class ParallaxProgram - : Program - { - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InPosition { get; protected set; } - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InNormal { get; protected set; } - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InTangent { get; protected set; } - [VertexAttrib(2, VertexAttribPointerType.Float)] - public VertexAttrib InTexCoord { get; protected set; } - - public Uniform<Matrix4> ModelViewMatrix { get; protected set; } - public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; } - public Uniform<Matrix3> NormalMatrix { get; protected set; } - - public Uniform<Vector3> Light_Position { get; protected set; } - public Uniform<Vector3> Camera_Position { get; protected set; } - - public TextureUniform<Texture2D> Material_DiffuseAndHeight { get; protected set; } - public TextureUniform<Texture2D> Material_NormalAndGloss { get; protected set; } - public Uniform<Vector3> Material_ScaleBiasShininess { get; protected set; } - - public Uniform<Vector3> Light_DiffuseColor { get; protected set; } - public Uniform<Vector3> Light_SpecularColor { get; protected set; } - } -} \ No newline at end of file diff --git a/Examples/Shaders/SimpleColorProgram.cs b/Examples/Shaders/SimpleColorProgram.cs deleted file mode 100644 index 67b1aa9..0000000 --- a/Examples/Shaders/SimpleColorProgram.cs +++ /dev/null @@ -1,21 +0,0 @@ -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using ObjectTK.Shaders.Variables; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shaders -{ - [VertexShaderSource("SimpleColor.Vertex")] - [FragmentShaderSource("SimpleColor.Fragment")] - public class SimpleColorProgram - : Program - { - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InPosition { get; protected set; } - [VertexAttrib(4, VertexAttribPointerType.UnsignedByte, true)] - public VertexAttrib InColor { get; protected set; } - - public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; } - } -} \ No newline at end of file diff --git a/Examples/Shaders/SimpleTextureProgram.cs b/Examples/Shaders/SimpleTextureProgram.cs deleted file mode 100644 index 4613e8e..0000000 --- a/Examples/Shaders/SimpleTextureProgram.cs +++ /dev/null @@ -1,25 +0,0 @@ -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using ObjectTK.Shaders.Variables; -using ObjectTK.Textures; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shaders -{ - [VertexShaderSource("SimpleTexture.Vertex")] - [FragmentShaderSource("SimpleTexture.Fragment")] - public class SimpleTextureProgram - : Program - { - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InPosition { get; protected set; } - [VertexAttrib(2, VertexAttribPointerType.Float)] - public VertexAttrib InTexCoord { get; protected set; } - - public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; } - - public TextureUniform<Texture2D> Texture { get; protected set; } - public Uniform<bool> RenderTexCoords { get; protected set; } - } -} \ No newline at end of file diff --git a/Examples/Shaders/SkyboxProgram.cs b/Examples/Shaders/SkyboxProgram.cs deleted file mode 100644 index 58ee6cf..0000000 --- a/Examples/Shaders/SkyboxProgram.cs +++ /dev/null @@ -1,21 +0,0 @@ -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using ObjectTK.Shaders.Variables; -using ObjectTK.Textures; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shaders -{ - [VertexShaderSource("Skybox.Vertex")] - [FragmentShaderSource("Skybox.Fragment")] - public class SkyboxProgram - : Program - { - [VertexAttrib(3, VertexAttribPointerType.Float)] - public VertexAttrib InPosition { get; protected set; } - - public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; } - public TextureUniform<TextureCubemap> Texture { get; protected set; } - } -} \ No newline at end of file diff --git a/Examples/Shaders/TextureGridProgram.cs b/Examples/Shaders/TextureGridProgram.cs deleted file mode 100644 index 8cb2311..0000000 --- a/Examples/Shaders/TextureGridProgram.cs +++ /dev/null @@ -1,24 +0,0 @@ -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using ObjectTK.Shaders.Variables; -using ObjectTK.Textures; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shaders -{ - [VertexShaderSource("TextureGrid.Vertex")] - [GeometryShaderSource("TextureGrid.Geometry")] - [FragmentShaderSource("TextureGrid.Fragment")] - public class TextureGridProgram - : Program - { - [VertexAttrib(2, VertexAttribPointerType.Float)] - public VertexAttrib InPosition { get; protected set; } - [VertexAttrib(1, VertexAttribPointerType.Float)] - public VertexAttrib InTexture { get; protected set; } - - public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; } - public TextureUniform<Texture2DArray> TextureData { get; protected set; } - } -} \ No newline at end of file diff --git a/Examples/app.config b/Examples/app.config deleted file mode 100644 index 7db8b13..0000000 --- a/Examples/app.config +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<configuration> - <configSections> - <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> - </configSections> - <log4net> - <appender name="LogFileAppender" type="log4net.Appender.FileAppender"> - <param name="File" value="Log.txt"/> - <param name="AppendToFile" value="false"/> - <layout type="log4net.Layout.PatternLayout"> - <param name="Header" value="[Application startup]
" /> - <param name="Footer" value="[Application shutdown]
" /> - <param name="ConversionPattern" value="%date [%thread] %-5level %class %message%newline" /> - </layout> - </appender> - <root> - <level value="INFO"/> - <appender-ref ref="LogFileAppender"/> - </root> - </log4net> - <startup> - <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> - </startup> -</configuration> diff --git a/Examples/packages.config b/Examples/packages.config deleted file mode 100644 index 338f3df..0000000 --- a/Examples/packages.config +++ /dev/null @@ -1,5 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<packages> - <package id="log4net" version="2.0.3" targetFramework="net40" /> - <package id="OpenTK" version="1.1.1589.5942" targetFramework="net40" /> -</packages> \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 5341a84..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jan Christoph Bernack for the Open Toolkit project. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/ObjectTK.Compiler/ObjectTK.Compiler.csproj b/ObjectTK.Compiler/ObjectTK.Compiler.csproj deleted file mode 100644 index 56d0f91..0000000 --- a/ObjectTK.Compiler/ObjectTK.Compiler.csproj +++ /dev/null @@ -1,64 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> - <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> - <PropertyGroup> - <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> - <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProjectGuid>{ABD0BE84-792D-4F52-82E2-C869585B3C29}</ProjectGuid> - <OutputType>Exe</OutputType> - <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>ObjectTK.Compiler</RootNamespace> - <AssemblyName>ObjectTKC</AssemblyName> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <FileAlignment>512</FileAlignment> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <PlatformTarget>AnyCPU</PlatformTarget> - <DebugSymbols>true</DebugSymbols> - <DebugType>full</DebugType> - <Optimize>false</Optimize> - <OutputPath>bin\Debug\</OutputPath> - <DefineConstants>DEBUG;TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <PlatformTarget>AnyCPU</PlatformTarget> - <DebugType>pdbonly</DebugType> - <Optimize>true</Optimize> - <OutputPath>bin\Release\</OutputPath> - <DefineConstants>TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - </PropertyGroup> - <ItemGroup> - <Reference Include="OpenTK, Version=1.1.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\OpenTK.1.1.1589.5942\lib\NET40\OpenTK.dll</HintPath> - </Reference> - <Reference Include="System" /> - <Reference Include="System.Core" /> - </ItemGroup> - <ItemGroup> - <Compile Include="ShaderCompiler.cs" /> - <Compile Include="Properties\AssemblyInfo.cs" /> - </ItemGroup> - <ItemGroup> - <None Include="app.config" /> - <None Include="packages.config" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\ObjectTK\ObjectTK.csproj"> - <Project>{0EE3347B-1BBE-44CA-8295-22DA13AE914A}</Project> - <Name>ObjectTK</Name> - </ProjectReference> - </ItemGroup> - <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> - <!-- To modify your build process, add your task inside one of the targets below and uncomment it. - Other similar extension points exist, see Microsoft.Common.targets. - <Target Name="BeforeBuild"> - </Target> - <Target Name="AfterBuild"> - </Target> - --> -</Project> \ No newline at end of file diff --git a/ObjectTK.Compiler/Properties/AssemblyInfo.cs b/ObjectTK.Compiler/Properties/AssemblyInfo.cs deleted file mode 100644 index 96df226..0000000 --- a/ObjectTK.Compiler/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region License -// ObjectTK License -// Copyright (C) 2013-2015 J.C.Bernack -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see <http://www.gnu.org/licenses/>. -#endregion -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ObjectTK ShaderCompiler")] -[assembly: AssemblyDescription("Shader compiler for integrated GLSL shader validation in MSBuild and Visual Studio")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("JcBernack")] -[assembly: AssemblyProduct("ObjectTK.Compiler")] -[assembly: AssemblyCopyright("Copyright © 2014-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("8bac61da-d508-4a19-a865-8df2c3bbda59")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.*")] diff --git a/ObjectTK.Compiler/ShaderCompiler.cs b/ObjectTK.Compiler/ShaderCompiler.cs deleted file mode 100644 index 1e4f7ac..0000000 --- a/ObjectTK.Compiler/ShaderCompiler.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -// ShaderCompiler.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; -using ObjectTK.Exceptions; -using ObjectTK.Shaders; -using ObjectTK.Shaders.Sources; -using OpenTK; - -namespace ObjectTK.Compiler -{ - /// <summary> - /// Compiles all shader programs contained in assemblies given per command line arguments and outputs errors in a MSBuild and Visual Studio friendly way.<br/> - /// </summary> - /// <remarks> - /// The easiest way to use this feature is to add a reference to ObjectTKC so that the executable gets copied to the output folder and add the following Post-build event:<br/> - /// "$(TargetDir)ObjectTKC.exe" "$(TargetPath)" - /// </remarks> - public class ShaderCompiler - { - // GLSL example error messages: - // ERROR: Data/Shaders/ExampleShader.glsl:21: error(#132) Syntax error: "d" parse error - // ERROR: error(#273) 1 compilation errors. No code generated - - /// <summary> - /// Matches essential parts of GLSL error messages. - /// </summary> - private static readonly Regex ErrorRegex = new Regex(@"^ERROR: (.+):(\d+): error\(#(\d+)\) (.*)$", RegexOptions.Multiline); - - /// <summary> - /// Matches essential parts of GLSL warning messages.<br/> - /// TODO: currently untested - /// </summary> - private static readonly Regex WarningRegex = new Regex(@"^WARNING: (.+):(\d+): (.*)$", RegexOptions.Multiline); - - /// <summary> - /// Reformats OpenGL information log to a MSBuild and Visual Studio friendly format. Makes errors and warnings apprear correctly in the "Error List" of Visual Studio. - /// </summary> - /// <param name="infoLog">OpenGL information log.</param> - private static string FormatInfoLog(string infoLog) - { - var log = ErrorRegex.Replace(infoLog, "$1($2): error $3: $4"); - return WarningRegex.Replace(log, "$1($2): warning 0: $3"); - } - - public static void Main(string[] args) - { - // create a hidden GameWindow to initialize an OpenGL context - using (new GameWindow()) - { - // iterate over given arguments - foreach (var path in args) - { - // check if file exists - if (!File.Exists(path)) - { - Console.Out.WriteLine("{0}: error 0: ShaderCompiler: file not found", path); - continue; - } - Console.Out.WriteLine("Compiling shaders of: {0}", path); - // load assembly - var assembly = Assembly.LoadFrom(path); - // set working directory - Directory.SetCurrentDirectory(Path.GetDirectoryName(assembly.Location)); - // iterate over all non-abstract shader programs - foreach (var type in assembly.GetTypes().Where(_ => !_.IsAbstract && typeof(Program).IsAssignableFrom(_))) - { - // check if the program has any shader sources tagged to it - if (ShaderSourceAttribute.GetShaderSources(type).Count == 0) continue; - Console.Out.WriteLine("Compiling: {0}", type.FullName); - // get generic program factory method - var method = typeof(ProgramFactory).GetMethod("Create"); - var generic = method.MakeGenericMethod(type); - try - { - // invoke program factory - var program = (Program)generic.Invoke(null, null); - program.Dispose(); - } - catch (TargetInvocationException ex) - { - Console.Out.WriteLine(ex.InnerException.Message); - // reformat OpenGL information log if existing - var exception = ex.InnerException as ProgramException; - if (exception != null) Console.Out.WriteLine(FormatInfoLog(exception.InfoLog)); - } - } - } - } - } - } -} diff --git a/ObjectTK.Compiler/app.config b/ObjectTK.Compiler/app.config deleted file mode 100644 index b04d010..0000000 --- a/ObjectTK.Compiler/app.config +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<configuration> - <startup> - <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> - </startup> -</configuration> diff --git a/ObjectTK.Compiler/packages.config b/ObjectTK.Compiler/packages.config deleted file mode 100644 index 725fa42..0000000 --- a/ObjectTK.Compiler/packages.config +++ /dev/null @@ -1,4 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<packages> - <package id="OpenTK" version="1.1.1589.5942" targetFramework="net40" /> -</packages> \ No newline at end of file diff --git a/ObjectTK.Tools/Cameras/Camera.cs b/ObjectTK.Tools/Cameras/Camera.cs deleted file mode 100644 index 6784c1d..0000000 --- a/ObjectTK.Tools/Cameras/Camera.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -// Camera.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using OpenTK; -using OpenTK.Input; - -namespace ObjectTK.Tools.Cameras -{ - public class Camera - { - public CameraState State; - public CameraState DefaultState; - protected CameraBehavior Behavior; - - public float MouseMoveSpeed = 0.005f; - public float MouseWheelSpeed = 0.1f; - public float MoveSpeed = 60; - - public Camera() - { - State = new CameraState(); - DefaultState = new CameraState(); - } - - public void ResetToDefault() - { - State.Position = DefaultState.Position; - State.LookAt = DefaultState.LookAt; - State.Up = DefaultState.Up; - Update(); - } - - public void SetBehavior(CameraBehavior behavior) - { - Behavior = behavior; - Update(); - } - - public void Enable(GameWindow window) - { - if (Behavior == null) throw new InvalidOperationException("Can not enable Camera while the Behavior is not set."); - window.UpdateFrame += UpdateFrame; - window.Mouse.Move += MouseMove; - window.Mouse.WheelChanged += MouseWheelChanged; - } - - public void Disable(GameWindow window) - { - window.UpdateFrame -= UpdateFrame; - window.Mouse.Move -= MouseMove; - window.Mouse.WheelChanged -= MouseWheelChanged; - } - - public void Update() - { - if (Behavior != null) Behavior.Initialize(State); - } - - private void UpdateFrame(object sender, FrameEventArgs e) - { - Behavior.UpdateFrame(State, (float) e.Time * MoveSpeed); - } - - private void MouseMove(object sender, MouseMoveEventArgs e) - { - Behavior.MouseMove(State, MouseMoveSpeed * new Vector2(e.XDelta, e.YDelta)); - } - - private void MouseWheelChanged(object sender, MouseWheelEventArgs e) - { - Behavior.MouseWheelChanged(State, MouseWheelSpeed * e.DeltaPrecise); - } - - /// <summary> - /// TODO: add smooth transitions for the CameraState variables - /// </summary> - public Matrix4 GetCameraTransform() - { - // kind of hack: prevent look-at and up directions to be parallel - if (Math.Abs(Vector3.Dot(State.Up, State.LookAt)) > 0.99999999999) State.LookAt += 0.001f * new Vector3(3,5,4); - return Matrix4.LookAt(State.Position, State.Position + State.LookAt, State.Up); - } - - public override string ToString() - { - return string.Format("({0},{1})", State, Behavior); - } - } -} - -// for later use.. -//public Vector3 GetPickingRay(int mouseX, int mouseY) -//{ -// const float fieldOfView = MathHelper.PiOver4; -// const float nearClippingPaneDistance = 1; -// var view = -Position; -// view.Normalize(); -// var cameraUp = Vector3.UnitY; -// var h = Vector3.Cross(view, cameraUp); -// h.Normalize(); -// var v = Vector3.Cross(h, view); -// v.Normalize(); -// var vLength = (float)Math.Tan(fieldOfView / 2) * nearClippingPaneDistance; -// var hLength = vLength * ((float)_window.Width / _window.Height); -// v = v * vLength; -// h = h * hLength; -// //Vector3.Multiply(ref v, vLength, out v); -// //Vector3.Multiply(ref h, hLength, out h); -// // scale mouse position to [-1,1] -// var x = 2f * mouseX / _window.Width - 1; -// var y = 1 - 2f * mouseY / _window.Height; -// var pos = Position + view * nearClippingPaneDistance + h * x + v * y; -// var dir = pos - Position; -// return dir; -//} \ No newline at end of file diff --git a/ObjectTK.Tools/Cameras/CameraBehavior.cs b/ObjectTK.Tools/Cameras/CameraBehavior.cs deleted file mode 100644 index ebd968b..0000000 --- a/ObjectTK.Tools/Cameras/CameraBehavior.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// CameraBehavior.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; - -namespace ObjectTK.Tools.Cameras -{ - public abstract class CameraBehavior - { - public virtual void Initialize(CameraState state) { } - public virtual void UpdateFrame(CameraState state, float step) { } - public virtual void MouseMove(CameraState state, Vector2 delta) { } - public virtual void MouseWheelChanged(CameraState state, float delta) { } - - /// <summary> - /// TODO: add possibility to limit the pitch and prevent "flipping over" - /// </summary> - protected void HandleFreeLook(CameraState state, Vector2 delta) - { - var leftRight = Vector3.Cross(state.Up, state.LookAt); - var forward = Vector3.Cross(leftRight, state.Up); - // rotate look at direction - var rot = Matrix4.CreateFromAxisAngle(state.Up, -delta.X) * Matrix4.CreateFromAxisAngle(leftRight, delta.Y); - Vector3.Transform(ref state.LookAt, ref rot, out state.LookAt); - // renormalize to prevent summing up of floating point errors - state.LookAt.Normalize(); - // flip up vector when pitched more than +/-90� from the forward direction - if (Vector3.Dot(state.LookAt, forward) < 0) state.Up *= -1; - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Cameras/CameraState.cs b/ObjectTK.Tools/Cameras/CameraState.cs deleted file mode 100644 index 971e9c6..0000000 --- a/ObjectTK.Tools/Cameras/CameraState.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// CameraState.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; - -namespace ObjectTK.Tools.Cameras -{ - /// <summary> - /// Represents the state of a camera.<br/> - /// TODO: Maybe also add field-of-view and z-near/far plane parameter - /// </summary> - public class CameraState - { - public Vector3 Position; - public Vector3 LookAt; - public Vector3 Up; - - public CameraState() - { - LookAt.Z = -1; - Up.Y = 1; - } - - public override string ToString() - { - return string.Format((string) "({0},{1},{2})", (object) Position, (object) LookAt, (object) Up); - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Cameras/FreeLookAlignedBehavior.cs b/ObjectTK.Tools/Cameras/FreeLookAlignedBehavior.cs deleted file mode 100644 index ecb95c9..0000000 --- a/ObjectTK.Tools/Cameras/FreeLookAlignedBehavior.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// FreeLookAlignedBehavior.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; - -namespace ObjectTK.Tools.Cameras -{ - public class FreeLookAlignedBehavior - : FreeLookBehavior - { - public Vector3 AlignmentPoint; - - public override void UpdateFrame(CameraState state, float step) - { - base.UpdateFrame(state, step); - // update the up direction to always point away from the alignment point - var up = state.Position - AlignmentPoint; - up.Normalize(); - // if the angle between the old and new up directions is larger than 90� - // we assume that the camera is upside down and keep it that way - state.Up = Vector3.Dot(state.Up, up) < 0 ? -up : up; - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Cameras/FreeLookBehavior.cs b/ObjectTK.Tools/Cameras/FreeLookBehavior.cs deleted file mode 100644 index e2c4e90..0000000 --- a/ObjectTK.Tools/Cameras/FreeLookBehavior.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// FreeLookBehavior.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Input; - -namespace ObjectTK.Tools.Cameras -{ - public class FreeLookBehavior - : CameraBehavior - { - public override void UpdateFrame(CameraState state, float step) - { - var keyboard = Keyboard.GetState(); - var dir = Vector3.Zero; - var leftRight = Vector3.Cross(state.Up, state.LookAt).Normalized(); - if (keyboard.IsKeyDown(Key.W)) dir += state.LookAt; - if (keyboard.IsKeyDown(Key.S)) dir -= state.LookAt; - if (keyboard.IsKeyDown(Key.A)) dir += leftRight; - if (keyboard.IsKeyDown(Key.D)) dir -= leftRight; - if (keyboard.IsKeyDown(Key.Space)) dir += state.Up; - if (keyboard.IsKeyDown(Key.LControl)) dir -= state.Up; - // normalize dir to enforce consistent movement speed, independent of the number of keys pressed - if (dir.LengthSquared > 0) state.Position += dir.Normalized() * step; - } - - public override void MouseMove(CameraState state, Vector2 delta) - { - var mouse = Mouse.GetState(); - if (mouse.IsButtonDown(MouseButton.Left)) - { - HandleFreeLook(state, delta); - } - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Cameras/GimbalBehavior.cs b/ObjectTK.Tools/Cameras/GimbalBehavior.cs deleted file mode 100644 index 65077ae..0000000 --- a/ObjectTK.Tools/Cameras/GimbalBehavior.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -// GimbalBehavior.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Input; - -namespace ObjectTK.Tools.Cameras -{ - /// <summary> - /// TODO: Does not yet work like it should. - /// </summary> - public class GimbalBehavior - : ThirdPersonBehavior - { - public override void MouseMove(CameraState state, Vector2 delta) - { - var mouse = Mouse.GetState(); - if (mouse.IsButtonDown(MouseButton.Left)) - { - base.MouseMove(state, delta); - var leftRight = Vector3.Cross(state.Up, state.LookAt); - Vector3.Cross(ref state.LookAt, ref leftRight, out state.Up); - state.Up.Normalize(); - } - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Cameras/ThirdPersonBehavior.cs b/ObjectTK.Tools/Cameras/ThirdPersonBehavior.cs deleted file mode 100644 index dc3a7fd..0000000 --- a/ObjectTK.Tools/Cameras/ThirdPersonBehavior.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -// ThirdPersonBehavior.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Input; - -namespace ObjectTK.Tools.Cameras -{ - public class ThirdPersonBehavior - : CameraBehavior - { - public Vector3 Origin; - - protected void UpdateDistance(CameraState state, float scale) - { - state.Position = Origin - (state.Position - Origin).Length * (1 + scale) * state.LookAt; - } - - public override void Initialize(CameraState state) - { - // recalculate look at direction - state.LookAt = Origin - state.Position; - state.LookAt.Normalize(); - } - - public override void MouseMove(CameraState state, Vector2 delta) - { - var mouse = Mouse.GetState(); - if (mouse.IsButtonDown(MouseButton.Left)) - { - // rotate look direction with mouse - HandleFreeLook(state, delta); - // recalculate the position - UpdateDistance(state, 0); - } - if (mouse.IsButtonDown(MouseButton.Right)) - { - UpdateDistance(state, delta.Y); - } - } - - public override void MouseWheelChanged(CameraState state, float delta) - { - if (delta > 100) delta = 100; - UpdateDistance(state, -delta); - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/DerpWindow.cs b/ObjectTK.Tools/DerpWindow.cs deleted file mode 100644 index 9f82625..0000000 --- a/ObjectTK.Tools/DerpWindow.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// DerpWindow.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools -{ - /// <summary> - /// Provides basic functionality to an OpenTK GameWindow such as camera controls, - /// ModelView and Projection matrices and improved timing. - /// </summary> - public abstract class DerpWindow - : GameWindow - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(DerpWindow)); - - protected readonly FrameTimer FrameTimer; - - /// <summary> - /// Initializes a new instance of the DerpWindow class. - /// </summary> - protected DerpWindow(int width, int height, GraphicsMode mode, string title) - : base(width, height, mode, title) - { - // log some OpenGL information - Logger?.Info("OpenGL context information:"); - Logger?.InfoFormat("{0}: {1}", StringName.Vendor, GL.GetString(StringName.Vendor)); - Logger?.InfoFormat("{0}: {1}", StringName.Renderer, GL.GetString(StringName.Renderer)); - Logger?.InfoFormat("{0}: {1}", StringName.Version, GL.GetString(StringName.Version)); - Logger?.InfoFormat("{0}: {1}", StringName.ShadingLanguageVersion, GL.GetString(StringName.ShadingLanguageVersion)); - int numExtensions; - GL.GetInteger(GetPName.NumExtensions, out numExtensions); - Logger?.DebugFormat("Number available extensions: {0}", numExtensions); - for (var i = 0; i < numExtensions; i++) Logger?.DebugFormat("{0}: {1}", i, GL.GetString(StringNameIndexed.Extensions, i)); - Logger?.InfoFormat("Initializing game window: {0}", title); - // set up GameWindow events - Resize += OnResize; - UpdateFrame += OnUpdateFrame; - // set up frame timer - FrameTimer = new FrameTimer(); - } - - private void OnResize(object sender, EventArgs eventArgs) - { - Logger?.InfoFormat("Window resized to: {0}x{1}", Width, Height); - } - - private void OnUpdateFrame(object sender, FrameEventArgs e) - { - FrameTimer.Time(); - } - } -} diff --git a/ObjectTK.Tools/ObjectTK.Tools.csproj b/ObjectTK.Tools/ObjectTK.Tools.csproj deleted file mode 100644 index 6b8226a..0000000 --- a/ObjectTK.Tools/ObjectTK.Tools.csproj +++ /dev/null @@ -1,90 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> - <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> - <PropertyGroup> - <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> - <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProjectGuid>{E38997F8-7ECE-4B35-BB94-7E609F68D217}</ProjectGuid> - <OutputType>Library</OutputType> - <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>ObjectTK.Tools</RootNamespace> - <AssemblyName>ObjectTK.Tools</AssemblyName> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <FileAlignment>512</FileAlignment> - <TargetFrameworkProfile> - </TargetFrameworkProfile> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <PlatformTarget>AnyCPU</PlatformTarget> - <DebugSymbols>true</DebugSymbols> - <DebugType>full</DebugType> - <Optimize>false</Optimize> - <OutputPath>bin\Debug\</OutputPath> - <DefineConstants>DEBUG;TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <Prefer32Bit>false</Prefer32Bit> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <PlatformTarget>AnyCPU</PlatformTarget> - <DebugType>pdbonly</DebugType> - <Optimize>true</Optimize> - <OutputPath>bin\Release\</OutputPath> - <DefineConstants>TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <Prefer32Bit>false</Prefer32Bit> - </PropertyGroup> - <PropertyGroup> - <StartupObject /> - </PropertyGroup> - <ItemGroup> - <None Include="packages.config" /> - </ItemGroup> - <ItemGroup> - <Compile Include="Cameras\Camera.cs" /> - <Compile Include="Cameras\CameraBehavior.cs" /> - <Compile Include="Cameras\CameraState.cs" /> - <Compile Include="Cameras\FreeLookAlignedBehavior.cs" /> - <Compile Include="Cameras\FreeLookBehavior.cs" /> - <Compile Include="Cameras\GimbalBehavior.cs" /> - <Compile Include="Cameras\ThirdPersonBehavior.cs" /> - <Compile Include="DerpWindow.cs" /> - <Compile Include="FrameTimer.cs" /> - <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Shapes\Circle.cs" /> - <Compile Include="Shapes\ColorCube.cs" /> - <Compile Include="Shapes\ColoredShape.cs" /> - <Compile Include="Shapes\Cube.cs" /> - <Compile Include="Shapes\IndexedShape.cs" /> - <Compile Include="Shapes\LayeredQuads.cs" /> - <Compile Include="Shapes\Quad.cs" /> - <Compile Include="Shapes\Rect.cs" /> - <Compile Include="Shapes\Shape.cs" /> - <Compile Include="Shapes\TexturedCube.cs" /> - <Compile Include="Shapes\TexturedQuad.cs" /> - <Compile Include="Shapes\TexturedShape.cs" /> - </ItemGroup> - <ItemGroup> - <Reference Include="OpenTK, Version=1.1.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\OpenTK.1.1.1589.5942\lib\NET40\OpenTK.dll</HintPath> - </Reference> - <Reference Include="System" /> - <Reference Include="System.Drawing" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\ObjectTK\ObjectTK.csproj"> - <Project>{0EE3347B-1BBE-44CA-8295-22DA13AE914A}</Project> - <Name>ObjectTK</Name> - </ProjectReference> - </ItemGroup> - <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> - <!-- To modify your build process, add your task inside one of the targets below and uncomment it. - Other similar extension points exist, see Microsoft.Common.targets. - <Target Name="BeforeBuild"> - </Target> - <Target Name="AfterBuild"> - </Target> - --> -</Project> \ No newline at end of file diff --git a/ObjectTK.Tools/Properties/AssemblyInfo.cs b/ObjectTK.Tools/Properties/AssemblyInfo.cs deleted file mode 100644 index 082e496..0000000 --- a/ObjectTK.Tools/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region License -// ObjectTK License -// Copyright (C) 2013-2015 J.C.Bernack -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see <http://www.gnu.org/licenses/>. -#endregion -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ObjectTK Tools")] -[assembly: AssemblyDescription("Additional features to complement ObjectTK")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("JcBernack")] -[assembly: AssemblyProduct("ObjectTK.Tools")] -[assembly: AssemblyCopyright("Copyright © 2013-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("8133d931-0992-47fd-b4a0-f7ee832615cd")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.*")] \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/Circle.cs b/ObjectTK.Tools/Shapes/Circle.cs deleted file mode 100644 index 3c4cabc..0000000 --- a/ObjectTK.Tools/Shapes/Circle.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// Circle.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public class Circle - : Shape - { - public Circle(float radius) - { - DefaultMode = PrimitiveType.TriangleFan; - const int z = 0; - const int slices = 64; - const float dtheta = MathHelper.TwoPi / (slices - 1); - var theta = 0f; - Vertices = new Vector3[slices+1]; - Vertices[0] = new Vector3(0, 0, z); - for (var i = 0; i < slices; i++) - { - Vertices[i+1] = new Vector3((float)Math.Cos(theta) * radius, (float)Math.Sin(theta) * radius, z); - theta += dtheta; - } - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/ColorCube.cs b/ObjectTK.Tools/Shapes/ColorCube.cs deleted file mode 100644 index 0446e94..0000000 --- a/ObjectTK.Tools/Shapes/ColorCube.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// ColorCube.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public class ColorCube - : ColoredShape - { - public ColorCube() - { - DefaultMode = PrimitiveType.Triangles; - - // use default cube - using (var cube = new Cube()) - { - Vertices = cube.Vertices; - Indices = cube.Indices; - } - - // add color to the vertices - Colors = new List<Color> - { - Color.DarkRed, - Color.DarkRed, - Color.Gold, - Color.Gold, - Color.DarkRed, - Color.DarkRed, - Color.Gold, - Color.Gold - }.Select(_ => _.ToRgba32()).ToArray(); - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/ColoredShape.cs b/ObjectTK.Tools/Shapes/ColoredShape.cs deleted file mode 100644 index c9731d7..0000000 --- a/ObjectTK.Tools/Shapes/ColoredShape.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// ColoredShape.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using ObjectTK.Buffers; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public abstract class ColoredShape - : IndexedShape - { - public uint[] Colors { get; protected set; } - public Buffer<uint> ColorBuffer { get; protected set; } - - public override void UpdateBuffers() - { - base.UpdateBuffers(); - ColorBuffer = new Buffer<uint>(); - ColorBuffer.Init(BufferTarget.ArrayBuffer, Colors); - } - - protected override void Dispose(bool manual) - { - base.Dispose(manual); - if (!manual) return; - if (ColorBuffer != null) ColorBuffer.Dispose(); - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/Cube.cs b/ObjectTK.Tools/Shapes/Cube.cs deleted file mode 100644 index e16c92c..0000000 --- a/ObjectTK.Tools/Shapes/Cube.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// Cube.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public class Cube - : IndexedShape - { - public Cube() - { - DefaultMode = PrimitiveType.Triangles; - - Vertices = new[] - { - new Vector3(-1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, 1.0f, -1.0f), - new Vector3(-1.0f, 1.0f, -1.0f) - }; - - Indices = new uint[] - { - // front face - 0, 1, 2, 2, 3, 0, - // top face - 3, 2, 6, 6, 7, 3, - // back face - 7, 6, 5, 5, 4, 7, - // left face - 4, 0, 3, 3, 7, 4, - // bottom face - 5, 1, 0, 0, 4, 5, - // right face - 1, 5, 6, 6, 2, 1 - }; - } - } -} diff --git a/ObjectTK.Tools/Shapes/IndexedShape.cs b/ObjectTK.Tools/Shapes/IndexedShape.cs deleted file mode 100644 index 388a875..0000000 --- a/ObjectTK.Tools/Shapes/IndexedShape.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// IndexedShape.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using ObjectTK.Buffers; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public abstract class IndexedShape - : Shape - { - public uint[] Indices { get; protected set; } - public Buffer<uint> IndexBuffer { get; protected set; } - - public override void UpdateBuffers() - { - base.UpdateBuffers(); - IndexBuffer = new Buffer<uint>(); - IndexBuffer.Init(BufferTarget.ElementArrayBuffer, Indices); - } - - protected override void Dispose(bool manual) - { - base.Dispose(manual); - if (!manual) return; - if (IndexBuffer != null) IndexBuffer.Dispose(); - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/LayeredQuads.cs b/ObjectTK.Tools/Shapes/LayeredQuads.cs deleted file mode 100644 index 0cfafec..0000000 --- a/ObjectTK.Tools/Shapes/LayeredQuads.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// LayeredQuads.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public class LayeredQuads - : IndexedShape - { - public LayeredQuads(int layers) - { - DefaultMode = PrimitiveType.Triangles; - const float size = 1; - var z = -size / 2f; - var step = size / (layers-1); - Vertices = new Vector3[4*layers]; - Indices = new uint[6*layers]; - var order = new uint[]{ 0, 1, 2, 2, 3, 0 }; - for (uint i = 0; i < layers; ++i) - { - Vertices[i * 4 + 0] = new Vector3(-size / 2, -size / 2, z); - Vertices[i * 4 + 1] = new Vector3(+size / 2, -size / 2, z); - Vertices[i * 4 + 2] = new Vector3(+size / 2, +size / 2, z); - Vertices[i * 4 + 3] = new Vector3(-size / 2, +size / 2, z); - for (uint j = 0; j < 6; j++) Indices[i * 6 + j] = i*4 + order[j]; - z += step; - } - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/Quad.cs b/ObjectTK.Tools/Shapes/Quad.cs deleted file mode 100644 index df6f760..0000000 --- a/ObjectTK.Tools/Shapes/Quad.cs +++ /dev/null @@ -1,34 +0,0 @@ -// -// Quad.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public class Quad - : Shape - { - public Quad() - { - DefaultMode = PrimitiveType.TriangleStrip; - - // Source: http://www.opengl.org/archives/resources/faq/technical/transformations.htm (9.090 How do I draw a full-screen quad?) - // Your rectangle or quad's Z value should be in the range of –1.0 to 1.0, with –1.0 mapping to the zNear clipping plane, and 1.0 to the zFar clipping plane. - const int z = 0; - Vertices = new[] - { - new Vector3(-1, -1, z), - new Vector3( 1, -1, z), - new Vector3(-1, 1, z), - new Vector3( 1, 1, z) - }; - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/Rect.cs b/ObjectTK.Tools/Shapes/Rect.cs deleted file mode 100644 index 2aff09d..0000000 --- a/ObjectTK.Tools/Shapes/Rect.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// Rect.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public class Rect - : Shape - { - public Rect(float right, float top) - : this(-1, -1, right, top) - { - } - - public Rect(float left, float bottom, float right, float top) - { - DefaultMode = PrimitiveType.LineLoop; - const int z = 0; - Vertices = new[] - { - new Vector3(left, bottom, z), - new Vector3(right, bottom, z), - new Vector3(right, top, z), - new Vector3(left, top, z) - }; - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/Shape.cs b/ObjectTK.Tools/Shapes/Shape.cs deleted file mode 100644 index e26bf8c..0000000 --- a/ObjectTK.Tools/Shapes/Shape.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -// Shape.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using ObjectTK.Buffers; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - /// <summary> - /// TODO: needs a total refactoring - /// does not prevent multiple calls to UpdateBuffers() and causes resource leaks - /// does not fit well to an inheritance chain - /// there may be a shape just with vertices - /// there may be an indexed shape with vertices and indices - /// there may be a colored, indexed shape with vertices, indices and colors - /// there may be a colored shape with vertices and colors but no indices... - /// </summary> - public abstract class Shape - : GLResource - { - public PrimitiveType DefaultMode { get; set; } - public Vector3[] Vertices { get; protected set; } - public Buffer<Vector3> VertexBuffer { get; protected set; } - - public virtual void UpdateBuffers() - { - VertexBuffer = new Buffer<Vector3>(); - VertexBuffer.Init(BufferTarget.ArrayBuffer, Vertices); - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - if (VertexBuffer != null) VertexBuffer.Dispose(); - } - } -} diff --git a/ObjectTK.Tools/Shapes/TexturedCube.cs b/ObjectTK.Tools/Shapes/TexturedCube.cs deleted file mode 100644 index cec25d5..0000000 --- a/ObjectTK.Tools/Shapes/TexturedCube.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// TexturedCube.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Graphics.OpenGL; -using System.Linq; - -namespace ObjectTK.Tools.Shapes -{ - public class TexturedCube - : TexturedShape - { - public TexturedCube() - { - DefaultMode = PrimitiveType.Triangles; - - var quad_uv_map = new[] - { - new Vector2(0, 0), - new Vector2(0, 1), - new Vector2(1, 1), - new Vector2(1, 1), - new Vector2(1, 0), - new Vector2(0, 0), - }; - - // use default cube - using (var cube = new Cube()) - { - // Cube uses indexed vertices, TexturedShape assumes a flat vertices array - // So we need to assemble the missing vertices ourself - Vertices = cube.Indices.Select(idx => cube.Vertices[idx]).ToArray(); - - // Use predefined uv texture mapping for vertices - TexCoords = Enumerable.Range(0, Vertices.Length).Select(i => quad_uv_map[i % quad_uv_map.Length]).ToArray(); - } - } - } -} diff --git a/ObjectTK.Tools/Shapes/TexturedQuad.cs b/ObjectTK.Tools/Shapes/TexturedQuad.cs deleted file mode 100644 index ebb78da..0000000 --- a/ObjectTK.Tools/Shapes/TexturedQuad.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// TexturedQuad.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public class TexturedQuad - : TexturedShape - { - public TexturedQuad() - { - DefaultMode = PrimitiveType.TriangleStrip; - - // Source: http://www.opengl.org/archives/resources/faq/technical/transformations.htm (9.090 How do I draw a full-screen quad?) - // Your rectangle or quad's Z value should be in the range of –1.0 to 1.0, with –1.0 mapping to the zNear clipping plane, and 1.0 to the zFar clipping plane. - const int z = 0; - Vertices = new[] - { - new Vector3(-1, -1, z), - new Vector3( 1, -1, z), - new Vector3(-1, 1, z), - new Vector3( 1, 1, z) - }; - - TexCoords = new[] - { - new Vector2(0,0), - new Vector2(1,0), - new Vector2(0,1), - new Vector2(1,1) - }; - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/Shapes/TexturedShape.cs b/ObjectTK.Tools/Shapes/TexturedShape.cs deleted file mode 100644 index ad122fc..0000000 --- a/ObjectTK.Tools/Shapes/TexturedShape.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// TexturedShape.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using ObjectTK.Buffers; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Tools.Shapes -{ - public abstract class TexturedShape - : Shape - { - public Vector2[] TexCoords { get; protected set; } - public Buffer<Vector2> TexCoordBuffer { get; protected set; } - - public override void UpdateBuffers() - { - base.UpdateBuffers(); - TexCoordBuffer = new Buffer<Vector2>(); - TexCoordBuffer.Init(BufferTarget.ArrayBuffer, TexCoords); - } - - protected override void Dispose(bool manual) - { - base.Dispose(manual); - if (TexCoordBuffer != null) TexCoordBuffer.Dispose(); - } - } -} \ No newline at end of file diff --git a/ObjectTK.Tools/packages.config b/ObjectTK.Tools/packages.config deleted file mode 100644 index 725fa42..0000000 --- a/ObjectTK.Tools/packages.config +++ /dev/null @@ -1,4 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<packages> - <package id="OpenTK" version="1.1.1589.5942" targetFramework="net40" /> -</packages> \ No newline at end of file diff --git a/ObjectTK.sln b/ObjectTK.sln index 93682a5..4d0b457 100644 --- a/ObjectTK.sln +++ b/ObjectTK.sln @@ -1,20 +1,17 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30114.105 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObjectTK", "ObjectTK\ObjectTK.csproj", "{0EE3347B-1BBE-44CA-8295-22DA13AE914A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectTK.Core", "src\ObjectTK.Core\ObjectTK.Core.csproj", "{163450BD-24E0-4C3E-A310-3AEBD709E065}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples", "Examples\Examples.csproj", "{B05720A6-8E0A-4D53-96D1-AA341AE0D0D5}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectTK.Extensions", "src\ObjectTK.Extensions\ObjectTK.Extensions.csproj", "{DE7D5895-068B-42CF-B69A-D5E3AAE7E43B}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F291BD61-42A4-4FBC-B05C-C24BC97EB2EE}" - ProjectSection(SolutionItems) = preProject - README.md = README.md - EndProjectSection +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples", "src\Examples\Examples.csproj", "{AF523BFF-E1A2-45CF-B9CE-F14F3A16536E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObjectTK.Tools", "ObjectTK.Tools\ObjectTK.Tools.csproj", "{E38997F8-7ECE-4B35-BB94-7E609F68D217}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObjectTK.Tools", "src\ObjectTK.Tools\ObjectTK.Tools.csproj", "{B5DCB84E-3E09-4F37-B06E-68565756624F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObjectTK.Compiler", "ObjectTK.Compiler\ObjectTK.Compiler.csproj", "{ABD0BE84-792D-4F52-82E2-C869585B3C29}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObjectTK.2D", "src\ObjectTK.2D\ObjectTK.2D.csproj", "{77B6C529-5DD8-4A76-8577-E50F0F06F7F2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -22,24 +19,31 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {0EE3347B-1BBE-44CA-8295-22DA13AE914A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0EE3347B-1BBE-44CA-8295-22DA13AE914A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0EE3347B-1BBE-44CA-8295-22DA13AE914A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0EE3347B-1BBE-44CA-8295-22DA13AE914A}.Release|Any CPU.Build.0 = Release|Any CPU - {B05720A6-8E0A-4D53-96D1-AA341AE0D0D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B05720A6-8E0A-4D53-96D1-AA341AE0D0D5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B05720A6-8E0A-4D53-96D1-AA341AE0D0D5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B05720A6-8E0A-4D53-96D1-AA341AE0D0D5}.Release|Any CPU.Build.0 = Release|Any CPU - {E38997F8-7ECE-4B35-BB94-7E609F68D217}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E38997F8-7ECE-4B35-BB94-7E609F68D217}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E38997F8-7ECE-4B35-BB94-7E609F68D217}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E38997F8-7ECE-4B35-BB94-7E609F68D217}.Release|Any CPU.Build.0 = Release|Any CPU - {ABD0BE84-792D-4F52-82E2-C869585B3C29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {ABD0BE84-792D-4F52-82E2-C869585B3C29}.Debug|Any CPU.Build.0 = Debug|Any CPU - {ABD0BE84-792D-4F52-82E2-C869585B3C29}.Release|Any CPU.ActiveCfg = Release|Any CPU - {ABD0BE84-792D-4F52-82E2-C869585B3C29}.Release|Any CPU.Build.0 = Release|Any CPU + {163450BD-24E0-4C3E-A310-3AEBD709E065}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {163450BD-24E0-4C3E-A310-3AEBD709E065}.Debug|Any CPU.Build.0 = Debug|Any CPU + {163450BD-24E0-4C3E-A310-3AEBD709E065}.Release|Any CPU.ActiveCfg = Release|Any CPU + {163450BD-24E0-4C3E-A310-3AEBD709E065}.Release|Any CPU.Build.0 = Release|Any CPU + {DE7D5895-068B-42CF-B69A-D5E3AAE7E43B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DE7D5895-068B-42CF-B69A-D5E3AAE7E43B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DE7D5895-068B-42CF-B69A-D5E3AAE7E43B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DE7D5895-068B-42CF-B69A-D5E3AAE7E43B}.Release|Any CPU.Build.0 = Release|Any CPU + {AF523BFF-E1A2-45CF-B9CE-F14F3A16536E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AF523BFF-E1A2-45CF-B9CE-F14F3A16536E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AF523BFF-E1A2-45CF-B9CE-F14F3A16536E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AF523BFF-E1A2-45CF-B9CE-F14F3A16536E}.Release|Any CPU.Build.0 = Release|Any CPU + {B5DCB84E-3E09-4F37-B06E-68565756624F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B5DCB84E-3E09-4F37-B06E-68565756624F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B5DCB84E-3E09-4F37-B06E-68565756624F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B5DCB84E-3E09-4F37-B06E-68565756624F}.Release|Any CPU.Build.0 = Release|Any CPU + {77B6C529-5DD8-4A76-8577-E50F0F06F7F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {77B6C529-5DD8-4A76-8577-E50F0F06F7F2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {77B6C529-5DD8-4A76-8577-E50F0F06F7F2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {77B6C529-5DD8-4A76-8577-E50F0F06F7F2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {ED1B1358-95C3-48DA-BF83-8A320A20B918} + EndGlobalSection EndGlobal diff --git a/ObjectTK.sln.DotSettings b/ObjectTK.sln.DotSettings deleted file mode 100644 index 38f2b95..0000000 --- a/ObjectTK.sln.DotSettings +++ /dev/null @@ -1,19 +0,0 @@ -<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> - <s:String x:Key="/Default/CodeStyle/CodeCleanup/Profiles/=Insert_0020Header/@EntryIndexedValue"><?xml version="1.0" encoding="utf-16"?><Profile name="Insert Header"><CSUpdateFileHeader>True</CSUpdateFileHeader><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags></Profile></s:String> - <s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderRegionName/@EntryValue">License</s:String> - <s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">$SOLUTION$ License
 -Copyright (C) 2013-2015 J.C.Bernack
 -
 -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version.
 -
 -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details.
 -
 -You should have received a copy of the GNU General Public License -along with this program. If not, see <http://www.gnu.org/licenses/>.</s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TK/@EntryIndexedValue">TK</s:String></wpf:ResourceDictionary> \ No newline at end of file diff --git a/ObjectTK/Buffers/Buffer.cs b/ObjectTK/Buffers/Buffer.cs deleted file mode 100644 index bd165cd..0000000 --- a/ObjectTK/Buffers/Buffer.cs +++ /dev/null @@ -1,259 +0,0 @@ -// -// Buffer.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Runtime.InteropServices; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Buffers -{ - /// <summary> - /// Represents a buffer object. - /// </summary> - /// <typeparam name="T">The type of elements in the buffer object.</typeparam> - public class Buffer<T> - : GLObject - where T : struct - { - /// <summary> - /// A value indicating whether the buffer has been initialized and thus has access to allocated memory. - /// </summary> - public bool Initialized { get; private set; } - - /// <summary> - /// The size in bytes of one element within the buffer. - /// </summary> - public int ElementSize { get; protected set; } - - /// <summary> - /// The number of elements for which buffer memory was allocated. - /// </summary> - public int ElementCount { get; private set; } - - /// <summary> - /// The index to the element which will be written to on the next usage of SubData(). - /// </summary> - public int CurrentElementIndex { get; set; } - - /// <summary> - /// The number of elements with data explicitly written. - /// </summary> - public int ActiveElementCount { get; set; } - - /// <summary> - /// Retrieves data back from vram. - /// Mainly for debugging purposes. - /// </summary> - public T[] Content - { - get - { - var items = new T[ElementCount]; - GL.BindBuffer(BufferTarget.ArrayBuffer, Handle); - GL.GetBufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, (IntPtr)(ElementSize * ElementCount), items); - return items; - } - } - - /// <summary> - /// Creates a new, uninitialized buffer object using an explicitly given element size in bytes. - /// </summary> - public Buffer(int elementSize) - : base(GL.GenBuffer()) - { - Initialized = false; - ElementSize = elementSize; - } - - /// <summary> - /// Creates a new, uninitialized buffer object using the element size determined by Marshal.SizeOf(). - /// </summary> - public Buffer() - : this(Marshal.SizeOf(typeof(T))) - { - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteBuffer(Handle); - } - - /// <summary> - /// Allocates buffer memory and uploads given data to it. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - /// <param name="data">The data to be transfered into the buffer.</param> - /// <param name="usageHint">The usage hint of the buffer object.</param> - public void Init(BufferTarget bufferTarget, T[] data, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) - { - Init(bufferTarget, data.Length, data, usageHint); - ActiveElementCount = data.Length; - CurrentElementIndex = 0; - } - - /// <summary> - /// Allocates buffer memory without initializing it. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - /// <param name="elementCount">The number of elements to allocate memory for.</param> - /// <param name="usageHint">The usage hint of the buffer object.</param> - public void Init(BufferTarget bufferTarget, int elementCount, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) - { - Init(bufferTarget, elementCount, null, usageHint); - ActiveElementCount = 0; - CurrentElementIndex = 0; - } - - /// <summary> - /// Allocates buffer memory and initializes it to the given data. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - /// <param name="elementCount">The number of elements to allocate memory for.</param> - /// <param name="data">The data to upload into the buffer.</param> - /// <param name="usageHint">The usage hint of the buffer object.</param> - protected void Init(BufferTarget bufferTarget, int elementCount, T[] data, BufferUsageHint usageHint) - { - Initialized = true; - ElementCount = elementCount; - var fullSize = elementCount * ElementSize; - GL.BindBuffer(bufferTarget, Handle); - GL.BufferData(bufferTarget, (IntPtr)fullSize, data, usageHint); - CheckBufferSize(bufferTarget, fullSize); - } - - /// <summary> - /// Overwrites part of the buffer with the given data and automatically indexes forward through the available memory. - /// Skips back to the beginning automatically once the end was reached. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - /// <param name="data">The data to be transfered into the buffer.</param> - public void SubData(BufferTarget bufferTarget, T[] data) - { - if (data.Length > ElementCount) throw new ArgumentException( - string.Format("Buffer not large enough to hold data. Buffer size: {0}. Elements to write: {1}.", ElementCount, data.Length)); - // check if data does not fit at the end of the buffer - var rest = ElementCount - CurrentElementIndex; - if (rest >= data.Length) - { - // add the elements of data to the buffer at the current index - SubData(bufferTarget, data, CurrentElementIndex); - // skip forward through the buffer - CurrentElementIndex += data.Length; - // remember the total number of elements with data - if (ActiveElementCount < CurrentElementIndex) ActiveElementCount = CurrentElementIndex; - // skip back if the end was reached - // in this case it can only be reached exactly because otherwise it would be handled by the else-case - if (CurrentElementIndex >= ElementCount) CurrentElementIndex = 0; - } - else - { - // first fill the end of the buffer - SubData(bufferTarget, data, CurrentElementIndex, rest); - // proceed to add the remaining elements at the beginning - rest = data.Length - rest; - SubData(bufferTarget, data, 0, rest); - CurrentElementIndex = rest; - // remember that the full buffer was already written to - ActiveElementCount = ElementCount; - } - } - - /// <summary> - /// Overwrites part of the buffer with the given data at the given offset. - /// Writes all data available in data. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - /// <param name="data">The data to be transfered into the buffer.</param> - /// <param name="offset">The index to the first element of the buffer to be overwritten.</param> - public void SubData(BufferTarget bufferTarget, T[] data, int offset) - { - SubData(bufferTarget, data, offset, data.Length); - } - - /// <summary> - /// Overwrites part of the buffer with the given data at the given offset. - /// Writes <paramref name="count" /> elements of data. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - /// <param name="data">The data to be transfered into the buffer.</param> - /// <param name="offset">The index to the first element of the buffer to be overwritten.</param> - /// <param name="count">The number of elements from data to write.</param> - public void SubData(BufferTarget bufferTarget, T[] data, int offset, int count) - { - if (count > ElementCount - offset) throw new ArgumentException( - string.Format("Buffer not large enough to hold data. Buffer size: {0}. Offset: {1}. Elements to write: {2}.", ElementCount, offset, count)); - if (count > data.Length) throw new ArgumentException( - string.Format("Not enough data to write to buffer. Data length: {0}. Elements to write: {1}.", data.Length, count)); - GL.BindBuffer(bufferTarget, Handle); - GL.BufferSubData(bufferTarget, (IntPtr)(ElementSize * offset), (IntPtr)(ElementSize * count), data); - } - - /// <summary> - /// Clear the buffer to default values. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - public void Clear(BufferTarget bufferTarget) - { - SubData(bufferTarget, new T[ElementCount], 0, ElementCount); - } - - /// <summary> - /// "Orphan" the buffer by calling glBufferData() with the exact same size and usage hint, - /// but with a NULL pointer as the new data. This will let OpenGL allocate a new buffer - /// under the same handle and continue using it without synchronization, even if the old - /// buffer may still be in use by commands remaining in the queue. - /// </summary> - /// <param name="bufferTarget">The BufferTarget to use when binding the buffer.</param> - /// <param name="usageHint">The usage hint of the buffer object.</param> - public void Orphan(BufferTarget bufferTarget, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) - { - if (!Initialized) throw new InvalidOperationException("Can not orphan uninitialized buffer."); - Init(bufferTarget, ElementCount, usageHint); - // GL 4.3 - //GL.InvalidateBufferData(Handle); - } - - /// <summary> - /// Copies elements from the source buffer to this buffer. - /// Copied on server-side only, no synchronization or transfer of data to host required. - /// </summary> - /// <param name="source">The source buffer to copy data from.</param> - /// <param name="readOffset">Element offset into the source buffer.</param> - /// <param name="writeOffset">Element offset into this buffer</param> - /// <param name="count">The Number of elements to copy.</param> - public void CopyFrom(Buffer<T> source, int readOffset, int writeOffset, int count) - { - GL.BindBuffer(BufferTarget.CopyReadBuffer, source.Handle); - GL.BindBuffer(BufferTarget.CopyWriteBuffer, Handle); - GL.CopyBufferSubData(BufferTarget.CopyReadBuffer, BufferTarget.CopyWriteBuffer, - (IntPtr)(ElementSize * readOffset), (IntPtr)(ElementSize * writeOffset), (IntPtr)(ElementSize * count)); - } - - /// <summary> - /// Copies elements from the source buffer to this buffer until the end of either buffer is reached. - /// </summary> - /// <param name="source">The source buffer to copy elements from.</param> - public void CopyFrom(Buffer<T> source) - { - CopyFrom(source, 0, 0, Math.Min(ElementCount, source.ElementCount)); - } - - /// <summary> - /// Checks if uploaded size matches the expected size. - /// </summary> - protected void CheckBufferSize(BufferTarget bufferTarget, int size) - { - int uploadedSize; - GL.GetBufferParameter(bufferTarget, BufferParameterName.BufferSize, out uploadedSize); - if (uploadedSize != size) throw new ApplicationException( - string.Format("Problem uploading data to buffer object. Tried to upload {0} bytes, but uploaded {1}.", size, uploadedSize)); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Buffers/BufferPod.cs b/ObjectTK/Buffers/BufferPod.cs deleted file mode 100644 index 4272f96..0000000 --- a/ObjectTK/Buffers/BufferPod.cs +++ /dev/null @@ -1,109 +0,0 @@ -// -// BufferPod.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Buffers -{ - /// <summary> - /// Represents two buffer objects which are bundled together to simplify ping-ponging. - /// </summary> - /// <typeparam name="T">The type of elements in the buffer objects.</typeparam> - public class BufferPod<T> - : GLResource - where T : struct - { - /// <summary> - /// First or front buffer. - /// </summary> - public Buffer<T> Ping { private set; get; } - - /// <summary> - /// Second or back buffer. - /// </summary> - public Buffer<T> Pong { private set; get; } - - /// <summary> - /// Requests two new, uninitialized <see cref="Buffer{T}"/> objects. - /// </summary> - public BufferPod() - { - Ping = new Buffer<T>(); - Pong = new Buffer<T>(); - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - Ping.Dispose(); - Pong.Dispose(); - } - - /// <summary> - /// Allocates memory for both buffer objects without initializing it. - /// </summary> - /// <param name="target">The BufferTarget to use when binding the buffers.</param> - /// <param name="elementCount">The number of elements for each buffer to allocate memory for.</param> - /// <param name="usageHint">The usage hint for both buffer objects.</param> - public void Init(BufferTarget target, int elementCount, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) - { - Ping.Init(target, elementCount, usageHint); - Pong.Init(target, elementCount, usageHint); - } - - /// <summary> - /// Allocates memory for both buffer objects and initializes the first buffer with the given data. - /// The second buffer is left uninitialized. - /// </summary> - /// <param name="target">The BufferTarget to use when binding the buffers.</param> - /// <param name="data">The data to upload to the first buffer and allocate enough memory for in the second buffer.</param> - /// <param name="usageHint">The usage hint for both buffer objects.</param> - public void Init(BufferTarget target, T[] data, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) - { - Ping.Init(target, data, usageHint); - Pong.Init(target, data.Length, usageHint); - } - - /// <summary> - /// Changes the size of both buffer objects. - /// </summary> - /// <param name="target">The BufferTarget to use when binding the buffers.</param> - /// <param name="elementCount">The new number of elements for each buffer to allocate memory for.</param> - /// <param name="usageHint">The usage hint for both buffer objects.</param> - public void Resize(BufferTarget target, int elementCount, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) - { - // wrap current element index into the new buffer size if it is smaller than before - Ping.CurrentElementIndex %= elementCount; - // prevent active element count from exceeding the new buffer size - Ping.ActiveElementCount = Math.Min(Ping.ActiveElementCount, elementCount); - // copy data into resized buffer - Pong.Init(target, elementCount, usageHint); - if (Ping.Initialized) Pong.CopyFrom(Ping); - // swap buffers - Swap(); - // resize the other buffer - Pong.Init(target, elementCount, usageHint); - } - - /// <summary> - /// Swaps the two buffer objects. - /// </summary> - public void Swap() - { - // copy over current "state" - Pong.CurrentElementIndex = Ping.CurrentElementIndex; - Pong.ActiveElementCount = Ping.ActiveElementCount; - // swap buffers - var tmp = Ping; - Ping = Pong; - Pong = tmp; - } - } -} \ No newline at end of file diff --git a/ObjectTK/Buffers/Framebuffer.cs b/ObjectTK/Buffers/Framebuffer.cs deleted file mode 100644 index 2dccdf9..0000000 --- a/ObjectTK/Buffers/Framebuffer.cs +++ /dev/null @@ -1,193 +0,0 @@ -// -// Framebuffer.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using ObjectTK.Exceptions; -using ObjectTK.Textures; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Buffers -{ - /// <summary> - /// Represents a framebuffer object. - /// </summary> - public class Framebuffer - : GLObject - { - /// <summary> - /// Creates a new framebuffer object. - /// </summary> - public Framebuffer() - : base(GL.GenFramebuffer()) - { - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteFramebuffer(Handle); - } - - /// <summary> - /// Binds this framebuffer. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - public void Bind(FramebufferTarget target) - { - GL.BindFramebuffer(target, Handle); - } - - /// <summary> - /// Unbind this framebuffer, i.e. bind the default framebuffer. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - public static void Unbind(FramebufferTarget target) - { - GL.BindFramebuffer(target, 0); - } - - /// <summary> - /// Attaches the given texture level to the an attachment point. - /// </summary> - /// <remarks> - /// If texture is a three-dimensional, cube map array, cube map, one- or two-dimensional array, or two-dimensional multisample array texture - /// the specified texture level is an array of images and the framebuffer attachment is considered to be layered. - /// </remarks> - /// <param name="target">The framebuffer target to bind to.</param> - /// <param name="attachment">The attachment point to attach to.</param> - /// <param name="texture">The texture to attach.</param> - /// <param name="level">The level of the texture to attach.</param> - public void Attach(FramebufferTarget target, FramebufferAttachment attachment, Texture texture, int level = 0) - { - texture.AssertLevel(level); - AssertActive(target); - GL.FramebufferTexture(target, attachment, texture.Handle, level); - CheckState(target); - } - - /// <summary> - /// Attaches a single layer of the given texture level to an attachment point. - /// </summary> - /// <remarks> - /// Note that for cube maps and cube map arrays the <paramref name="layer"/> parameter actually indexes the layer-faces.<br/> - /// Thus for cube maps the layer parameter equals the face to be bound.<br/> - /// For cube map arrays the layer parameter can be calculated as 6 * arrayLayer + face, which is done automatically when using - /// the corresponding overload <see cref="Attach(FramebufferTarget, FramebufferAttachment, TextureCubemapArray, int, int, int)"/>. - /// </remarks> - /// <param name="target">The framebuffer target to bind to.</param> - /// <param name="attachment">The attachment point to attach to.</param> - /// <param name="texture">The texture to attach.</param> - /// <param name="layer">The layer of the texture to attach.</param> - /// <param name="level">The level of the texture to attach.</param> - public void Attach(FramebufferTarget target, FramebufferAttachment attachment, LayeredTexture texture, int layer, int level = 0) - { - texture.AssertLevel(level); - AssertActive(target); - GL.FramebufferTextureLayer(target, attachment, texture.Handle, level, layer); - CheckState(target); - } - - /// <summary> - /// Attaches a single face of the given cube map texture level to the an attachment point. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - /// <param name="attachment">The attachment point to attach to.</param> - /// <param name="texture">The texture to attach.</param> - /// <param name="face">The cube map face of the texture to attach.</param> - /// <param name="level">The level of the texture to attach.</param> - public void Attach(FramebufferTarget target, FramebufferAttachment attachment, TextureCubemap texture, int face, int level = 0) - { - Attach(target, attachment, (LayeredTexture)texture, face, level); - } - - /// <summary> - /// Attaches a single face of the given cube map array texture level to an attachment point. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - /// <param name="attachment">The attachment point to attach to.</param> - /// <param name="texture">The texture to attach.</param> - /// <param name="arrayLayer">The layer of the texture to attach.</param> - /// <param name="face">The cube map face of the texture to attach.</param> - /// <param name="level">The level of the texture to attach.</param> - public void Attach(FramebufferTarget target, FramebufferAttachment attachment, TextureCubemapArray texture, int arrayLayer, int face, int level = 0) - { - Attach(target, attachment, (LayeredTexture)texture, 6 * arrayLayer + face, level); - } - - /// <summary> - /// Attaches the render buffer to the given attachment point. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - /// <param name="attachment">The attachment point to attach to.</param> - /// <param name="renderbuffer">Render buffer to attach.</param> - public void Attach(FramebufferTarget target, FramebufferAttachment attachment, Renderbuffer renderbuffer) - { - AssertActive(target); - GL.FramebufferRenderbuffer(target, attachment, RenderbufferTarget.Renderbuffer, renderbuffer.Handle); - CheckState(target); - } - - /// <summary> - /// Detaches the currently attached texture from the given attachment point. - /// </summary> - /// <param name="attachment">The attachment point to detach from.</param> - /// <param name="target">The framebuffer target to bind to.</param> - public void DetachTexture(FramebufferTarget target, FramebufferAttachment attachment) - { - AssertActive(target); - GL.FramebufferTexture(target, attachment, 0, 0); - CheckState(target); - } - - /// <summary> - /// Detaches the currently attached render buffer from the given attachment point. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - /// <param name="attachment">The attachment point to detach from.</param> - public void DetachRenderbuffer(FramebufferTarget target, FramebufferAttachment attachment) - { - AssertActive(target); - GL.FramebufferRenderbuffer(target, attachment, RenderbufferTarget.Renderbuffer, 0); - CheckState(target); - } - - /// <summary> - /// Check if the current framebuffer status is "frambuffer complete", throws on error. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - public void CheckState(FramebufferTarget target) - { -#if DEBUG - Utility.Assert("Error on framebuffer attach/detach"); - Utility.Assert(GL.CheckFramebufferStatus(target), FramebufferErrorCode.FramebufferComplete, "Framebuffer is not framebuffer complete."); -#endif - } - - /// <summary> - /// Throws an <see cref="ObjectNotBoundException"/> if this framebuffer is not the currently active one. - /// </summary> - /// <param name="target">The framebuffer target to bind to.</param> - public void AssertActive(FramebufferTarget target) - { -#if DEBUG - int activeHandle; - GetPName binding; - switch (target) - { - case FramebufferTarget.ReadFramebuffer: binding = GetPName.ReadFramebufferBinding; break; - case FramebufferTarget.DrawFramebuffer: binding = GetPName.DrawFramebufferBinding; break; - case FramebufferTarget.Framebuffer: binding = GetPName.FramebufferBinding; break; - default: throw new ArgumentOutOfRangeException(); - } - GL.GetInteger(binding, out activeHandle); - if (activeHandle != Handle) throw new ObjectNotBoundException("Can not access an unbound framebuffer. Call Framebuffer.Bind() first."); -#endif - } - } -} \ No newline at end of file diff --git a/ObjectTK/Buffers/Renderbuffer.cs b/ObjectTK/Buffers/Renderbuffer.cs deleted file mode 100644 index 52d259a..0000000 --- a/ObjectTK/Buffers/Renderbuffer.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// Renderbuffer.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Buffers -{ - /// <summary> - /// Represents a renderbuffer object. - /// </summary> - public class Renderbuffer - : GLObject - { - /// <summary> - /// Creates a new renderbuffer object. - /// </summary> - public Renderbuffer() - : base(GL.GenRenderbuffer()) - { - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteRenderbuffer(Handle); - } - - /// <summary> - /// Initializes the renderbuffer with the given parameters. - /// </summary> - /// <param name="storage">Specifies the internal format.</param> - /// <param name="width">The width of the renderbuffer.</param> - /// <param name="height">The height of the renderbuffer.</param> - public void Init(RenderbufferStorage storage, int width, int height) - { - GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, Handle); - GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, storage, width, height); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Buffers/TransformFeedback.cs b/ObjectTK/Buffers/TransformFeedback.cs deleted file mode 100644 index cd03378..0000000 --- a/ObjectTK/Buffers/TransformFeedback.cs +++ /dev/null @@ -1,132 +0,0 @@ -// -// TransformFeedback.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using ObjectTK.Exceptions; -using ObjectTK.Shaders.Variables; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Buffers -{ - /// <summary> - /// Represents a transform feedback object. - /// </summary> - public class TransformFeedback - : GLObject - { - /// <summary> - /// Creates a new transform feedback buffer. - /// </summary> - public TransformFeedback() - : base(GL.GenTransformFeedback()) - { - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteTransformFeedback(Handle); - } - - /// <summary> - /// Binds the transform feedback buffer. - /// </summary> - public void Bind() - { - GL.BindTransformFeedback(TransformFeedbackTarget.TransformFeedback, Handle); - } - - /// <summary> - /// Unbinds the transform feedback buffer. - /// </summary> - public void UnBind() - { - AssertActive(); - GL.BindTransformFeedback(TransformFeedbackTarget.TransformFeedback, 0); - } - - /// <summary> - /// Start transform feedback operation. - /// </summary> - /// <param name="primitiveMode">Specify the output type of the primitives that will be recorded into the buffer objects that are bound for transform feedback.</param> - public void Begin(TransformFeedbackPrimitiveType primitiveMode) - { - AssertActive(); - GL.BeginTransformFeedback(primitiveMode); - } - - /// <summary> - /// End transform feedback operation. - /// </summary> - public void End() - { - AssertActive(); - GL.EndTransformFeedback(); - } - - /// <summary> - /// Pause transform feedback operations. - /// </summary> - public void Pause() - { - AssertActive(); - GL.PauseTransformFeedback(); - } - - /// <summary> - /// Resume transform feedback operations. - /// </summary> - public void Resume() - { - AssertActive(); - GL.ResumeTransformFeedback(); - } - - /// <summary> - /// Binds a buffer to the binding index utilized by the given transform feeedback varying. - /// </summary> - /// <param name="transformOut">Specifies a transform feedback varying.</param> - /// <param name="buffer">Specifies a buffer object to bind.</param> - public void BindOutput<T>(TransformOut transformOut, Buffer<T> buffer) - where T : struct - { - AssertActive(); - GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, transformOut.Index, buffer.Handle); - } - - /// <summary> - /// Binds part of a buffer to the binding index utilized by the given transform feeedback varying. - /// </summary> - /// <remarks> - /// If multiple parts of the same buffer are bound as transform feedback output targets they must not overlap. - /// </remarks> - /// <param name="transformOut">Specifies a transform feedback varying.</param> - /// <param name="buffer">Specifies a buffer object to bind.</param> - /// <param name="offset">Specifies the starting offset in bytes into the buffer object.</param> - /// <param name="size">Specifies the amount of data in bytes that can be written to the buffer.</param> - public void BindOutput<T>(TransformOut transformOut, Buffer<T> buffer, int offset, int size) - where T : struct - { - AssertActive(); - GL.BindBufferRange(BufferRangeTarget.TransformFeedbackBuffer, transformOut.Index, buffer.Handle, (IntPtr)offset, (IntPtr)size); - } - - /// <summary> - /// Throws an <see cref="ObjectNotBoundException"/> if this vertex array is not the currently active one. - /// </summary> - public void AssertActive() - { -#if DEBUG - int activeHandle; - GL.GetInteger(GetPName.TransformFeedbackBinding, out activeHandle); - if (activeHandle != Handle) throw new ObjectNotBoundException("Transform feedback object is not bound."); -#endif - } - } -} \ No newline at end of file diff --git a/ObjectTK/Buffers/VertexArray.cs b/ObjectTK/Buffers/VertexArray.cs deleted file mode 100644 index 57d515b..0000000 --- a/ObjectTK/Buffers/VertexArray.cs +++ /dev/null @@ -1,237 +0,0 @@ -// -// VertexArray.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using ObjectTK.Exceptions; -using ObjectTK.Shaders.Variables; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Buffers -{ - /// <summary> - /// Represents a vertex array object.<br/> - /// TODO: add support for instanced vertex attributes with glVertexAttribDivisor (or maybe glVertexBindingDivisor) - /// </summary> - public class VertexArray - : GLObject - { - /// <summary> - /// Initializes a new vertex array object. - /// </summary> - public VertexArray() - : base(GL.GenVertexArray()) - { - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteVertexArray(Handle); - } - - /// <summary> - /// Bind the vertex array. - /// </summary> - public void Bind() - { - GL.BindVertexArray(Handle); - } - - /// <summary> - /// Render primitives from array data. - /// </summary> - /// <param name="mode">Specifies what kind of primitives to render.</param> - /// <param name="first">Specifies the starting index in the enabled arrays.</param> - /// <param name="count">Specifies the number of indices to be rendered.</param> - public void DrawArrays(PrimitiveType mode, int first, int count) - { - AssertActive(); - GL.DrawArrays(mode, first, count); - } - - public void DrawArraysInstances(PrimitiveType mode, int first, int count, int instanceCount) - { - AssertActive(); - GL.DrawArraysInstanced(mode, first, count, instanceCount); - } - - public void DrawArraysIndirect(PrimitiveType mode, int offset = 0) - { - AssertActive(); - GL.DrawArraysIndirect(mode, new IntPtr(offset)); - } - - public void MultiDrawArrays(PrimitiveType mode, int[] first, int[] count) - { - AssertActive(); - if (first.Length != count.Length) throw new ArgumentException("The length of first and count must be equal."); - GL.MultiDrawArrays(mode, first, count, count.Length); - } - - /// <summary> - /// Render primitives from array data using the element buffer. - /// </summary> - /// <param name="mode">Specifies what kind of primitives to render.</param> - /// <param name="count">Specifies the number of elements to be rendered.</param> - /// <param name="type">Specifies the type of the values in indices.</param> - public void DrawElements(PrimitiveType mode, int count, DrawElementsType type = DrawElementsType.UnsignedInt) - { - AssertActive(); - GL.DrawElements(mode, count, type, IntPtr.Zero); - } - - public void DrawElementsIndirect(PrimitiveType mode, DrawElementsType type = DrawElementsType.UnsignedInt, int offset = 0) - { - AssertActive(); - GL.DrawElementsIndirect(mode, (All)type, new IntPtr(offset)); - } - - public void MultiDrawElements(PrimitiveType mode, int[] count, DrawElementsType type = DrawElementsType.UnsignedInt) - { - AssertActive(); - GL.MultiDrawElements(mode, count, type, IntPtr.Zero, count.Length); - } - - public void DrawTransformFeedback(PrimitiveType mode, TransformFeedback transformFeedback) - { - AssertActive(); - GL.DrawTransformFeedback(mode, transformFeedback.Handle); - } - - /// <summary> - /// Binds the given buffer to the element array buffer target. - /// </summary> - public void BindElementBuffer<T>(Buffer<T> buffer) - where T : struct - { - AssertActive(); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, buffer.Handle); - } - - /// <summary> - /// Unbinds any buffer bound to the element array buffer target. - /// </summary> - public void UnbindElementBuffer() - { - AssertActive(); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. Uses the buffers element size as the stride parameter with an offset of zero. - /// The other parameters, namely components, type and normalized are chosen according to the corresponding <see cref="VertexAttribAttribute"/> attribute. - /// </summary> - public void BindAttribute<T>(VertexAttrib attribute, Buffer<T> buffer) - where T : struct - { - BindAttribute(attribute, buffer, attribute.Components, attribute.Type, buffer.ElementSize, 0, attribute.Normalized); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. Uses the buffers element size as the stride parameter and the given offset. - /// The other parameters, namely components, type and normalized are chosen according to the corresponding <see cref="VertexAttribAttribute"/> attribute. - /// </summary> - public void BindAttribute<T>(VertexAttrib attribute, Buffer<T> buffer, int offset) - where T : struct - { - BindAttribute(attribute, buffer, attribute.Components, attribute.Type, buffer.ElementSize, offset, attribute.Normalized); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. Uses the given stride and offset parameters. - /// The other parameters, namely components, type and normalized are chosen according to the corresponding <see cref="VertexAttribAttribute"/> attribute. - /// </summary> - public void BindAttribute<T>(VertexAttrib attribute, Buffer<T> buffer, int stride, int offset) - where T : struct - { - BindAttribute(attribute, buffer, attribute.Components, attribute.Type, stride, offset, attribute.Normalized); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. - /// </summary> - public void BindAttribute<T>(VertexAttrib attribute, Buffer<T> buffer, int stride, int offset, bool normalized) - where T : struct - { - BindAttribute(attribute, buffer, attribute.Components, attribute.Type, stride, offset, normalized); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. - /// </summary> - public void BindAttribute<T>(VertexAttrib attribute, Buffer<T> buffer, int components, int stride, int offset) - where T : struct - { - BindAttribute(attribute, buffer, components, attribute.Type, stride, offset, attribute.Normalized); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. - /// </summary> - public void BindAttribute<T>(VertexAttrib attribute, Buffer<T> buffer, int components, int stride, int offset, bool normalized) - where T : struct - { - BindAttribute(attribute, buffer, components, attribute.Type, stride, offset, normalized); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. - /// </summary> - public void BindAttribute<T>(VertexAttrib attribute, Buffer<T> buffer, int components, VertexAttribPointerType type, int stride, int offset, bool normalized) - where T : struct - { - if (!attribute.Active) return; - BindAttribute(attribute.Index, buffer, components, type, stride, offset, normalized); - } - - /// <summary> - /// Binds the buffer to the given vertex attribute. - /// </summary> - public void BindAttribute<T>(int index, Buffer<T> buffer, int components, VertexAttribPointerType type, int stride, int offset, bool normalized) - where T : struct - { - AssertActive(); - // bind given buffer - GL.BindBuffer(BufferTarget.ArrayBuffer, buffer.Handle); - // make sure the vertex attribute is enabled - GL.EnableVertexAttribArray(index); - // set the vertex attribute pointer to the current buffer - GL.VertexAttribPointer(index, components, type, normalized, stride, offset); - } - - /// <summary> - /// Disable the given vertex attribute. - /// </summary> - public void UnbindAttribute(VertexAttrib attribute) - { - UnbindAttribute(attribute.Index); - } - - /// <summary> - /// Disable the given vertex attribute. - /// </summary> - public void UnbindAttribute(int index) - { - AssertActive(); - GL.DisableVertexAttribArray(index); - } - - /// <summary> - /// Throws an <see cref="ObjectNotBoundException"/> if this vertex array is not the currently active one. - /// </summary> - public void AssertActive() - { -#if DEBUG - int activeHandle; - GL.GetInteger(GetPName.VertexArrayBinding, out activeHandle); - if (activeHandle != Handle) throw new ObjectNotBoundException("Vertex array object is not bound."); -#endif - } - } -} \ No newline at end of file diff --git a/ObjectTK/Exceptions/ObjectNotBoundException.cs b/ObjectTK/Exceptions/ObjectNotBoundException.cs deleted file mode 100644 index dfefe7d..0000000 --- a/ObjectTK/Exceptions/ObjectNotBoundException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// ObjectNotBoundException.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; - -namespace ObjectTK.Exceptions -{ - /// <summary> - /// The exception that is thrown when an object is used which must be bound before usage. - /// </summary> - [Serializable] - public class ObjectNotBoundException - : ObjectTKException - { - internal ObjectNotBoundException(string message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Exceptions/ObjectTKException.cs b/ObjectTK/Exceptions/ObjectTKException.cs deleted file mode 100644 index f7f8109..0000000 --- a/ObjectTK/Exceptions/ObjectTKException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// ObjectTKException.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; - -namespace ObjectTK.Exceptions -{ - /// <summary> - /// The exception that is thrown when an ObjectTK related error occurs. - /// </summary> - [Serializable] - public class ObjectTKException - : Exception - { - internal ObjectTKException(string message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Exceptions/ProgramException.cs b/ObjectTK/Exceptions/ProgramException.cs deleted file mode 100644 index d5eb444..0000000 --- a/ObjectTK/Exceptions/ProgramException.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// ProgramException.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Runtime.Serialization; - -namespace ObjectTK.Exceptions -{ - /// <summary> - /// The exception that is thrown when a program related error occurs. - /// </summary> - [Serializable] - public class ProgramException - : ObjectTKException - { - public string InfoLog { get; private set; } - - internal ProgramException(string message, string infoLog) - : base(message) - { - InfoLog = infoLog; - } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("InfoLog", InfoLog); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Exceptions/ProgramLinkException.cs b/ObjectTK/Exceptions/ProgramLinkException.cs deleted file mode 100644 index 10c5b47..0000000 --- a/ObjectTK/Exceptions/ProgramLinkException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// ProgramLinkException.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; - -namespace ObjectTK.Exceptions -{ - /// <summary> - /// The exception that is thrown when a program link error occurs. - /// </summary> - [Serializable] - public class ProgramLinkException - : ProgramException - { - internal ProgramLinkException(string message, string infoLog) - : base(message, infoLog) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Exceptions/QueryException.cs b/ObjectTK/Exceptions/QueryException.cs deleted file mode 100644 index 44041f2..0000000 --- a/ObjectTK/Exceptions/QueryException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// QueryException.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; - -namespace ObjectTK.Exceptions -{ - /// <summary> - /// The exception that is thrown when a query related error occurs. - /// </summary> - [Serializable] - public class QueryException - : ObjectTKException - { - internal QueryException(string message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Exceptions/ShaderCompileException.cs b/ObjectTK/Exceptions/ShaderCompileException.cs deleted file mode 100644 index d11f4a9..0000000 --- a/ObjectTK/Exceptions/ShaderCompileException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// ShaderCompileException.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; - -namespace ObjectTK.Exceptions -{ - /// <summary> - /// The exception that is thrown when a shader compile error occurs. - /// </summary> - [Serializable] - public class ShaderCompileException - : ProgramException - { - internal ShaderCompileException(string message, string infoLog) - : base(message, infoLog) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Exceptions/UniformTypeNotSupportedException.cs b/ObjectTK/Exceptions/UniformTypeNotSupportedException.cs deleted file mode 100644 index f83f249..0000000 --- a/ObjectTK/Exceptions/UniformTypeNotSupportedException.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// UniformTypeNotSupportedException.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Runtime.Serialization; -using ObjectTK.Shaders.Variables; - -namespace ObjectTK.Exceptions -{ - /// <summary> - /// The exception that is thrown when the generic type parameter used for an instance of <see cref="Uniform{T}"/> is not supported. - /// </summary> - [Serializable] - public class UniformTypeNotSupportedException - : ObjectTKException - { - /// <summary> - /// The unsupported type parameter to <see cref="Uniform{T}"/> which caused the initialization to fail. - /// </summary> - public readonly Type UniformType; - - internal UniformTypeNotSupportedException(Type uniformType) - : base(string.Format("Uniforms of type {0} are not supported", uniformType.Name)) - { - UniformType = uniformType; - } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("UniformType", UniformType); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Extensions.cs b/ObjectTK/Extensions.cs deleted file mode 100644 index 40c478b..0000000 --- a/ObjectTK/Extensions.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -// Extensions.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Reflection; -using OpenTK; - -namespace ObjectTK -{ - /// <summary> - /// Contains extension methods. - /// </summary> - public static class Extensions - { - /// <summary> - /// Transforms this <see cref="Color"/> object to a <see cref="Vector4"/>.<br/> - /// The resulting vector contains values in the range of (0,1). - /// </summary> - /// <param name="color">The Color object to transform.</param> - /// <returns>A Vector4 object containing the color information.</returns> - public static Vector4 ToVector4(this Color color) - { - return new Vector4(color.R/255f, color.G/255f, color.B/255f, color.A/255f); - } - - /// <summary> - /// Transforms this <see cref="Color"/> object to an unsigned integer.<br/> - /// The components are formatted compatible to OpenGL. - /// </summary> - /// <param name="color">The Color object to transform.</param> - /// <returns>An unsigned integer containing the color information.</returns> - public static uint ToRgba32(this Color color) - { - return (uint)(color.A << 24 | color.B << 16 | color.G << 8 | color.R); - } - - /// <summary> - /// Transforms this unsigned integer to a <see cref="Color"/> object.<br/> - /// Requires the information formatted like the output of <see cref="ToRgba32"/>. - /// </summary> - /// <param name="color">The unsigned integer to transform.</param> - /// <returns>A Color object containing the same information.</returns> - public static Color Rgba32ToColor(this uint color) - { - const uint mask = 0x000000FF; - return Color.FromArgb((int)(color >> 24 & mask), (int)(color & mask), (int)(color >> 8 & mask), (int)(color >> 16 & mask)); - } - - /// <summary> - /// Retrieves custom attributes in a typed enumerable. - /// </summary> - /// <typeparam name="T">The type of attribute to search for. Only attributes that are assignable to this type are returned.</typeparam> - /// <param name="type">The member on which to look for custom attributes.</param> - /// <param name="inherit">Specifies whether to search this member's inheritance chain to find the attributes.</param> - /// <returns>An IEnumerable of custom attributes applied to this member.</returns> - public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo type, bool inherit) - { - return type.GetCustomAttributes(typeof(T), inherit).Cast<T>(); - } - } -} diff --git a/ObjectTK/GLObject.cs b/ObjectTK/GLObject.cs deleted file mode 100644 index b80f8b9..0000000 --- a/ObjectTK/GLObject.cs +++ /dev/null @@ -1,55 +0,0 @@ -// -// GLObject.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; - -namespace ObjectTK -{ - /// <summary> - /// Represents an OpenGL handle.<br/> - /// Must be disposed explicitly, otherwise there will be a memory leak which will be logged as a warning. - /// </summary> - public abstract class GLObject - : GLResource - , IEquatable<GLObject> - { - /// <summary> - /// The OpenGL handle. - /// </summary> - public readonly int Handle; - - /// <summary> - /// Initializes a new instance of the GLResource class. - /// </summary> - protected GLObject(int handle) - { - Handle = handle; - } - - public bool Equals(GLObject other) - { - return other != null && Handle.Equals(other.Handle); - } - - public override bool Equals(object obj) - { - return obj is GLObject && Equals((GLObject) obj); - } - - public override int GetHashCode() - { - return Handle.GetHashCode(); - } - - public override string ToString() - { - return string.Format("{0}({1})", GetType().Name, Handle); - } - } -} \ No newline at end of file diff --git a/ObjectTK/GLResource.cs b/ObjectTK/GLResource.cs deleted file mode 100644 index 5e33c08..0000000 --- a/ObjectTK/GLResource.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// GLResource.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Reflection; -using ObjectTK.Exceptions; - -namespace ObjectTK -{ - /// <summary> - /// Represents an OpenGL resource.<br/> - /// Must be disposed explicitly, otherwise a warning will be logged indicating a memory leak.<br/> - /// Can be derived to inherit the dispose pattern. - /// </summary> - public abstract class GLResource - : IDisposable - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(GLResource)); - - /// <summary> - /// Gets a values specifying if this resource has already been disposed. - /// </summary> - public bool IsDisposed { get; private set; } - - /// <summary> - /// Initializes a new instance of the GLObject class. - /// </summary> - protected GLResource() - { - IsDisposed = false; - } - - /// <summary> - /// Called by the garbage collector and an indicator for a resource leak because the manual dispose prevents this destructor from being called. - /// </summary> - ~GLResource() - { - Logger?.WarnFormat("GLResource leaked: {0}", this); - Dispose(false); -#if DEBUG - throw new ObjectTKException(string.Format("GLResource leaked: {0}", this)); -#endif - } - - /// <summary> - /// Releases all OpenGL handles related to this resource. - /// </summary> - public void Dispose() - { - // safely handle multiple calls to dispose - if (IsDisposed) return; - IsDisposed = true; - // dipose this resource - Dispose(true); - // prevent the destructor from being called - GC.SuppressFinalize(this); - // make sure the garbage collector does not eat our object before it is properly disposed - GC.KeepAlive(this); - } - - /// <summary> - /// Releases all OpenGL handles related to this resource. - /// </summary> - /// <param name="manual">True if the call is performed explicitly and within the OpenGL thread, false if it is caused by the garbage collector and therefore from another thread and the result of a resource leak.</param> - protected abstract void Dispose(bool manual); - - /// <summary> - /// Automatically calls <see cref="Dispose()"/> on all <see cref="GLResource"/> objects found on the given object. - /// </summary> - /// <param name="obj"></param> - public static void DisposeAll(object obj) - { - // get all fields, including backing fields for properties - foreach (var field in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) - { - // check if it should be released - if (typeof (GLResource).IsAssignableFrom(field.FieldType)) - { - // and release it - ((GLResource)field.GetValue(obj)).Dispose(); - } - } - } - } -} \ No newline at end of file diff --git a/ObjectTK/Logging/DefaultLogImpl.cs b/ObjectTK/Logging/DefaultLogImpl.cs deleted file mode 100644 index e42acb0..0000000 --- a/ObjectTK/Logging/DefaultLogImpl.cs +++ /dev/null @@ -1,135 +0,0 @@ -// -// DefaultLogImpl.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using log4net; -using log4net.Core; - -namespace ObjectTK.Logging -{ - public class DefaultLogImpl : IObjectTKLogger - { - protected virtual Type ThisDeclaringType => typeof(DefaultLogImpl); - protected ILogger _logger => _log.Logger; - - protected readonly ILog _log; - - public DefaultLogImpl(ILog logger) - { - _log = logger; - } - - public bool IsFatalEnabled => _log.IsFatalEnabled; - - public bool IsWarnEnabled => _log.IsWarnEnabled; - - public bool IsInfoEnabled => _log.IsInfoEnabled; - - public bool IsDebugEnabled => _log.IsDebugEnabled; - - public bool IsErrorEnabled => _log.IsErrorEnabled; - - private void Log(Level level, object message, Exception exception = null) - { - if (!_logger.IsEnabledFor(level)) return; - _logger.Log(ThisDeclaringType, level, message, exception); - } - - private void LogFormat(Level level, IFormatProvider provider, string format, params object[] args) - { - if (!_logger.IsEnabledFor(level)) return; - - var message = (provider == null) ? - string.Format(format, args) : - string.Format(provider, format, args); - - _logger.Log(ThisDeclaringType, level, message, null); - } - - private void LogFormat(Level level, string format, params object[] args) - { - LogFormat(null, format, args); - } - - public void Debug(object message, Exception exception = null) - { - Log(Level.Debug, message); - } - - public void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Debug, provider, format, args); - } - - public void DebugFormat(string format, params object[] args) - { - LogFormat(Level.Debug, null, format, args); - } - - public void Error(object message, Exception exception = null) - { - Log(Level.Error, message); - } - - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Error, provider, format, args); - } - - public void ErrorFormat(string format, params object[] args) - { - LogFormat(Level.Error, null, format, args); - } - - public void Fatal(object message, Exception exception = null) - { - Log(Level.Fatal, message); - } - - public void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Fatal, provider, format, args); - } - - public void FatalFormat(string format, params object[] args) - { - LogFormat(Level.Fatal, null, format, args); - } - - public void Info(object message, Exception exception = null) - { - Log(Level.Info, message); - } - - public void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Info, provider, format, args); - } - - public void InfoFormat(string format, params object[] args) - { - LogFormat(Level.Info, null, format, args); - } - - public void Warn(object message, Exception exception = null) - { - Log(Level.Warn, message); - } - - public void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Warn, provider, format, args); - } - - public void WarnFormat(string format, params object[] args) - { - LogFormat(Level.Warn, null, format, args); - } - } -} diff --git a/ObjectTK/Logging/IObjectTKLogger.cs b/ObjectTK/Logging/IObjectTKLogger.cs deleted file mode 100644 index 57b1b89..0000000 --- a/ObjectTK/Logging/IObjectTKLogger.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// IObjectTKLogger.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace ObjectTK.Logging -{ - public interface IObjectTKLogger - { - bool IsFatalEnabled { get; } - bool IsWarnEnabled { get; } - bool IsInfoEnabled { get; } - bool IsDebugEnabled { get; } - bool IsErrorEnabled { get; } - - void Debug(object message, Exception exception = null); - void DebugFormat(IFormatProvider provider, string format, params object[] args); - void DebugFormat(string format, params object[] args); - - void Error(object message, Exception exception = null); - void ErrorFormat(IFormatProvider provider, string format, params object[] args); - void ErrorFormat(string format, params object[] args); - - void Fatal(object message, Exception exception = null); - void FatalFormat(IFormatProvider provider, string format, params object[] args); - void FatalFormat(string format, params object[] args); - - void Info(object message, Exception exception = null); - void InfoFormat(IFormatProvider provider, string format, params object[] args); - void InfoFormat(string format, params object[] args); - - void Warn(object message, Exception exception = null); - void WarnFormat(IFormatProvider provider, string format, params object[] args); - void WarnFormat(string format, params object[] args); - } -} diff --git a/ObjectTK/Logging/LogFactory.cs b/ObjectTK/Logging/LogFactory.cs deleted file mode 100644 index 32e5f46..0000000 --- a/ObjectTK/Logging/LogFactory.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// LogFactory.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.IO; -using log4net; - -namespace ObjectTK.Logging -{ - public static class LogFactory - { - public static readonly bool IsAvailable = File.Exists(AppDomain.CurrentDomain.BaseDirectory + "log4net.dll"); - - static IObjectTKLogger CreateLogger(Type type) - { - var logger = LogManager.GetLogger(type); - return logger != null ? new DefaultLogImpl(logger) : null; - } - - public static IObjectTKLogger GetLogger(Type type) - { - return IsAvailable ? CreateLogger(type) : null; - } - } -} diff --git a/ObjectTK/MathF.cs b/ObjectTK/MathF.cs deleted file mode 100644 index f0255ba..0000000 --- a/ObjectTK/MathF.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -// MathF.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using OpenTK; - -namespace ObjectTK -{ - /// <summary> - /// Provides mathematical constants and functions with float precision. - /// </summary> - public static class MathF - { - /// <summary> - /// Returns the sine of the specified angle. - /// </summary> - /// <param name="angle">An angle, measured in radians.</param> - /// <returns>The sine of angle. If angle is equal to NaN, NegativeInfinity, or PositiveInfinity, this method returns NaN.</returns> - public static float Sin(float angle) - { - return (float)Math.Sin(angle); - } - - /// <summary> - /// Returns the cosine of the specified angle. - /// </summary> - /// <param name="angle">An angle, measured in radians.</param> - /// <returns>The cosine of angle. If angle is equal to NaN, NegativeInfinity, or PositiveInfinity, this method returns NaN.</returns> - public static float Cos(float angle) - { - return (float)Math.Cos(angle); - } - - /// <summary> - /// Return the normal matrix, that is the upper 3x3 part of the inverted and transposed matrix. - /// </summary> - /// <param name="matrix">Specifies the transformation matrix.</param> - /// <returns>The normal matrix.</returns> - public static Matrix3 GetNormalMatrix(this Matrix4 matrix) - { - matrix.Invert(); - matrix.Transpose(); - return new Matrix3(matrix); - } - } -} \ No newline at end of file diff --git a/ObjectTK/ObjectTK.csproj b/ObjectTK/ObjectTK.csproj deleted file mode 100644 index c9c5171..0000000 --- a/ObjectTK/ObjectTK.csproj +++ /dev/null @@ -1,128 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> - <PropertyGroup> - <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> - <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProductVersion>8.0.30703</ProductVersion> - <SchemaVersion>2.0</SchemaVersion> - <ProjectGuid>{0EE3347B-1BBE-44CA-8295-22DA13AE914A}</ProjectGuid> - <OutputType>Library</OutputType> - <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>ObjectTK</RootNamespace> - <AssemblyName>ObjectTK</AssemblyName> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <FileAlignment>512</FileAlignment> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DebugSymbols>true</DebugSymbols> - <DebugType>full</DebugType> - <Optimize>false</Optimize> - <OutputPath>bin\Debug\</OutputPath> - <DefineConstants>DEBUG;TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <DocumentationFile>bin\Debug\ObjectTK.xml</DocumentationFile> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <DebugType>pdbonly</DebugType> - <Optimize>true</Optimize> - <OutputPath>bin\Release\</OutputPath> - <DefineConstants>TRACE</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <DocumentationFile>bin\Release\ObjectTK.xml</DocumentationFile> - </PropertyGroup> - <ItemGroup> - <Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\log4net.2.0.3\lib\net40-full\log4net.dll</HintPath> - </Reference> - <Reference Include="OpenTK, Version=1.1.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\OpenTK.1.1.1589.5942\lib\NET40\OpenTK.dll</HintPath> - </Reference> - <Reference Include="System" /> - <Reference Include="System.Core" /> - <Reference Include="System.Drawing" /> - </ItemGroup> - <ItemGroup> - <Compile Include="Buffers\Buffer.cs" /> - <Compile Include="Buffers\BufferPod.cs" /> - <Compile Include="Buffers\Framebuffer.cs" /> - <Compile Include="Buffers\VertexArray.cs" /> - <Compile Include="Buffers\Renderbuffer.cs" /> - <Compile Include="Buffers\TransformFeedback.cs" /> - <Compile Include="Exceptions\ObjectTKException.cs" /> - <Compile Include="Exceptions\ObjectNotBoundException.cs" /> - <Compile Include="Exceptions\ProgramException.cs" /> - <Compile Include="Exceptions\ProgramLinkException.cs" /> - <Compile Include="Exceptions\QueryException.cs" /> - <Compile Include="Exceptions\ShaderCompileException.cs" /> - <Compile Include="Exceptions\UniformTypeNotSupportedException.cs" /> - <Compile Include="Extensions.cs" /> - <Compile Include="GLObject.cs" /> - <Compile Include="GLResource.cs" /> - <Compile Include="Logging\DefaultLogImpl.cs" /> - <Compile Include="Logging\IObjectTKLogger.cs" /> - <Compile Include="Logging\LogFactory.cs" /> - <Compile Include="MathF.cs" /> - <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Queries\QueryIndexer.cs" /> - <Compile Include="Queries\QueryMapping.cs" /> - <Compile Include="Shaders\ComputeProgram.cs" /> - <Compile Include="Shaders\Effect.cs" /> - <Compile Include="Shaders\Program.cs" /> - <Compile Include="Shaders\ProgramFactory.cs" /> - <Compile Include="Shaders\Shader.cs" /> - <Compile Include="Shaders\TransformProgram.cs" /> - <Compile Include="Shaders\Sources\ComputeShaderSourceAttribute.cs" /> - <Compile Include="Shaders\Sources\FragmentShaderSourceAttribute.cs" /> - <Compile Include="Shaders\Sources\GeometryShaderSourceAttribute.cs" /> - <Compile Include="Shaders\Sources\ShaderSourceAttribute.cs" /> - <Compile Include="Shaders\Sources\TessControlShaderSourceAttribute.cs" /> - <Compile Include="Shaders\Sources\TessEvaluationShaderSourceAttribute.cs" /> - <Compile Include="Shaders\Sources\VertexShaderSourceAttribute.cs" /> - <Compile Include="Shaders\Variables\BufferBinding.cs" /> - <Compile Include="Shaders\Variables\FragData.cs" /> - <Compile Include="Shaders\Variables\ImageUniform.cs" /> - <Compile Include="Shaders\Variables\ShaderStorage.cs" /> - <Compile Include="Shaders\Variables\ProgramVariable.cs" /> - <Compile Include="Shaders\Variables\TextureUniform.cs" /> - <Compile Include="Shaders\Variables\TransformOut.cs" /> - <Compile Include="Shaders\Variables\Uniform.cs" /> - <Compile Include="Shaders\Variables\UniformBuffer.cs" /> - <Compile Include="Shaders\Variables\UniformSetter.cs" /> - <Compile Include="Shaders\Variables\VertexAttrib.cs" /> - <Compile Include="Shaders\Variables\VertexAttribAttribute.cs" /> - <Compile Include="Textures\TextureBuffer.cs" /> - <Compile Include="Textures\BitmapFormat.cs" /> - <Compile Include="Textures\LayeredTexture.cs" /> - <Compile Include="Textures\Sampler.cs" /> - <Compile Include="Textures\Texture.cs" /> - <Compile Include="Textures\Texture1D.cs" /> - <Compile Include="Textures\Texture1DArray.cs" /> - <Compile Include="Textures\Texture2D.cs" /> - <Compile Include="Textures\Texture2DArray.cs" /> - <Compile Include="Textures\Texture2DMultisample.cs" /> - <Compile Include="Textures\Texture2DMultisampleArray.cs" /> - <Compile Include="Textures\Texture3D.cs" /> - <Compile Include="Textures\TextureCubemap.cs" /> - <Compile Include="Textures\TextureCubemapArray.cs" /> - <Compile Include="Textures\BitmapTexture.cs" /> - <Compile Include="Textures\TextureFactory.cs" /> - <Compile Include="Textures\TextureRectangle.cs" /> - <Compile Include="Utility.cs" /> - <Compile Include="Vector3i.cs" /> - </ItemGroup> - <ItemGroup> - <None Include="packages.config" /> - </ItemGroup> - <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> - <!-- To modify your build process, add your task inside one of the targets below and uncomment it. - Other similar extension points exist, see Microsoft.Common.targets. - <Target Name="BeforeBuild"> - </Target> - <Target Name="AfterBuild"> - </Target> - --> -</Project> \ No newline at end of file diff --git a/ObjectTK/Properties/AssemblyInfo.cs b/ObjectTK/Properties/AssemblyInfo.cs deleted file mode 100644 index c9458d9..0000000 --- a/ObjectTK/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region License -// ObjectTK License -// Copyright (C) 2013-2015 J.C.Bernack -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see <http://www.gnu.org/licenses/>. -#endregion -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ObjectTK")] -[assembly: AssemblyDescription("Abstraction layer on top of OpenTK to provide OpenGL features in an object-oriented and type-safe manner with modern C#-style")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("JcBernack")] -[assembly: AssemblyProduct("ObjectTK")] -[assembly: AssemblyCopyright("Copyright © 2013-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("8133d931-0992-47fd-b4a0-f7ee832615cd")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.*")] \ No newline at end of file diff --git a/ObjectTK/Queries/QueryIndexer.cs b/ObjectTK/Queries/QueryIndexer.cs deleted file mode 100644 index eb12ef7..0000000 --- a/ObjectTK/Queries/QueryIndexer.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -// QueryIndexer.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Collections.Generic; -using ObjectTK.Exceptions; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Queries -{ - /// <summary> - /// Base class for <see cref="QueryMapping{T}"/>.<br/> - /// Provides methods to prevent query collisions on standard and indexable <see cref="QueryTarget"/>s. - /// </summary> - public abstract class QueryIndexer - : GLResource - { - /// <summary> - /// Stores indices currently in use for each QueryTarget. - /// </summary> - private static readonly Dictionary<QueryTarget, SortedSet<int>> TargetIndices = new Dictionary<QueryTarget, SortedSet<int>>(); - - /// <summary> - /// Defines which <see cref="QueryTarget"/> is indexable. - /// </summary> - private static readonly List<QueryTarget> IndexableTargets = new List<QueryTarget> - { - QueryTarget.PrimitivesGenerated, - QueryTarget.TransformFeedbackPrimitivesWritten - }; - - /// <summary> - /// Acquires an unused index for the given <see cref="QueryTarget"/>. - /// </summary> - /// <param name="target">The QueryTarget to acquire an index for.</param> - /// <returns>Unused index.</returns> - protected static int AcquireIndex(QueryTarget target) - { - if (!TargetIndices.ContainsKey(target)) TargetIndices.Add(target, new SortedSet<int>()); - // find first free index - var i = 0; - foreach (var index in TargetIndices[target]) - { - if (index > i) break; - i++; - } - if (!IndexableTargets.Contains(target) && i > 0) throw new QueryException( - string.Format("Query target not indexable and the single target it already in use: {0}", target)); - // remember index is in use - TargetIndices[target].Add(i); - return i; - } - - /// <summary> - /// Releases a previously acquired index for the given <see cref="QueryTarget"/>. - /// </summary> - /// <param name="target">The QueryTarget to release the index from.</param> - /// <param name="index">The index to release.</param> - protected static void ReleaseIndex(QueryTarget target, int index) - { - TargetIndices[target].Remove(index); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Queries/QueryMapping.cs b/ObjectTK/Queries/QueryMapping.cs deleted file mode 100644 index e5b08a9..0000000 --- a/ObjectTK/Queries/QueryMapping.cs +++ /dev/null @@ -1,166 +0,0 @@ -// -// QueryMapping.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Collections.Generic; -using System.Linq; -using ObjectTK.Exceptions; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Queries -{ - /// <summary> - /// Provides named queries of hardware counters. - /// </summary> - /// <typeparam name="T">An enum type containing the query names.</typeparam> - public class QueryMapping<T> - : QueryIndexer - where T : struct, IConvertible - { - /// <summary> - /// Represents an OpenGL query. - /// </summary> - private class QueryMap - : GLObject - { - internal bool Active; - internal QueryTarget Target; - internal int Index; - - public int Value; - public int Average; - - public QueryMap() - : base(GL.GenQuery()) - { - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteQuery(Handle); - } - } - - - /// <summary> - /// Gets the average value measured for the given query name. - /// </summary> - /// <param name="key"></param> - public float this[T key] - { - get - { - return _queries[key].Average; - } - } - - /// <summary> - /// Elapsed time is measured in nanoseconds and divided by this factor for better readability.<br/> - /// A factor of 1,000 therefore results in microseconds, a factor of 1,000,000 results in milliseconds. - /// </summary> - public int ElapsedTimeFactor = 1000; - - /// <summary> - /// Weighting factor used for averaging.<br/> - /// A value close to 1 enables very fast averaging, giving noisy results.<br/> - /// A value close to 0 gives a better mean, reacting much slower to fluctuations in the results.<br/> - /// The default value is 0.05f.<br/> - /// Let the current and the previous query result be A and B, respectively, then the average is calculated with this formula:<br/> - /// average = A * AveragingFactor + B * (1-AveragingFactor);<br/> - /// </summary> - public float AveragingFactor = 0.05f; - - /// <summary> - /// Holds all QueryMap objects. - /// </summary> - private readonly Dictionary<T, QueryMap> _queries; - - /// <summary> - /// Initializes a new instance of this QueryMapping and generates required query objects. - /// </summary> - public QueryMapping() - { - if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type"); - // create a query object for each enum entry - _queries = Enum.GetValues(typeof (T)).Cast<T>().ToDictionary(_ => _, _ => new QueryMap()); - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - foreach (var queryMap in _queries.Values) - { - queryMap.Dispose(); - } - } - - /// <summary> - /// Begins the given query name. - /// </summary> - /// <param name="mapping">The query name to begin.</param> - /// <param name="target">The query target to capture.</param> - public void Begin(T mapping, QueryTarget target) - { - var map = _queries[mapping]; - if (map.Active) throw new QueryException(string.Format("Query already active: {0} {1}", target, mapping)); - map.Active = true; - map.Target = target; - map.Index = AcquireIndex(target); - GL.BeginQueryIndexed(target, map.Index, map.Handle); - } - - /// <summary> - /// End the given query name. - /// </summary> - /// <param name="mapping">The query name to end.</param> - public void End(T mapping) - { - var map = _queries[mapping]; - if (!map.Active) throw new QueryException(string.Format("Query not active: {0}", mapping)); - GL.EndQueryIndexed(map.Target, map.Index); - ReleaseIndex(map.Target, map.Index); - map.Active = false; - } - - /// <summary> - /// Updates all query results. - /// </summary> - public void Update() - { - foreach (var map in _queries.Values) - { - // get current value - GL.GetQueryObject(map.Handle, GetQueryObjectParam.QueryResult, out map.Value); - // scale elapsed time - if (map.Target == QueryTarget.TimeElapsed) map.Value /= ElapsedTimeFactor; - // calculate averaged value - map.Average = (int)(map.Value * AveragingFactor + map.Average * (1 - AveragingFactor)); - } - } - - /// <summary> - /// Retrieves query results. - /// </summary> - /// <returns>The query results.</returns> - public IEnumerable<KeyValuePair<T, int>> GetValues() - { - return _queries.Select(map => new KeyValuePair<T, int>(map.Key, map.Value.Value)); - } - - /// <summary> - /// Retrieves averaged query results. - /// </summary> - /// <returns>The averaged query results.</returns> - public IEnumerable<KeyValuePair<T, int>> GetAverages() - { - return _queries.Select(map => new KeyValuePair<T, int>(map.Key, map.Value.Average)); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/ComputeProgram.cs b/ObjectTK/Shaders/ComputeProgram.cs deleted file mode 100644 index 2554211..0000000 --- a/ObjectTK/Shaders/ComputeProgram.cs +++ /dev/null @@ -1,125 +0,0 @@ -// -// ComputeProgram.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Linq; -using ObjectTK.Shaders.Sources; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders -{ - /// <summary> - /// Represents a program object which contains compute shaders. - /// </summary> - public class ComputeProgram - : Program - { - /// <summary> - /// The work group size of the compute shader. - /// </summary> - public Vector3i WorkGroupSize { get; protected set; } - - /// <summary> - /// The total number of work groups of this compute shader. - /// </summary> - public int WorkGroupTotalSize { get; protected set; } - - /// <summary> - /// The maximum work group size of compute shaders.<br/> - /// The values are hardware dependent and queried from OpenGL. - /// </summary> - public static Vector3i MaximumWorkGroupSize { get; protected set; } - - static ComputeProgram() - { - int x,y,z; - GL.GetInteger((GetIndexedPName)All.MaxComputeWorkGroupCount, 0, out x); - GL.GetInteger((GetIndexedPName)All.MaxComputeWorkGroupCount, 1, out y); - GL.GetInteger((GetIndexedPName)All.MaxComputeWorkGroupCount, 2, out z); - MaximumWorkGroupSize = new Vector3i(x,y,z); - } - - /// <summary> - /// Initializes a new instance of this compute shader.<br/> - /// Retrieves shader source filenames from ShaderSourceAttributes tagged to this type. - /// </summary> - protected ComputeProgram() - { - if (ShaderSourceAttribute.GetShaderSources(GetType()).Any(_ => _.Type != ShaderType.ComputeShader)) - throw new ApplicationException("Invalid ShaderType supplied to compute shader via ShaderSourceAttribute(s)."); - } - - public override void Link() - { - base.Link(); - // query the work group size - var sizes = new int[3]; - GL.GetProgram(Handle, (GetProgramParameterName)All.ComputeWorkGroupSize, sizes); - WorkGroupSize = new Vector3i(sizes[0], sizes[1], sizes[2]); - WorkGroupTotalSize = sizes[0] * sizes[1] * sizes[2]; - } - - /// <summary> - /// Splits a given number of work groups up to the three dimensions. - /// The number of work groups in any dimensions is kept less or equal to the supported maximum. - /// The resulting total number of work groups may be larger than the given number. - /// </summary> - public static Vector3i SplitWorkGroups(long groups) - { - //TODO: add missing limitations. there is not only the limitation on workgroup size in each dimension but also for the total number of work groups - if (groups > (long)MaximumWorkGroupSize.X * MaximumWorkGroupSize.Y * MaximumWorkGroupSize.Z) - throw new ArgumentOutOfRangeException("groups", groups, "Maximum number of work groups exceeded."); - double n = groups; - // determine number of layers needed - var z = (int)Math.Ceiling(n / ((long)MaximumWorkGroupSize.X * MaximumWorkGroupSize.Y)); - // determine the number of items per layer - n = Math.Ceiling(n / z); - // determine x and y to have the smallest number of items equal or larger to n - var y = (int)Math.Ceiling(n / MaximumWorkGroupSize.X); - var x = (int)Math.Ceiling(n / y); - return new Vector3i(x, y, z); - } - - /// <summary> - /// Dispatches the currently active compute shader. - /// </summary> - public static void Dispatch(int x, int y, int z) - { - GL.DispatchCompute(x, y, z); - } - - /// <summary> - /// Dispatches the currently active compute shader. - /// </summary> - /// <param name="workGroups">The number of work groups to be launched for each dimension.</param> - public static void Dispatch(Vector3i workGroups) - { - GL.DispatchCompute(workGroups.X, workGroups.Y, workGroups.Z); - } - - /// <summary> - /// Dispatches the currently active compute shader. - /// May split the number of work groups up to more dimensions. - /// </summary> - public static void Dispatch(int total) - { - Dispatch(SplitWorkGroups(total)); - } - - /// <summary> - /// Dispatches the currently active compute shader. - /// Uses the shaders work group size to launch as many work groups as necessary to reach the given number of invocations. - /// May also split the number of work groups up to more dimensions. - /// </summary> - public void DispatchInvocations(int invocations) - { - Dispatch((int)Math.Ceiling((float)invocations / WorkGroupTotalSize)); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Effect.cs b/ObjectTK/Shaders/Effect.cs deleted file mode 100644 index 921307a..0000000 --- a/ObjectTK/Shaders/Effect.cs +++ /dev/null @@ -1,156 +0,0 @@ -// -// Effect.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace ObjectTK.Shaders -{ - /// <summary> - /// Represents an effect file which may contain several sections, each containing the source of a shader.<br/> - /// Similar implementation to GLSW: http://prideout.net/blog/?p=11 - /// </summary> - public class Effect - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(Effect)); - - private static readonly Dictionary<string, Effect> Cache = new Dictionary<string, Effect>(); - - /// <summary> - /// Specifies the Path to the effects source file. - /// </summary> - public string Path { get; private set; } - - /// <summary> - /// Holds all sections contained within this effect. - /// </summary> - private readonly Dictionary<string, Section> _sections; - - /// <summary> - /// Represents a section within an effect file. - /// </summary> - public class Section - { - /// <summary> - /// Holds a reference to the effect which contains this section. - /// </summary> - public Effect Effect; - - /// <summary> - /// The shader key to this section. - /// </summary> - public string ShaderKey; - - /// <summary> - /// The source within this section. - /// </summary> - public string Source; - - /// <summary> - /// Specifies the first line number of this section within the effect file. - /// </summary> - public int FirstLineNumber; - } - - private Effect(string path) - { - Path = path; - _sections = new Dictionary<string, Section>(); - } - - /// <summary> - /// Retrieves the best matching section to the given shader key. - /// </summary> - /// <param name="shaderKey">The shader key to find the best match for.</param> - /// <returns>A section containing shader source.</returns> - public Section GetMatchingSection(string shaderKey) - { - Section closestMatch = null; - foreach (var section in _sections.Values) - { - // find longest matching section key - if (shaderKey.StartsWith(section.ShaderKey) && (closestMatch == null || section.ShaderKey.Length > closestMatch.ShaderKey.Length)) - { - closestMatch = section; - } - } - return closestMatch; - } - - /// <summary> - /// Retrieves the best matching section from the effect file. - /// </summary> - /// <param name="effectPath">Specifies the path to the effect file.</param> - /// <param name="shaderKey">The shader key to find the best match for.</param> - /// <returns>A section containing shader source.</returns> - public static Section GetSection(string effectPath, string shaderKey) - { - return LoadEffect(effectPath).GetMatchingSection(shaderKey); - } - - /// <summary> - /// Loads the the given effect file and parses its sections. - /// </summary> - /// <param name="path">Specifies the path to the effect file.</param> - /// <returns>A new Effect object containing the parsed content from the file.</returns> - public static Effect LoadEffect(string path) - { - // return cached effect if available - if (Cache.ContainsKey(path)) return Cache[path]; - // otherwise load the whole effect file - const string sectionSeparator = "--"; - try - { - using (var reader = new StreamReader(path)) - { - var effect = new Effect(path); - var source = new StringBuilder(); - Section section = null; - var lineNumber = 1; - while (!reader.EndOfStream) - { - // read the file line by line - var line = reader.ReadLine(); - if (line == null) break; - // count line number - lineNumber++; - // append code to current section until a section separator is reached - if (!line.StartsWith(sectionSeparator)) - { - source.AppendLine(line); - continue; - } - // write source to current section - if (section != null) section.Source = source.ToString(); - // start new section - section = new Section - { - Effect = effect, - ShaderKey = line.Substring(sectionSeparator.Length).Trim(), - FirstLineNumber = lineNumber - }; - effect._sections.Add(section.ShaderKey, section); - source.Clear(); - } - // make sure the last section is finished - if (section != null) section.Source = source.ToString(); - // cache the effect - Cache.Add(path, effect); - return effect; - } - } - catch (FileNotFoundException ex) - { - Logger?.Error("Effect source file not found.", ex); - throw; - } - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Program.cs b/ObjectTK/Shaders/Program.cs deleted file mode 100644 index 5dee7a7..0000000 --- a/ObjectTK/Shaders/Program.cs +++ /dev/null @@ -1,133 +0,0 @@ -// -// Program.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using ObjectTK.Exceptions; -using ObjectTK.Shaders.Variables; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders -{ - /// <summary> - /// Represents a program object. - /// </summary> - public class Program - : GLObject - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(Program)); - - /// <summary> - /// The name of this shader program. - /// </summary> - public string Name { get { return GetType().Name; } } - - private List<ProgramVariable> _variables; - - /// <summary> - /// Initializes a new program object. - /// </summary> - protected Program() - : base(GL.CreateProgram()) - { - Logger?.InfoFormat("Creating shader program: {0}", Name); - InitializeShaderVariables(); - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteProgram(Handle); - } - - private void InitializeShaderVariables() - { - const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public; - _variables = new List<ProgramVariable>(); - foreach (var property in GetType().GetProperties(flags).Where(_ => typeof(ProgramVariable).IsAssignableFrom(_.PropertyType))) - { - var instance = (ProgramVariable)Activator.CreateInstance(property.PropertyType, true); - instance.Initialize(this, property); - property.SetValue(this, instance, null); - _variables.Add(instance); - } - } - - /// <summary> - /// Activate the program. - /// </summary> - public void Use() - { - GL.UseProgram(Handle); - } - - /// <summary> - /// Attach shader object. - /// </summary> - /// <param name="shader">Specifies the shader object to attach.</param> - public void Attach(Shader shader) - { - GL.AttachShader(Handle, shader.Handle); - } - - /// <summary> - /// Detach shader object. - /// </summary> - /// <param name="shader">Specifies the shader object to detach.</param> - public void Detach(Shader shader) - { - GL.DetachShader(Handle, shader.Handle); - } - - /// <summary> - /// Link the program. - /// </summary> - public virtual void Link() - { - Logger?.DebugFormat("Linking program: {0}", Name); - GL.LinkProgram(Handle); - CheckLinkStatus(); - // call OnLink() on all ShaderVariables - _variables.ForEach(_ => _.OnLink()); - } - - /// <summary> - /// Assert that no link error occured. - /// </summary> - private void CheckLinkStatus() - { - // check link status - int linkStatus; - GL.GetProgram(Handle, GetProgramParameterName.LinkStatus, out linkStatus); - Logger?.DebugFormat("Link status: {0}", linkStatus); - // check program info log - var info = GL.GetProgramInfoLog(Handle); - if (!string.IsNullOrEmpty(info)) Logger?.InfoFormat("Link log:\n{0}", info); - // log message and throw exception on link error - if (linkStatus == 1) return; - var msg = string.Format("Error linking program: {0}", Name); - Logger?.Error(msg); - throw new ProgramLinkException(msg, info); - } - - /// <summary> - /// Throws an <see cref="ObjectNotBoundException"/> if this program is not the currently active one. - /// </summary> - public void AssertActive() - { -#if DEBUG - int activeHandle; - GL.GetInteger(GetPName.CurrentProgram, out activeHandle); - if (activeHandle != Handle) throw new ObjectNotBoundException("Program object is not currently active."); -#endif - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/ProgramFactory.cs b/ObjectTK/Shaders/ProgramFactory.cs deleted file mode 100644 index ab9c71a..0000000 --- a/ObjectTK/Shaders/ProgramFactory.cs +++ /dev/null @@ -1,163 +0,0 @@ -// -// ProgramFactory.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using ObjectTK.Exceptions; -using ObjectTK.Shaders.Sources; - -namespace ObjectTK.Shaders -{ - /// <summary> - /// Contains methods to automatically initialize program objects. - /// </summary> - public static class ProgramFactory - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(ProgramFactory)); - - /// <summary> - /// The base path used when looking for shader files.<br/> - /// Default is: Data/Shaders/ - /// </summary> - public static string BasePath { get; set; } - - /// <summary> - /// Specifies the default extension appended to effect names.<br/> - /// Default is: glsl - /// </summary> - public static string Extension { get; set; } - - static ProgramFactory() - { - BasePath = Path.Combine("Data", "Shaders"); - Extension = "glsl"; - } - - /// <summary> - /// Initializes a program object using the shader sources tagged to the type with <see cref="ShaderSourceAttribute"/>. - /// </summary> - /// <typeparam name="T">Specifies the program type to create.</typeparam> - /// <returns>A compiled and linked program.</returns> - public static T Create<T>() - where T : Program - { - // retrieve shader types and filenames from attributes - var shaders = ShaderSourceAttribute.GetShaderSources(typeof(T)); - if (shaders.Count == 0) throw new ObjectTKException("ShaderSourceAttribute(s) missing!"); - // create program instance - var program = (T)Activator.CreateInstance(typeof(T)); - try - { - // compile and attach all shaders - foreach (var attribute in shaders) - { - // create a new shader of the appropriate type - using (var shader = new Shader(attribute.Type)) - { - Logger?.DebugFormat("Compiling {0}: {1}", attribute.Type, attribute.EffectKey); - // load the source from effect(s) - var included = new List<Effect.Section>(); - var source = GetShaderSource(attribute.EffectKey, included); - // assign source filenames for proper information log output - shader.SourceFiles = included.Select(_ => _.Effect.Path).ToList(); - // compile shader source - shader.CompileSource(source); - // attach shader to the program - program.Attach(shader); - } - } - // link and return the program - program.Link(); - } - catch - { - program.Dispose(); - throw; - } - return program; - } - - /// <summary> - /// Load shader source file(s).<br/> - /// Supports multiple source files via "#include xx" directives and corrects the line numbering by using the glsl standard #line directive. - /// </summary> - /// <param name="effectKey">Specifies the effect key to load.</param> - /// <param name="included">Holds the effectKeys of all shaders already loaded to prevent multiple inclusions.</param> - /// <returns>The fully assembled shader source.</returns> - private static string GetShaderSource(string effectKey, List<Effect.Section> included = null) - { - if (included == null) included = new List<Effect.Section>(); - // retrieve effect section - Effect.Section section; - try - { - var directory = Path.GetDirectoryName(effectKey); - var filename = Path.GetFileName(effectKey); - var separator = filename.IndexOf('.'); - var effectPath = Path.ChangeExtension(Path.Combine(BasePath, directory, filename.Substring(0, separator)), Extension); - var shaderKey = filename.Substring(separator + 1); - section = Effect.GetSection(effectPath, shaderKey); - } - catch (Exception ex) - { - throw new Exception(string.Format("Invalid effect key: {0}", effectKey), ex); - } - if (section == null) throw new Exception(string.Format("Shader source not found: {0}", effectKey)); - // check for multiple includes of the same section - if (included.Contains(section)) - { - Logger?.WarnFormat("Shader already included: {0}", effectKey); - return ""; - } - included.Add(section); - // parse source for #include directives and insert proper #line annotations - using (var reader = new StringReader(section.Source)) - { - var source = new StringBuilder(); - var lineNumber = section.FirstLineNumber; - var fileNumber = included.Count-1; - var fixLine = true; - while (true) - { - var line = reader.ReadLine(); - if (line == null) break; - // check if it is an include statement - const string includeKeyword = "#include"; - const string versionKeyword = "#version"; - if (!line.StartsWith(includeKeyword)) - { - // add correct line number offset to the corresponding section within the effect file - if ((fixLine)&& !line.StartsWith(versionKeyword) ) - { - source.AppendLine(string.Format("#line {0} {1}", lineNumber, fileNumber)); - fixLine = false; - } - source.AppendLine(line); - } - else - { - // parse the included filename - var includedEffectKey = line.Remove(0, includeKeyword.Length).Trim(); - // make the include path relative to the current file - includedEffectKey = Path.Combine(Path.GetDirectoryName(effectKey) ?? "", includedEffectKey); - // replace current line with the source of the included section - source.Append(GetShaderSource(includedEffectKey, included)); - // remember to fix the line numbering on the next line - fixLine = true; - } - lineNumber++; - } - return source.ToString(); - } - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Shader.cs b/ObjectTK/Shaders/Shader.cs deleted file mode 100644 index 2e5daaa..0000000 --- a/ObjectTK/Shaders/Shader.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// Shader.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Collections.Generic; -using System.Text.RegularExpressions; -using ObjectTK.Exceptions; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders -{ - /// <summary> - /// Represents a shader object. - /// </summary> - public class Shader - : GLObject - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(Shader)); - - /// <summary> - /// Specifies the type of this shader. - /// </summary> - public readonly ShaderType Type; - - /// <summary> - /// Specifies a list of source filenames which are used to improve readability of the the information log in case of an error. - /// </summary> - public List<string> SourceFiles; - - /// <summary> - /// Used to match and replace the source filenames into the information log. - /// </summary> - private static readonly Regex Regenechse = new Regex(@"^ERROR: (\d+):", RegexOptions.Multiline); - - /// <summary> - /// Initializes a new shader object of the given type. - /// </summary> - /// <param name="type"></param> - public Shader(ShaderType type) - : base(GL.CreateShader(type)) - { - Type = type; - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteShader(Handle); - } - - /// <summary> - /// Loads the given source file and compiles the shader. - /// </summary> - public void CompileSource(string source) - { - GL.ShaderSource(Handle, source); - GL.CompileShader(Handle); - CheckCompileStatus(); - } - - /// <summary> - /// Assert that no compile error occured. - /// </summary> - private void CheckCompileStatus() - { - // check compile status - int compileStatus; - GL.GetShader(Handle, ShaderParameter.CompileStatus, out compileStatus); - Logger?.DebugFormat("Compile status: {0}", compileStatus); - // check shader info log - var info = GL.GetShaderInfoLog(Handle); - if (SourceFiles != null) info = Regenechse.Replace(info, GetSource); - if (!string.IsNullOrEmpty(info)) Logger?.InfoFormat("Compile log:\n{0}", info); - // log message and throw exception on compile error - if (compileStatus == 1) return; - const string msg = "Error compiling shader."; - Logger?.Error(msg); - throw new ShaderCompileException(msg, info); - } - - private string GetSource(Match match) - { - var index = int.Parse(match.Groups[1].Value); - return index < SourceFiles.Count ? string.Format("ERROR: {0}:", SourceFiles[index]) : match.ToString(); - } - } -} diff --git a/ObjectTK/Shaders/Sources/ComputeShaderSourceAttribute.cs b/ObjectTK/Shaders/Sources/ComputeShaderSourceAttribute.cs deleted file mode 100644 index bb8a8ca..0000000 --- a/ObjectTK/Shaders/Sources/ComputeShaderSourceAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// ComputeShaderSourceAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Sources -{ - /// <summary> - /// Specifies the source of a compute shader. - /// </summary> - public class ComputeShaderSourceAttribute - : ShaderSourceAttribute - { - /// <summary> - /// Initializes a new instance of the ComputeShaderSourceAttribute. - /// </summary> - /// <param name="effectKey">Specifies the effect key for this shader.</param> - public ComputeShaderSourceAttribute(string effectKey) - : base(ShaderType.ComputeShader, effectKey) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Sources/FragmentShaderSourceAttribute.cs b/ObjectTK/Shaders/Sources/FragmentShaderSourceAttribute.cs deleted file mode 100644 index 50a0a62..0000000 --- a/ObjectTK/Shaders/Sources/FragmentShaderSourceAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// FragmentShaderSourceAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Sources -{ - /// <summary> - /// Specifies the source of a fragment shader. - /// </summary> - public class FragmentShaderSourceAttribute - : ShaderSourceAttribute - { - /// <summary> - /// Initializes a new instance of the FragmentShaderSourceAttribute. - /// </summary> - /// <param name="effectKey">Specifies the effect key for this shader.</param> - public FragmentShaderSourceAttribute(string effectKey) - : base(ShaderType.FragmentShader, effectKey) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Sources/GeometryShaderSourceAttribute.cs b/ObjectTK/Shaders/Sources/GeometryShaderSourceAttribute.cs deleted file mode 100644 index ca555ae..0000000 --- a/ObjectTK/Shaders/Sources/GeometryShaderSourceAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// GeometryShaderSourceAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Sources -{ - /// <summary> - /// Specifies the source of a geometry shader. - /// </summary> - public class GeometryShaderSourceAttribute - : ShaderSourceAttribute - { - /// <summary> - /// Initializes a new instance of the GeometryShaderSourceAttribute. - /// </summary> - /// <param name="effectKey">Specifies the effect key for this shader.</param> - public GeometryShaderSourceAttribute(string effectKey) - : base(ShaderType.GeometryShader, effectKey) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Sources/ShaderSourceAttribute.cs b/ObjectTK/Shaders/Sources/ShaderSourceAttribute.cs deleted file mode 100644 index 6fb77d4..0000000 --- a/ObjectTK/Shaders/Sources/ShaderSourceAttribute.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// ShaderSourceAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Collections.Generic; -using System.Linq; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Sources -{ - /// <summary> - /// Specifies a source file which contains a single shader of predefined type. - /// </summary> - [AttributeUsage(AttributeTargets.Class)] - public class ShaderSourceAttribute - : Attribute - { - /// <summary> - /// Specifies the type of shader. - /// </summary> - public ShaderType Type { get; private set; } - - /// <summary> - /// Specifies the effect key for this shader.<br/> - /// Example: Path/to/file/CoolShader.Fragment.Diffuse - /// </summary> - public string EffectKey { get; private set; } - - /// <summary> - /// Initializes a new instance of the ShaderSourceAttribute. - /// </summary> - /// <param name="type">Specifies the type of the shader.</param> - /// <param name="effectKey">Specifies the effect key for this shader.</param> - protected ShaderSourceAttribute(ShaderType type, string effectKey) - { - Type = type; - EffectKey = effectKey; - } - - /// <summary> - /// Retrieves all shader sources from attributes tagged to the given program type. - /// </summary> - /// <param name="programType">Specifies the type of the program of which the shader sources are to be found.</param> - /// <returns>A mapping of ShaderType and source path.</returns> - public static List<ShaderSourceAttribute> GetShaderSources(Type programType) - { - return programType.GetCustomAttributes<ShaderSourceAttribute>(true).ToList(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Sources/TessControlShaderSourceAttribute.cs b/ObjectTK/Shaders/Sources/TessControlShaderSourceAttribute.cs deleted file mode 100644 index 0e2b165..0000000 --- a/ObjectTK/Shaders/Sources/TessControlShaderSourceAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// TessControlShaderSourceAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Sources -{ - /// <summary> - /// Specifies the source of a vertex shader. - /// </summary> - public class TessControlShaderSourceAttribute - : ShaderSourceAttribute - { - /// <summary> - /// Initializes a new instance of the TessControlShaderSourceAttribute. - /// </summary> - /// <param name="effectKey">Specifies the effect key for this shader.</param> - public TessControlShaderSourceAttribute(string effectKey) - : base(ShaderType.TessControlShader, effectKey) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Sources/TessEvaluationShaderSourceAttribute.cs b/ObjectTK/Shaders/Sources/TessEvaluationShaderSourceAttribute.cs deleted file mode 100644 index fe00f44..0000000 --- a/ObjectTK/Shaders/Sources/TessEvaluationShaderSourceAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// TessEvaluationShaderSourceAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Sources -{ - /// <summary> - /// Specifies the source of a vertex shader. - /// </summary> - public class TessEvaluationShaderSourceAttribute - : ShaderSourceAttribute - { - /// <summary> - /// Initializes a new instance of the TessEvaluationShaderSourceAttribute. - /// </summary> - /// <param name="effectKey">Specifies the effect key for this shader.</param> - public TessEvaluationShaderSourceAttribute(string effectKey) - : base(ShaderType.TessEvaluationShader, effectKey) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Sources/VertexShaderSourceAttribute.cs b/ObjectTK/Shaders/Sources/VertexShaderSourceAttribute.cs deleted file mode 100644 index eb56e04..0000000 --- a/ObjectTK/Shaders/Sources/VertexShaderSourceAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// VertexShaderSourceAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Sources -{ - /// <summary> - /// Specifies the source of a vertex shader. - /// </summary> - public class VertexShaderSourceAttribute - : ShaderSourceAttribute - { - /// <summary> - /// Initializes a new instance of the VertexShaderSourceAttribute. - /// </summary> - /// <param name="effectKey">Specifies the effect key for this shader.</param> - public VertexShaderSourceAttribute(string effectKey) - : base(ShaderType.VertexShader, effectKey) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/TransformProgram.cs b/ObjectTK/Shaders/TransformProgram.cs deleted file mode 100644 index ceda9bb..0000000 --- a/ObjectTK/Shaders/TransformProgram.cs +++ /dev/null @@ -1,80 +0,0 @@ -// -// TransformProgram.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Linq; -using ObjectTK.Exceptions; -using ObjectTK.Shaders.Variables; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders -{ - /// <summary> - /// Represents a program object which utilizes transform feedback. - /// </summary> - public class TransformProgram - : Program - { - /// <summary> - /// Represents "gl_NextBuffer" when specifying feedback varyings and using advanced interleaving. - /// </summary> - public static TransformOut NextBuffer = new TransformOut("gl_NextBuffer"); - - /// <summary> - /// Represents "gl_SkipComponents1" when specifying feedback varyings and using advanced interleaving. - /// </summary> - public static TransformOut SkipComponents1 = new TransformOut("gl_SkipComponents1"); - - /// <summary> - /// Represents "gl_SkipComponents2" when specifying feedback varyings and using advanced interleaving. - /// </summary> - public static TransformOut SkipComponents2 = new TransformOut("gl_SkipComponents2"); - - /// <summary> - /// Represents "gl_SkipComponents3" when specifying feedback varyings and using advanced interleaving. - /// </summary> - public static TransformOut SkipComponents3 = new TransformOut("gl_SkipComponents3"); - - /// <summary> - /// Represents "gl_SkipComponents4" when specifying feedback varyings and using advanced interleaving. - /// </summary> - public static TransformOut SkipComponents4 = new TransformOut("gl_SkipComponents4"); - - /// <summary> - /// Holds a list of all special keywords which can only be used with advanced interleaving. - /// </summary> - private static readonly TransformOut[] SpecialOuts = { NextBuffer, SkipComponents1, SkipComponents2, SkipComponents3, SkipComponents4 }; - - /// <summary> - /// Specify values to record in transform feedback buffers. - /// </summary> - /// <remarks> - /// Transform feedback varyings must be specified before linking the program. Either specify them in the constructor of the program - /// or call <see cref="Program.Link"/> again after a call to this method.<br/> - /// To specify the keywords introduced with advanced interleaving "gl_NextBuffer" and "gl_SkipComponents#" - /// use the TransformOut dummy-instances <see cref="NextBuffer"/> and <see cref="SkipComponents1"/>, etc. - /// </remarks> - /// <param name="bufferMode">Identifies the mode used to capture the varying variables when transform feedback is active. bufferMode must be InterleavedAttribs or SeparateAttribs.</param> - /// <param name="feedbackVaryings">An array of TransformOut objects specifying the varying variables to use for transform feedback.</param> - public void FeedbackVaryings(TransformFeedbackMode bufferMode, params TransformOut[] feedbackVaryings) - { - //TODO: find out if the varyings buffer binding indices can be queried from OpenGL - var index = 0; - foreach (var output in feedbackVaryings) - { - if (bufferMode == TransformFeedbackMode.SeparateAttribs && SpecialOuts.Contains(output)) - throw new ObjectTKException("Advanced interleaving features can not be used with separate mode."); - // set the outputs buffer binding index - output.Index = index; - // increase the index if all outputs get routed to a separate bindind or if the gl_NextBuffer keyword is found - if (bufferMode == TransformFeedbackMode.SeparateAttribs || output == NextBuffer) index++; - } - GL.TransformFeedbackVaryings(Handle, feedbackVaryings.Length, feedbackVaryings.Select(_ => _.Name).ToArray(), bufferMode); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/BufferBinding.cs b/ObjectTK/Shaders/Variables/BufferBinding.cs deleted file mode 100644 index f2b8cac..0000000 --- a/ObjectTK/Shaders/Variables/BufferBinding.cs +++ /dev/null @@ -1,98 +0,0 @@ -// -// BufferBinding.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using ObjectTK.Buffers; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a shader buffer binding point identified by its resource index. - /// </summary> - public abstract class BufferBinding - : ProgramVariable - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(BufferBinding)); - - /// <summary> - /// The target to use when binding to this point. - /// </summary> - public readonly BufferRangeTarget BindingTarget; - - /// <summary> - /// The resource index of this binding point. - /// </summary> - public int Index { get; private set; } - - /// <summary> - /// Current binding point - /// </summary> - protected int Binding; - - private readonly ProgramInterface _programInterface; - - internal BufferBinding(BufferRangeTarget bindingTarget, ProgramInterface programInterface) - { - BindingTarget = bindingTarget; - _programInterface = programInterface; - } - - internal override void OnLink() - { - Index = GL.GetProgramResourceIndex(ProgramHandle, _programInterface, Name); - Active = Index > -1; - if (!Active) Logger?.WarnFormat("Binding block not found or not active: {0}", Name); - Binding = -1; - } - - /// <summary> - /// Assigns a binding point. - /// </summary> - public virtual void ChangeBinding(int binding) - { - Binding = binding; - } - - /// <summary> - /// Binds a buffer to this binding point. - /// </summary> - /// <typeparam name="T">The type of the container elements.</typeparam> - /// <param name="buffer">The buffer to bind.</param> - public void BindBuffer<T>(Buffer<T> buffer) - where T : struct - { - if (!Active) return; - GL.BindBufferBase(BindingTarget, Binding, buffer.Handle); - } - - /// <summary> - /// Binds a buffer to this binding point. - /// </summary> - /// <typeparam name="T">The type of the container elements.</typeparam> - /// <param name="buffer">The buffer to bind.</param> - /// <param name="offset">The starting offset in basic machine units into the buffer object buffer. </param> - /// <param name="size">The amount of data in machine units that can be read from the buffer object while used as an indexed target. </param> - public void BindBuffer<T>(Buffer<T> buffer, int offset, int size) - where T : struct - { - if (!Active) return; - GL.BindBufferRange(BindingTarget, Binding, buffer.Handle, (IntPtr)offset, (IntPtr)size); - } - - /// <summary> - /// Unbinds any buffer from this binding point. - /// </summary> - public void Unbind() - { - if (!Active) return; - GL.BindBufferBase(BindingTarget, Binding, 0); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/FragData.cs b/ObjectTK/Shaders/Variables/FragData.cs deleted file mode 100644 index 7ce8484..0000000 --- a/ObjectTK/Shaders/Variables/FragData.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// FragData.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a fragment shader output.<br/> - /// TODO: implement methods to bind output to a specific attachment - /// see glBindFragDataLocation, glDrawBuffers and http://stackoverflow.com/questions/1733838/fragment-shaders-output-variables - /// </summary> - public sealed class FragData - : ProgramVariable - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(FragData)); - - /// <summary> - /// The location of the output. - /// </summary> - public int Location { get; private set; } - - internal FragData() - { - } - - internal override void OnLink() - { - //TODO: find out what GL.GetFragDataIndex(); does - Location = GL.GetFragDataLocation(ProgramHandle, Name); - if (Location == -1) Logger?.WarnFormat("Output variable not found or not active: {0}", Name); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/ImageUniform.cs b/ObjectTK/Shaders/Variables/ImageUniform.cs deleted file mode 100644 index 907fcbe..0000000 --- a/ObjectTK/Shaders/Variables/ImageUniform.cs +++ /dev/null @@ -1,138 +0,0 @@ -// -// ImageUniform.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using ObjectTK.Textures; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents an image uniform. - /// </summary> - public sealed class ImageUniform - : Uniform<int> - { - internal ImageUniform() - : base(GL.Uniform1) - { - } - - /// <summary> - /// Binds the given buffer texture to an image unit. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="textureBuffer">The buffer texture to bind.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - public void Bind(int imageUnit, TextureBuffer textureBuffer, TextureAccess access) - { - Bind(imageUnit, textureBuffer, 0, false, 0, access); - } - - /// <summary> - /// Binds a single face of the given texture level to an image unit.<br/> - /// Calculates the index of the layer-face as 6 * arrayLayer + face. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="texture">The texture to bind.</param> - /// <param name="level">The mipmap level to bind.</param> - /// <param name="arrayLayer">The layer of the texture to bind.</param> - /// <param name="face">The cube map face to bind.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - public void Bind(int imageUnit, TextureCubemapArray texture, int level, int arrayLayer, int face, TextureAccess access) - { - // note: the layer parameter indexes the layer-faces, hence the multiplication of the array-layer by 6 - Bind(imageUnit, texture, level, false, 6 * arrayLayer + face, access); - } - - /// <summary> - /// Binds a single face of the given texture level to an image unit. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="texture">The texture to bind.</param> - /// <param name="level">The mipmap level to bind.</param> - /// <param name="face">The cube map face to bind.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - public void Bind(int imageUnit, TextureCubemap texture, int level, int face, TextureAccess access) - { - Bind(imageUnit, texture, level, false, face, access); - } - - /// <summary> - /// Binds a single layer of the given texture level to an image unit.<br/> - /// Note that for cube maps and cube map arrays the <paramref name="layer"/> parameter actually indexes the layer-faces.<br/> - /// Thus for cube maps the layer parameter equals the face to be bound.<br/> - /// For cube map arrays the layer parameter can be calculated as 6 * arrayLayer + face, which is done automatically when using - /// the corresponding overload <see cref="Bind(int,TextureCubemapArray,int,int,int,OpenTK.Graphics.OpenGL.TextureAccess)"/>. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="texture">The texture to bind.</param> - /// <param name="level">The mipmap level to bind.</param> - /// <param name="layer">The layer of the texture to bind.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - public void Bind(int imageUnit, LayeredTexture texture, int level, int layer, TextureAccess access) - { - Bind(imageUnit, texture, level, false, layer, access); - } - - /// <summary> - /// Binds an entire level of the given texture to an image unit.<br/> - /// The mipmap level defaults to zero. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="texture">The texture to bind.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - public void Bind(int imageUnit, Texture texture, TextureAccess access) - { - Bind(imageUnit, texture, 0, true, 0, access); - } - - /// <summary> - /// Binds an entire level of the given texture to an image unit. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="texture">The texture to bind.</param> - /// <param name="level">The mipmap level to bind.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - public void Bind(int imageUnit, Texture texture, int level, TextureAccess access) - { - Bind(imageUnit, texture, level, true, 0, access); - } - - /// <summary> - /// Binds a single level of a texture to an image unit. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="texture">The texture to bind.</param> - /// <param name="level">The mipmap level to bind.</param> - /// <param name="layered">Specifies whether a layered texture binding is to be established.</param> - /// <param name="layer">If <paramref name="layered"/> is false, specifies the layer of the texture to be bound, ignored otherwise.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - public void Bind(int imageUnit, Texture texture, int level, bool layered, int layer, TextureAccess access) - { - texture.AssertLevel(level); - Bind(imageUnit, texture.Handle, level, layered, layer, access, texture.InternalFormat); - } - - /// <summary> - /// Binds a single level of a texture to an image unit. - /// </summary> - /// <param name="imageUnit">The image unit to use.</param> - /// <param name="textureHandle">The handle of the texture.</param> - /// <param name="level">The mipmap level to bind.</param> - /// <param name="layered">Specifies whether a layered texture binding is to be established.</param> - /// <param name="layer">If <paramref name="layered"/> is false, specifies the layer of the texture to be bound, ignored otherwise.</param> - /// <param name="access">Specifies the type of access allowed on the image.</param> - /// <param name="format">Specifies the format that the elements of the texture will be treated as.</param> - public void Bind(int imageUnit, int textureHandle, int level, bool layered, int layer, TextureAccess access, SizedInternalFormat format) - { - Set(imageUnit); - GL.BindImageTexture(imageUnit, textureHandle, level, layered, layer, access, format); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/ProgramVariable.cs b/ObjectTK/Shaders/Variables/ProgramVariable.cs deleted file mode 100644 index 4bba1ed..0000000 --- a/ObjectTK/Shaders/Variables/ProgramVariable.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// ProgramVariable.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Reflection; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a shader variable identified by its name and the corresponding program handle. - /// </summary> - public abstract class ProgramVariable - { - /// <summary> - /// The handle of the program to which this variable relates. - /// </summary> - protected Program Program { get; private set; } - - /// <summary> - /// The handle of the program to which this variable relates. - /// </summary> - public int ProgramHandle { get { return Program.Handle; } } - - /// <summary> - /// The name of this shader variable. - /// </summary> - public string Name { get; protected set; } - - /// <summary> - /// Specifies whether this variable is active.<br/> - /// Unused variables are generally removed by OpenGL and cause them to be inactive. - /// </summary> - public bool Active { get; protected set; } - - /// <summary> - /// Initializes this instance using the given Program and PropertyInfo. - /// </summary> - internal virtual void Initialize(Program program, PropertyInfo property) - { - Program = program; - Name = property.Name; - } - - /// <summary> - /// When overridden in a derived class, handles initialization which must occur after the program object is linked. - /// </summary> - internal virtual void OnLink() { } - - public override string ToString() - { - return string.Format("{0}.{1}", Program.Name, Name); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/ShaderStorage.cs b/ObjectTK/Shaders/Variables/ShaderStorage.cs deleted file mode 100644 index efc166a..0000000 --- a/ObjectTK/Shaders/Variables/ShaderStorage.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// ShaderStorage.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a shader storage buffer object (SSBO) binding. - /// </summary> - public sealed class ShaderStorage - : BufferBinding - { - internal ShaderStorage() - : base(BufferRangeTarget.ShaderStorageBuffer, ProgramInterface.ShaderStorageBlock) - { - } - - internal override void OnLink() - { - base.OnLink(); - //TODO: find out if the current binding point can be queried, like it can be for uniform blocks - // set the binding point to the blocks index - if (Active) ChangeBinding(Index); - } - - /// <summary> - /// Assigns a binding point to this shader storage block. - /// </summary> - /// <param name="binding"></param> - public override void ChangeBinding(int binding) - { - base.ChangeBinding(binding); - GL.ShaderStorageBlockBinding(ProgramHandle, Index, binding); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/TextureUniform.cs b/ObjectTK/Shaders/Variables/TextureUniform.cs deleted file mode 100644 index c8b0782..0000000 --- a/ObjectTK/Shaders/Variables/TextureUniform.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -// TextureUniform.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using ObjectTK.Textures; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a typed texture uniform. Allows only textures of the given type to be bound. - /// </summary> - public class TextureUniform<T> - : Uniform<int> - where T : Texture - { - internal TextureUniform() - : base(GL.Uniform1) - { - } - - /// <summary> - /// Sets this uniform to sample from the given texture unit.<br/> - /// Calls to <see cref="Set(TextureUnit)"/> are equivalent to <see cref="Uniform{T}.Set"/> - /// with the corresponding integer, it just adds readability. - /// </summary> - /// <param name="unit">The texture unit to sample from.</param> - public void Set(TextureUnit unit) - { - Set((int)unit - (int)TextureUnit.Texture0); - } - - /// <summary> - /// Binds a texture to the given texture unit and sets the corresponding uniform to the respective number to access it. - /// </summary> - /// <param name="unit">The texture unit to bind to.</param> - /// <param name="texture">The texture to bind.</param> - public void BindTexture(TextureUnit unit, T texture) - { - Set(unit); - texture.Bind(unit); - } - } - - /// <summary> - /// Represents a texture uniform. Allows any texture type to be bound. - /// </summary> - public sealed class TextureUniform : TextureUniform<Texture> { } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/TransformOut.cs b/ObjectTK/Shaders/Variables/TransformOut.cs deleted file mode 100644 index 0d41be1..0000000 --- a/ObjectTK/Shaders/Variables/TransformOut.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// TransformOut.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a transform feedback output varying. - /// </summary> - public sealed class TransformOut - : ProgramVariable - { - /// <summary> - /// Specifies the transform feedback buffer binding index of this output. - /// </summary> - public int Index { get; internal set; } - - internal TransformOut() - { - Index = -1; - Active = false; - } - - /// <summary> - /// Initializes a dummy instance of TransformOut used for the keywords introduced with advanced interleaving. - /// </summary> - internal TransformOut(string name) - { - Name = name; - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/Uniform.cs b/ObjectTK/Shaders/Variables/Uniform.cs deleted file mode 100644 index 6723b9b..0000000 --- a/ObjectTK/Shaders/Variables/Uniform.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// Uniform.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a uniform. - /// </summary> - /// <typeparam name="T">The type of the uniform.</typeparam> - public class Uniform<T> - : ProgramVariable - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(Uniform<T>)); - - /// <summary> - /// The location of the uniform within the shader program. - /// </summary> - public int Location { get; private set; } - - /// <summary> - /// Action used to set the uniform.<br/> - /// Inputs are the uniforms location and the value to set. - /// </summary> - private readonly Action<int, T> _setter; - - /// <summary> - /// The current value of the uniform. - /// </summary> - private T _value; - - /// <summary> - /// Gets or sets the current value of the shader uniform. - /// </summary> - public T Value - { - get - { - return _value; - } - set - { - Set(value); - } - } - - internal Uniform() - : this(UniformSetter.Get<T>()) - { - } - - public Uniform(Action<int, T> setter) - { - if (setter == null) throw new ArgumentNullException("setter"); - _setter = setter; - } - - internal override void OnLink() - { - Location = GL.GetUniformLocation(ProgramHandle, Name); - Active = Location > -1; - if (!Active) Logger?.WarnFormat("Uniform not found or not active: {0}", Name); - } - - /// <summary> - /// Sets the given value to the program uniform.<br/> - /// Must be called on an active program, i.e. after <see cref="Program"/>.<see cref="Program.Use()"/>. - /// </summary> - /// <param name="value">The value to set.</param> - public void Set(T value) - { - Program.AssertActive(); - _value = value; - if (Active) _setter(Location, value); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/UniformBuffer.cs b/ObjectTK/Shaders/Variables/UniformBuffer.cs deleted file mode 100644 index 68acffe..0000000 --- a/ObjectTK/Shaders/Variables/UniformBuffer.cs +++ /dev/null @@ -1,68 +0,0 @@ -// -// UniformBuffer.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a uniform buffer object (UBO) binding. - /// </summary> - public sealed class UniformBuffer - : BufferBinding - { - internal UniformBuffer() - : base(BufferRangeTarget.UniformBuffer, ProgramInterface.UniformBlock) - { - } - - internal override void OnLink() - { - base.OnLink(); - // retrieve the default binding point - if (Active) GL.GetActiveUniformBlock(ProgramHandle, Index, ActiveUniformBlockParameter.UniformBlockBinding, out Binding); - } - - /// <summary> - /// Assigns a binding point to this uniform block. - /// </summary> - /// <param name="binding">The binding point to assign.</param> - public override void ChangeBinding(int binding) - { - base.ChangeBinding(binding); - if (!Active) return; - GL.UniformBlockBinding(ProgramHandle, Index, binding); - } - - /// <summary> - /// Retrieves the total size of the uniform block. - /// </summary> - /// <returns>The total size of the uniform block.</returns> - public int GetBlockSize() - { - int size; - GL.GetActiveUniformBlock(ProgramHandle, Index, ActiveUniformBlockParameter.UniformBlockDataSize, out size); - return size; - } - - /// <summary> - /// Retrieves the offsets of the uniforms within the block to the start of the block. - /// </summary> - /// <param name="offsets">The offsets of the uniforms within the block.</param> - public void GetBlockOffsets(out int[] offsets) - { - int uniforms; - GL.GetActiveUniformBlock(ProgramHandle, Index, ActiveUniformBlockParameter.UniformBlockActiveUniforms, out uniforms); - var indices = new int[uniforms]; - GL.GetActiveUniformBlock(ProgramHandle, Index, ActiveUniformBlockParameter.UniformBlockActiveUniformIndices, indices); - offsets = new int[uniforms]; - GL.GetActiveUniforms(ProgramHandle, uniforms, indices, ActiveUniformParameter.UniformOffset, offsets); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/UniformSetter.cs b/ObjectTK/Shaders/Variables/UniformSetter.cs deleted file mode 100644 index 52661cf..0000000 --- a/ObjectTK/Shaders/Variables/UniformSetter.cs +++ /dev/null @@ -1,80 +0,0 @@ -// -// UniformSetter.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using ObjectTK.Exceptions; -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - internal abstract class UniformSetter - { - protected abstract Type MappedType { get; } - - private class Map<T> - : UniformSetter - { - protected override Type MappedType { get { return typeof(T); } } - - public readonly Action<int, T> Setter; - - public Map(Action<int, T> setter) - { - Setter = setter; - } - } - - private UniformSetter() { } - - private static readonly List<UniformSetter> Setters = new List<UniformSetter>(); - - static UniformSetter() - { - Setters = new List<UniformSetter> - { - new Map<bool>((_,value) => GL.Uniform1(_, value ? 1 : 0)), - new Map<int>(GL.Uniform1), - new Map<uint>(GL.Uniform1), - new Map<float>(GL.Uniform1), - new Map<double>(GL.Uniform1), - new Map<Half>((_, half) => GL.Uniform1(_, half)), - new Map<Color>((_, color) => GL.Uniform4(_, color)), - new Map<Vector2>(GL.Uniform2), - new Map<Vector3>(GL.Uniform3), - new Map<Vector4>(GL.Uniform4), - new Map<Vector2d>((_, vector) => GL.Uniform2(_, vector.X, vector.Y)), - new Map<Vector2h>((_, vector) => GL.Uniform2(_, vector.X, vector.Y)), - new Map<Vector3d>((_, vector) => GL.Uniform3(_, vector.X, vector.Y, vector.Z)), - new Map<Vector3h>((_, vector) => GL.Uniform3(_, vector.X, vector.Y, vector.Z)), - new Map<Vector4d>((_, vector) => GL.Uniform4(_, vector.X, vector.Y, vector.Z, vector.W)), - new Map<Vector4h>((_, vector) => GL.Uniform4(_, vector.X, vector.Y, vector.Z, vector.W)), - new Map<Matrix2>((_, matrix) => GL.UniformMatrix2(_, false, ref matrix)), - new Map<Matrix3>((_, matrix) => GL.UniformMatrix3(_, false, ref matrix)), - new Map<Matrix4>((_, matrix) => GL.UniformMatrix4(_, false, ref matrix)), - new Map<Matrix2x3>((_, matrix) => GL.UniformMatrix2x3(_, false, ref matrix)), - new Map<Matrix2x4>((_, matrix) => GL.UniformMatrix2x4(_, false, ref matrix)), - new Map<Matrix3x2>((_, matrix) => GL.UniformMatrix3x2(_, false, ref matrix)), - new Map<Matrix3x4>((_, matrix) => GL.UniformMatrix3x4(_, false, ref matrix)), - new Map<Matrix4x2>((_, matrix) => GL.UniformMatrix4x2(_, false, ref matrix)), - new Map<Matrix4x3>((_, matrix) => GL.UniformMatrix4x3(_, false, ref matrix)) - }; - } - - public static Action<int, T> Get<T>() - { - var setter = Setters.FirstOrDefault(_ => _.MappedType == typeof(T)); - if (setter == null) throw new UniformTypeNotSupportedException(typeof(T)); - return ((Map<T>)setter).Setter; - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/VertexAttrib.cs b/ObjectTK/Shaders/Variables/VertexAttrib.cs deleted file mode 100644 index e40ed5c..0000000 --- a/ObjectTK/Shaders/Variables/VertexAttrib.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// VertexAttrib.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System.Linq; -using System.Reflection; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Represents a vertex attribute. - /// </summary> - public sealed class VertexAttrib - : ProgramVariable - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(VertexAttrib)); - - /// <summary> - /// The vertex attributes location within the shader. - /// </summary> - public int Index { get; private set; } - - /// <summary> - /// The number components to read. - /// </summary> - public int Components { get; private set; } - - /// <summary> - /// The type of each component. - /// </summary> - public VertexAttribPointerType Type { get; private set; } - - /// <summary> - /// Specifies whether the components should be normalized. - /// </summary> - public bool Normalized { get; private set; } - - internal VertexAttrib() - { - } - - internal override void Initialize(Program program, PropertyInfo property) - { - base.Initialize(program, property); - var attribute = property.GetCustomAttributes<VertexAttribAttribute>(false).FirstOrDefault() ?? new VertexAttribAttribute(); - Components = attribute.Components; - Type = attribute.Type; - Normalized = attribute.Normalized; - if (attribute.Index > 0) BindAttribLocation(attribute.Index); - } - - public void BindAttribLocation(int index) - { - Index = index; - GL.BindAttribLocation(ProgramHandle, index, Name); - } - - internal override void OnLink() - { - Index = GL.GetAttribLocation(ProgramHandle, Name); - Active = Index > -1; - if (!Active) Logger?.WarnFormat("Vertex attribute not found or not active: {0}", Name); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Shaders/Variables/VertexAttribAttribute.cs b/ObjectTK/Shaders/Variables/VertexAttribAttribute.cs deleted file mode 100644 index bd891f8..0000000 --- a/ObjectTK/Shaders/Variables/VertexAttribAttribute.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -// VertexAttribAttribute.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Shaders.Variables -{ - /// <summary> - /// Defines default values when binding buffers to the attributed <see cref="VertexAttrib"/>. - /// </summary> - [AttributeUsage(AttributeTargets.Property)] - public class VertexAttribAttribute - : Attribute - { - /// <summary> - /// The number components to read.<br/> - /// Defaults to 4. - /// </summary> - public int Components { get; protected set; } - - /// <summary> - /// The type of each component.<br/> - /// Defaults to Float. - /// </summary> - public VertexAttribPointerType Type { get; protected set; } - - /// <summary> - /// Specifies whether the components should be normalized.<br/> - /// Defaults to false. - /// </summary> - public bool Normalized { get; protected set; } - - /// <summary> - /// Specifies the generic vertex attribute index this named attribute variable binds to.<br/> - /// If set explicitly this named attribute variable is bound to that generic vertex attribute index before the program is linked.<br/> - /// Defaults to -1, which causes the index to be retrieved after the program is linked. - /// </summary> - public int Index { get; protected set; } - - /// <summary> - /// Initializes a new instance of the VertexAttribAttribute with default values.<br/> - /// The default is 4 components of type float without normalization. - /// </summary> - public VertexAttribAttribute() - : this(4, VertexAttribPointerType.Float, false, -1) - { - } - - /// <summary> - /// Initializes a new instance of the VertexAttribAttribute.<br/> - /// Normalization defaults to false. - /// </summary> - /// <param name="components">The number of components to read.</param> - /// <param name="type">The type of each component.</param> - public VertexAttribAttribute(int components, VertexAttribPointerType type) - : this(components, type, false, -1) - { - } - - /// <summary> - /// Initializes a new instance of the VertexAttribAttribute. - /// </summary> - /// <param name="components">The number of components to read.</param> - /// <param name="type">The type of each component.</param> - /// <param name="normalized">Specifies whether each component should be normalized.</param> - public VertexAttribAttribute(int components, VertexAttribPointerType type, bool normalized) - : this(components, type, normalized, -1) - { - } - - /// <summary> - /// Initializes a new instance of the VertexAttribAttribute. - /// </summary> - /// <param name="components">The number of components to read.</param> - /// <param name="type">The type of each component.</param> - /// <param name="normalized">Specifies whether each component should be normalized.</param> - /// <param name="index"></param> - public VertexAttribAttribute(int components, VertexAttribPointerType type, bool normalized, int index) - { - Components = components; - Type = type; - Normalized = normalized; - Index = index; - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/BitmapFormat.cs b/ObjectTK/Textures/BitmapFormat.cs deleted file mode 100644 index 5a17214..0000000 --- a/ObjectTK/Textures/BitmapFormat.cs +++ /dev/null @@ -1,64 +0,0 @@ -// -// BitmapFormat.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Collections.Generic; -using System.Drawing; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - internal class BitmapFormat - { - public SizedInternalFormat InternalFormat; - public PixelFormat PixelFormat; - public PixelType PixelType; - - private static readonly Dictionary<System.Drawing.Imaging.PixelFormat, BitmapFormat> FormatMap = new Dictionary - <System.Drawing.Imaging.PixelFormat, BitmapFormat> - { - { - System.Drawing.Imaging.PixelFormat.Format24bppRgb, new BitmapFormat - { - InternalFormat = SizedInternalFormat.Rgba8, - PixelFormat = PixelFormat.Bgr, - PixelType = PixelType.UnsignedByte - } - }, - { - System.Drawing.Imaging.PixelFormat.Format32bppArgb, new BitmapFormat - { - InternalFormat = SizedInternalFormat.Rgba8, - PixelFormat = PixelFormat.Bgra, - PixelType = PixelType.UnsignedByte - } - } - }; - - // prevent instantiation - protected BitmapFormat() { } - - static BitmapFormat() - { - // does not work - //_formatMap.Add(System.Drawing.Imaging.PixelFormat.Format16bppRgb555, _formatMap[System.Drawing.Imaging.PixelFormat.Format16bppArgb1555]); - // has alpha too? wtf? - FormatMap.Add(System.Drawing.Imaging.PixelFormat.Format32bppRgb, - FormatMap[System.Drawing.Imaging.PixelFormat.Format32bppArgb]); - FormatMap.Add(System.Drawing.Imaging.PixelFormat.Canonical, - FormatMap[System.Drawing.Imaging.PixelFormat.Format32bppArgb]); - } - - public static BitmapFormat Get(Bitmap bitmap) - { - if (FormatMap.ContainsKey(bitmap.PixelFormat)) return FormatMap[bitmap.PixelFormat]; - throw new ArgumentException("Error: Unsupported Pixel Format " + bitmap.PixelFormat); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/BitmapTexture.cs b/ObjectTK/Textures/BitmapTexture.cs deleted file mode 100644 index 1530b06..0000000 --- a/ObjectTK/Textures/BitmapTexture.cs +++ /dev/null @@ -1,179 +0,0 @@ -// -// BitmapTexture.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Drawing; -using System.Drawing.Imaging; -using OpenTK.Graphics.OpenGL; -using PixelFormat = OpenTK.Graphics.OpenGL.PixelFormat; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Contains extension methods for texture types. - /// </summary> - public static class BitmapTexture - { - private static BitmapData LockBits(Bitmap bitmap) - { - return bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); - } - - private static void CheckError() - { - GL.Finish(); - Utility.Assert("Error while uploading data to texture."); - } - - /// <summary> - /// Creates a new Texture2D instance compatible to the given bitmap. - /// </summary> - /// <param name="bitmap">Specifies the bitmap to which the new texture will be compatible.</param> - /// <param name="texture">Outputs the newly created texture.</param> - /// <param name="levels">Specifies the number of mipmap levels.</param> - public static void CreateCompatible(Bitmap bitmap, out Texture2D texture, int levels = 0) - { - texture = new Texture2D(BitmapFormat.Get(bitmap).InternalFormat, bitmap.Width, bitmap.Height, levels); - } - - /// <summary> - /// Creates a new Texture2DArray instance compatible to the given bitmap. - /// </summary> - /// <param name="bitmap">Specifies the bitmap to which the new texture will be compatible.</param> - /// <param name="texture">Outputs the newly created texture.</param> - /// <param name="layers">Specifies the number of array layers the texture will contain.</param> - /// <param name="levels">Specifies the number of mipmap levels.</param> - public static void CreateCompatible(Bitmap bitmap, out Texture2DArray texture, int layers, int levels = 0) - { - texture = new Texture2DArray(BitmapFormat.Get(bitmap).InternalFormat, bitmap.Width, bitmap.Height, layers, levels); - } - - /// <summary> - /// Creates a new TextureCubemap instance with faces compatible to the given bitmap. - /// </summary> - /// <param name="bitmap">Specifies the bitmap to which the new texture will be compatible.</param> - /// <param name="texture">Outputs the newly created texture.</param> - /// <param name="levels">Specifies the number of mipmap levels.</param> - public static void CreateCompatible(Bitmap bitmap, out TextureCubemap texture, int levels = 0) - { - if (bitmap.Width != bitmap.Height) throw new ArgumentException("The faces of cube map textures must be square."); - texture = new TextureCubemap(BitmapFormat.Get(bitmap).InternalFormat, bitmap.Width, levels); - } - - /// <summary> - /// Creates a new TextureCubemapArray instance with faces compatible to the given bitmap. - /// </summary> - /// <param name="bitmap">Specifies the bitmap to which the new texture will be compatible.</param> - /// <param name="layers">Specifies the number of array layers the texture will contain.</param> - /// <param name="texture">Outputs the newly created texture.</param> - /// <param name="levels">Specifies the number of mipmap levels.</param> - public static void CreateCompatible(Bitmap bitmap, out TextureCubemapArray texture, int layers, int levels = 0) - { - if (bitmap.Width != bitmap.Height) throw new ArgumentException("The faces of cube map textures must be square."); - texture = new TextureCubemapArray(BitmapFormat.Get(bitmap).InternalFormat, bitmap.Width, layers, levels); - } - - /// <summary> - /// Creates a new TextureRectangle instance compatible to the given bitmap. - /// </summary> - /// <param name="bitmap">Specifies the bitmap to which the new texture will be compatible.</param> - /// <param name="texture">Outputs the newly created texture.</param> - public static void CreateCompatible(Bitmap bitmap, out TextureRectangle texture) - { - texture = new TextureRectangle(BitmapFormat.Get(bitmap).InternalFormat, bitmap.Width, bitmap.Height); - } - - /// <summary> - /// Uploads the contents of a bitmap to the given texture level.<br/> - /// Will result in an OpenGL error if the given bitmap is incompatible with the textures storage. - /// </summary> - public static void LoadBitmap(this Texture2D texture, Bitmap bitmap, int level = 0) - { - texture.Bind(); - var data = LockBits(bitmap); - try - { - var map = BitmapFormat.Get(bitmap); - GL.TexSubImage2D(texture.TextureTarget, level, 0, 0, data.Width, data.Height, - map.PixelFormat, map.PixelType, data.Scan0); - } - finally - { - bitmap.UnlockBits(data); - } - CheckError(); - } - - /// <summary> - /// Uploads the contents of a bitmap to the given texture layer and level.<br/> - /// Will result in an OpenGL error if the given bitmap is incompatible with the textures storage. - /// </summary> - public static void LoadBitmap(this LayeredTexture texture, Bitmap bitmap, int layer, int level = 0) - { - texture.Bind(); - var data = LockBits(bitmap); - try - { - var map = BitmapFormat.Get(bitmap); - GL.TexSubImage3D(texture.TextureTarget, level, 0, 0, layer, data.Width, data.Height, 1, - map.PixelFormat, map.PixelType, data.Scan0); - } - finally - { - bitmap.UnlockBits(data); - } - CheckError(); - } - - /// <summary> - /// Uploads the contents of the bitmaps to all faces of the given cube map level.<br/> - /// Will result in an OpenGL error if any of the given bitmaps is incompatible with the textures storage. - /// </summary> - public static void LoadBitmap(this TextureCubemap texture, Bitmap[] bitmaps, int level = 0) - { - if (bitmaps.Length != 6) throw new ArgumentException("Expected exactly 6 bitmaps for a cube map."); - // load all six faces - for (var face = 0; face < 6; face++) texture.LoadBitmap(bitmaps[face], face, level); - } - - /// <summary> - /// Uploads the contents of a bitmap to a single face of the given cube map level.<br/> - /// Will result in an OpenGL error if the given bitmap is incompatible with the textures storage. - /// </summary> - public static void LoadBitmap(this TextureCubemap texture, Bitmap bitmap, int face, int level = 0) - { - const TextureTarget firstFace = TextureTarget.TextureCubeMapPositiveX; - texture.Bind(); - var data = LockBits(bitmap); - try - { - var map = BitmapFormat.Get(bitmap); - GL.TexSubImage2D(firstFace + face, level, 0, 0, data.Width, data.Height, - map.PixelFormat, map.PixelType, data.Scan0); - } - finally - { - bitmap.UnlockBits(data); - } - CheckError(); - } - - /// <summary> - /// Retrieves the texture data. - /// </summary> - public static T[,] GetContent<T>(this Texture2D texture, PixelFormat pixelFormat, PixelType pixelType, int level = 0) - where T : struct - { - var data = new T[texture.Width, texture.Height]; - texture.Bind(); - GL.GetTexImage(texture.TextureTarget, level, pixelFormat, pixelType, data); - return data; - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/LayeredTexture.cs b/ObjectTK/Textures/LayeredTexture.cs deleted file mode 100644 index b26bbcd..0000000 --- a/ObjectTK/Textures/LayeredTexture.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -// LayeredTexture.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a layered texture.<br/> - /// Layered textures are all array, cube map and 3D textures. - /// </summary> - public abstract class LayeredTexture - : Texture - { - public override bool SupportsLayers { get { return true; } } - - internal LayeredTexture(SizedInternalFormat internalFormat, int levels) - : base(internalFormat, levels) - { - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Sampler.cs b/ObjectTK/Textures/Sampler.cs deleted file mode 100644 index 1d38438..0000000 --- a/ObjectTK/Textures/Sampler.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// Sampler.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a sampler object. - /// </summary> - public sealed class Sampler - : GLObject - { - /// <summary> - /// Initializes a new sampler object. - /// </summary> - public Sampler() - : base(GL.GenSampler()) - { - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteSampler(Handle); - } - - /// <summary> - /// Binds the sampler to the given texture unit. - /// </summary> - /// <param name="textureUnit">The texture unit to bind to.</param> - public void Bind(TextureUnit textureUnit) - { - Bind((int)textureUnit - (int)TextureUnit.Texture0); - } - - /// <summary> - /// Binds the sampler to the given texture unit. - /// </summary> - /// <param name="unit">The texture unit to bind to.</param> - public void Bind(int unit) - { - GL.BindSampler(unit, Handle); - } - - /// <summary> - /// Sets the given wrap mode on all dimensions R, S and T. - /// </summary> - /// <param name="wrapMode">The wrap mode to apply.</param> - public void SetWrapMode(TextureWrapMode wrapMode) - { - var mode = (int) wrapMode; - SetParameter(SamplerParameterName.TextureWrapR, mode); - SetParameter(SamplerParameterName.TextureWrapS, mode); - SetParameter(SamplerParameterName.TextureWrapT, mode); - } - - /// <summary> - /// Sets sampler parameters. - /// </summary> - /// <param name="parameterName">The parameter name to set.</param> - /// <param name="value">The value to set.</param> - public void SetParameter(SamplerParameterName parameterName, int value) - { - GL.SamplerParameter(Handle, parameterName, value); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture.cs b/ObjectTK/Textures/Texture.cs deleted file mode 100644 index f26229b..0000000 --- a/ObjectTK/Textures/Texture.cs +++ /dev/null @@ -1,218 +0,0 @@ -// -// Texture.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Linq; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a texture object. - /// </summary> - /// <remarks> - /// <code> - /// Type Supports: Mipmaps Layered - /// ------------------------------------------- - /// Texture1D yes - /// Texture2D yes - /// Texture3D yes yes - /// Texture1DArray yes yes - /// Texture2DArray yes yes - /// TextureCubemap yes yes - /// TextureCubemapArray yes yes - /// Texture2DMultisample - /// Texture2DMultisampleArray yes - /// TextureRectangle - /// TextureBuffer - /// </code> - /// </remarks> - public abstract class Texture - : GLObject - { - /// <summary> - /// Specifies the texture target. - /// </summary> - public abstract TextureTarget TextureTarget { get; } - - /// <summary> - /// Specifies whether this texture supports multiple layers.<br/> - /// True for all texture types derived from LayeredTexture, that is all array, cube map and 3D textures. - /// </summary> - public virtual bool SupportsLayers { get { return false; } } - - /// <summary> - /// Specifies whether this texture supports mipmap levels.<br/> - /// False for buffer, rectangle and multisample textures, otherwise true. - /// </summary> - public virtual bool SupportsMipmaps { get { return true; } } - - /// <summary> - /// The number of mipmap levels. - /// </summary> - public int Levels { get; private set; } - - /// <summary> - /// The internal format of the texture. - /// </summary> - public SizedInternalFormat InternalFormat { get; private set; } - - /// <summary> - /// Initializes a new texture object. Creates a new texture handle. - /// </summary> - /// <param name="internalFormat">The internal format of the texture.</param> - /// <param name="levels">The number of mipmap levels.</param> - internal Texture(SizedInternalFormat internalFormat, int levels) - : this(GL.GenTexture(), internalFormat, levels) - { - } - - /// <summary> - /// Initializes a new texture object. Uses the texture handle given.<br/> - /// Internal constructor used by <see cref="TextureFactory"/> to wrap a texture instance around an already existing texture. - /// </summary> - /// <param name="textureHandle">The texture handle.</param> - /// <param name="internalFormat">The internal format of the texture.</param> - /// <param name="levels">The number of mipmap levels.</param> - internal Texture(int textureHandle, SizedInternalFormat internalFormat, int levels) - : base(textureHandle) - { - InternalFormat = internalFormat; - Levels = levels; - } - - protected override void Dispose(bool manual) - { - if (!manual) return; - GL.DeleteTexture(Handle); - } - - /// <summary> - /// Binds the texture to the current texture unit at its default texture target. - /// </summary> - public void Bind() - { - GL.BindTexture(TextureTarget, Handle); - } - - /// <summary> - /// Binds the texture to the given texture unit at its default texture target. - /// </summary> - /// <param name="unit">The texture unit to bind to.</param> - public void Bind(TextureUnit unit) - { - GL.ActiveTexture(unit); - Bind(); - } - - /// <summary> - /// Calculates the maximum number of mipmap levels allowed for the given size in each dimension.<br/> - /// If <paramref name="levels"/> is greater than zero and less or equal to the calculated maximum it is returned without change.<br/> - /// If <paramref name="levels"/> is zero the calculated maximum is returned instead. - /// </summary> - /// <remarks> - /// At the maximum mipmap level the image would consist of exactly one texel, i.e. 1x1 in 2D or 1x1x1 in 3D. - /// </remarks> - /// <param name="levels">Specifies the number of desired mipmap levels.</param> - /// <param name="dimensions">Specifies the size of the textures base image in each dimension.</param> - /// <returns>A valid number of mipmap levels.</returns> - protected static int GetLevels(int levels, params int[] dimensions) - { - var maxLevels = TextureFactory.CalculateMaxMipmapLevels(dimensions); - if (levels > maxLevels || levels < 0) throw new ArgumentOutOfRangeException("levels", levels, - string.Format("The valid range of mipmapping levels for a maximum texture dimension of {0} is [0,{1}]", dimensions.Max(), maxLevels)); - return levels == 0 ? maxLevels : levels; - } - - /// <summary> - /// Automatically generates all mipmaps. - /// </summary> - public void GenerateMipMaps() - { - if (!SupportsMipmaps) throw new InvalidOperationException("Texture does not support mipmaps."); - Bind(); - GL.GenerateMipmap((GenerateMipmapTarget)TextureTarget); - Utility.Assert("Could not generate mipmaps."); - } - - /// <summary> - /// Sets texture parameters. - /// </summary> - /// <param name="parameterName"></param> - /// <param name="value"></param> - public void SetParameter(TextureParameterName parameterName, int value) - { - GL.TexParameter(TextureTarget, parameterName, value); - } - - /// <summary> - /// Sets the given wrap mode on all dimensions R, S and T. - /// </summary> - /// <param name="wrapMode">The wrap mode to apply.</param> - public void SetWrapMode(TextureWrapMode wrapMode) - { - var mode = (int)wrapMode; - SetParameter(TextureParameterName.TextureWrapR, mode); - SetParameter(TextureParameterName.TextureWrapS, mode); - SetParameter(TextureParameterName.TextureWrapT, mode); - } - - /// <summary> - /// Sets the given texture minification and magnification filters. - /// </summary> - /// <param name="minFilter"></param> - /// <param name="magFilter"></param> - public void SetFilter(TextureMinFilter minFilter, TextureMagFilter magFilter) - { - SetParameter(TextureParameterName.TextureMinFilter, (int)minFilter); - SetParameter(TextureParameterName.TextureMagFilter, (int)magFilter); - } - - /// <summary> - /// Sets default texture parameters to ensure texture completeness.<br/> - /// Enables mipmapping if the texture supports it, otherwise filtering is set to linear interpolation. - /// </summary> - public virtual void SetDefaultTexParameters() - { - SetParameter(TextureParameterName.TextureMinFilter, (int)(Levels > 1 ? TextureMinFilter.NearestMipmapLinear : TextureMinFilter.Linear)); - SetParameter(TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - Utility.Assert("Could not set tex parameters."); - } - - /// <summary> - /// Checks if the given mipmap level is supported by this texture.<br/> - /// A supported level is either zero for all textures which do not support mipmapping, - /// or smaller than the number of existing levels. - /// </summary> - /// <param name="level">The mipmap level of the texture.</param> - /// <returns>True if the level is supported, otherwise false.</returns> - public bool SupportsLevel(int level) - { - return (SupportsMipmaps || level == 0) && (level < Levels || !SupportsMipmaps); - } - - /// <summary> - /// Throws an exception if the given mipmap level is not supported by this texture.<br/> - /// The mipmap level must be zero for all texture types which do not support mipmaps. - /// </summary> - /// <param name="level">Specifies a mipmap level of the texture.</param> - internal void AssertLevel(int level) - { - if (!SupportsLevel(level)) throw new ArgumentException(string.Format("Texture does not contain the mipmap level {0} or does not support mipmapping at all.", level)); - } - - /// <summary> - /// Calls GL.<see cref="GL.GetError()"/> to check if there are any errors. - /// </summary> - protected static void CheckError() - { - Utility.Assert("Texture error"); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture1D.cs b/ObjectTK/Textures/Texture1D.cs deleted file mode 100644 index 6d9ed89..0000000 --- a/ObjectTK/Textures/Texture1D.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// Texture1D.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a 1D texture.<br/> - /// Images in this texture all are 1-dimensional. They have width, but no height or depth. - /// </summary> - public sealed class Texture1D - : Texture - { - public override TextureTarget TextureTarget { get { return TextureTarget.Texture1D; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="levels">The number of mipmap levels.</param> - public Texture1D(SizedInternalFormat internalFormat, int width, int levels = 0) - : base(internalFormat, GetLevels(levels, width)) - { - Width = width; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage1D((TextureTarget1d)TextureTarget, Levels, InternalFormat, Width); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture1DArray.cs b/ObjectTK/Textures/Texture1DArray.cs deleted file mode 100644 index 3ac1bf6..0000000 --- a/ObjectTK/Textures/Texture1DArray.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -// Texture1DArray.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a 1D texture array.<br/> - /// Images in this texture all are 1-dimensional. However, it contains multiple sets of 1-dimensional images, - /// all within one texture. The array length is part of the texture's size. - /// </summary> - public sealed class Texture1DArray - : LayeredTexture - { - public override TextureTarget TextureTarget { get { return TextureTarget.Texture1DArray; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// The number of layers.<br/> - /// note: OpenGL seems to call the second coordinate on a 1D texture array the "height", - /// which would make the whole thing almost exactly equal to a 2D texture with the exception that - /// a 1D texture array can be bound to a framebuffer via glFramebufferTextureLayer(). - /// </summary> - public int Layers { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="layers">The number of layers to allocate.</param> - /// <param name="levels">The number of mipmap levels.</param> - public Texture1DArray(SizedInternalFormat internalFormat, int width, int layers, int levels = 0) - : base(internalFormat, GetLevels(levels, width)) - { - Width = width; - Layers = layers; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage2D((TextureTarget2d)TextureTarget, Levels, InternalFormat, Width, Layers); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture2D.cs b/ObjectTK/Textures/Texture2D.cs deleted file mode 100644 index 27d0886..0000000 --- a/ObjectTK/Textures/Texture2D.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// Texture2D.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a 2D texture.<br/> - /// Images in this texture all are 2-dimensional. They have width and height, but no depth. - /// </summary> - public sealed class Texture2D - : Texture - { - public override TextureTarget TextureTarget { get { return TextureTarget.Texture2D; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// The height of the texture. - /// </summary> - public int Height { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters.<br/> - /// A value of zero for the number of mipmap levels will default to the maximum number of levels possible for the given bitmaps width and height. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="height">The height of the texture.</param> - /// <param name="levels">The number of mipmap levels.</param> - public Texture2D(SizedInternalFormat internalFormat, int width, int height, int levels = 0) - : base(internalFormat, GetLevels(levels, width, height)) - { - Width = width; - Height = height; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage2D((TextureTarget2d)TextureTarget, Levels, InternalFormat, Width, Height); - CheckError(); - } - - /// <summary> - /// Internal constructor used by <see cref="TextureFactory"/> to wrap a Texture2D instance around an already existing texture. - /// </summary> - internal Texture2D(int textureHandle, SizedInternalFormat internalFormat, int width, int height, int levels) - : base(textureHandle, internalFormat, levels) - { - Width = width; - Height = height; - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture2DArray.cs b/ObjectTK/Textures/Texture2DArray.cs deleted file mode 100644 index e645915..0000000 --- a/ObjectTK/Textures/Texture2DArray.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// Texture2DArray.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a 2D texture array.<br/> - /// Images in this texture all are 2-dimensional. However, it contains multiple sets of 2-dimensional images, - /// all within one texture. The array length is part of the texture's size. - /// </summary> - public sealed class Texture2DArray - : LayeredTexture - { - public override TextureTarget TextureTarget { get { return TextureTarget.Texture2DArray; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// The height of the texture. - /// </summary> - public int Height { get; private set; } - - /// <summary> - /// The number of layers. - /// </summary> - public int Layers { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters.<br/> - /// A value of zero for the number of mipmap levels will default to the maximum number of levels possible for the given bitmaps width and height. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="height">The height of the texture.</param> - /// <param name="layers">The number of layers to allocate.</param> - /// <param name="levels">The number of mipmap levels.</param> - public Texture2DArray(SizedInternalFormat internalFormat, int width, int height, int layers, int levels = 0) - : base(internalFormat, GetLevels(levels, width, height)) - { - Width = width; - Height = height; - Layers = layers; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage3D((TextureTarget3d)TextureTarget, Levels, InternalFormat, Width, Height, Layers); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture2DMultisample.cs b/ObjectTK/Textures/Texture2DMultisample.cs deleted file mode 100644 index b4c3796..0000000 --- a/ObjectTK/Textures/Texture2DMultisample.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// Texture2DMultisample.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a 2D multisample texture.<br/> - /// The image in this texture (only one image. No mipmapping) is 2-dimensional. - /// Each pixel in this image contains multiple samples instead of just one value. - /// </summary> - public sealed class Texture2DMultisample - : Texture - { - public override TextureTarget TextureTarget { get { return TextureTarget.Texture2DMultisample; } } - public override bool SupportsMipmaps { get { return false; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// The height of the texture. - /// </summary> - public int Height { get; private set; } - - /// <summary> - /// The number of samples per texel. - /// </summary> - public int Samples { get; private set; } - - /// <summary> - /// Specifies whether the texels will use identical sample locations. - /// </summary> - public bool FixedSampleLocations { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="height">The height of the texture.</param> - /// <param name="samples">The number of samples per texel.</param> - /// <param name="fixedSampleLocations">Specifies whether the texels will use identical sample locations.</param> - public Texture2DMultisample(SizedInternalFormat internalFormat, int width, int height, int samples, bool fixedSampleLocations) - : base(internalFormat, 1) - { - Width = width; - Height = height; - Samples = samples; - FixedSampleLocations = fixedSampleLocations; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage2DMultisample((TextureTargetMultisample2d)TextureTarget, Samples, InternalFormat, Width, Height, FixedSampleLocations); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture2DMultisampleArray.cs b/ObjectTK/Textures/Texture2DMultisampleArray.cs deleted file mode 100644 index 767ace5..0000000 --- a/ObjectTK/Textures/Texture2DMultisampleArray.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// Texture2DMultisampleArray.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a 2D multisample array texture.<br/> - /// Combines 2D array and 2D multisample types. No mipmapping. - /// </summary> - public sealed class Texture2DMultisampleArray - : LayeredTexture - { - public override TextureTarget TextureTarget { get { return TextureTarget.Texture2DMultisampleArray; } } - public override bool SupportsMipmaps { get { return false; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// The height of the texture. - /// </summary> - public int Height { get; private set; } - - /// <summary> - /// The number of layers. - /// </summary> - public int Layers { get; private set; } - - /// <summary> - /// The number of samples per texel. - /// </summary> - public int Samples { get; private set; } - - /// <summary> - /// Specifies whether the texels will use identical sample locations. - /// </summary> - public bool FixedSampleLocations { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="height">The height of the texture.</param> - /// <param name="layers">The number of layers to allocate.</param> - /// <param name="samples">The number of samples per texel.</param> - /// <param name="fixedSampleLocations">Specifies whether the texels will use identical sample locations.</param> - public Texture2DMultisampleArray(SizedInternalFormat internalFormat, int width, int height, int layers, int samples, bool fixedSampleLocations) - : base(internalFormat, 1) - { - Width = width; - Height = height; - Layers = layers; - Samples = samples; - FixedSampleLocations = fixedSampleLocations; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage3DMultisample((TextureTargetMultisample3d)TextureTarget, Samples, InternalFormat, Width, Height, Layers, FixedSampleLocations); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/Texture3D.cs b/ObjectTK/Textures/Texture3D.cs deleted file mode 100644 index 4d70ef7..0000000 --- a/ObjectTK/Textures/Texture3D.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// Texture3D.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a 3D texture.<br/> - /// Images in this texture all are 3-dimensional. They have width, height, and depth. - /// </summary> - public sealed class Texture3D - : LayeredTexture - { - public override TextureTarget TextureTarget { get { return TextureTarget.Texture3D; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// The height of the texture. - /// </summary> - public int Height { get; private set; } - - /// <summary> - /// The depth of the texture. - /// </summary> - public int Depth { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="height">The height of the texture.</param> - /// <param name="depth">The depth of the texture.</param> - /// <param name="levels">The number of mipmap levels.</param> - public Texture3D(SizedInternalFormat internalFormat, int width, int height, int depth, int levels = 0) - : base(internalFormat, GetLevels(levels, width, height, depth)) - { - Width = width; - Height = height; - Depth = depth; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage3D((TextureTarget3d)TextureTarget, Levels, InternalFormat, Width, Height, Depth); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/TextureBuffer.cs b/ObjectTK/Textures/TextureBuffer.cs deleted file mode 100644 index 491979e..0000000 --- a/ObjectTK/Textures/TextureBuffer.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// TextureBuffer.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using ObjectTK.Buffers; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a buffer texture.<br/> - /// The image in this texture (only one image. No mipmapping) is 1-dimensional. - /// The storage for this data comes from a Buffer Object. - /// </summary> - public sealed class TextureBuffer - : Texture - { - public override TextureTarget TextureTarget { get { return TextureTarget.TextureBuffer; } } - public override bool SupportsMipmaps { get { return false; } } - - /// <summary> - /// Creates a buffer texture and uses the given internal format to access a bound buffer, if not specified otherwise. - /// </summary> - /// <param name="internalFormat"></param> - public TextureBuffer(SizedInternalFormat internalFormat) - : base(internalFormat, 1) - { - } - - /// <summary> - /// Binds the given buffer to this texture.<br/> - /// Applies the internal format specified in the constructor. - /// </summary> - /// <param name="buffer">The buffer to bind.</param> - public void BindBufferToTexture<T>(Buffer<T> buffer) - where T : struct - { - BindBufferToTexture(buffer, InternalFormat); - } - - /// <summary> - /// Binds the given buffer to this texture using the given internal format. - /// </summary> - /// <param name="buffer">The buffer to bind.</param> - /// <param name="internalFormat">The internal format used when accessing the buffer.</param> - /// <typeparam name="T">The type of elements in the buffer object.</typeparam> - public void BindBufferToTexture<T>(Buffer<T> buffer, SizedInternalFormat internalFormat) - where T : struct - { - if (!buffer.Initialized) throw new ArgumentException("Can not bind uninitialized buffer to buffer texture.", "buffer"); - GL.BindTexture(TextureTarget.TextureBuffer, Handle); - GL.TexBuffer(TextureBufferTarget.TextureBuffer, internalFormat, buffer.Handle); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/TextureCubemap.cs b/ObjectTK/Textures/TextureCubemap.cs deleted file mode 100644 index afa5b86..0000000 --- a/ObjectTK/Textures/TextureCubemap.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -// TextureCubemap.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a cubemap texture.<br/> - /// There are exactly 6 distinct sets of 2D images, all of the same size. They act as 6 faces of a cube. - /// </summary> - public sealed class TextureCubemap - : LayeredTexture - { - public override TextureTarget TextureTarget { get { return TextureTarget.TextureCubeMap; } } - - /// <summary> - /// The size of the texture.<br/> - /// This represents both width and height of the texture, because cube maps have to be square. - /// </summary> - public int Size { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="size">The width and height of the cube map faces.</param> - /// <param name="levels">The number of mipmap levels.</param> - public TextureCubemap(SizedInternalFormat internalFormat, int size, int levels = 0) - : base(internalFormat, GetLevels(levels, size)) - { - Size = size; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage2D((TextureTarget2d)TextureTarget, Levels, InternalFormat, Size, Size); - CheckError(); - } - } -} diff --git a/ObjectTK/Textures/TextureCubemapArray.cs b/ObjectTK/Textures/TextureCubemapArray.cs deleted file mode 100644 index cd689c7..0000000 --- a/ObjectTK/Textures/TextureCubemapArray.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -// TextureCubemapArray.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a cubemap texture array.<br/> - /// Images in this texture are all cube maps. It contains multiple sets of cube maps, all within one texture. - /// The array length * 6 (number of cube faces) is part of the texture size. - /// </summary> - public sealed class TextureCubemapArray - : LayeredTexture - { - public override TextureTarget TextureTarget { get { return TextureTarget.TextureCubeMapArray; } } - - /// <summary> - /// The size of the texture.<br/> - /// This represents both width and height of the texture, because cube maps have to be square. - /// </summary> - public int Size { get; private set; } - - /// <summary> - /// The number of layers. - /// </summary> - public int Layers { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="size">The width and height of the cube map faces.</param> - /// <param name="layers">The number of layers to allocate.</param> - /// <param name="levels">The number of mipmap levels.</param> - public TextureCubemapArray(SizedInternalFormat internalFormat, int size, int layers, int levels = 0) - : base(internalFormat, GetLevels(levels, size)) - { - Size = size; - Layers = layers; - GL.BindTexture(TextureTarget, Handle); - // note: the depth parameter is the number of layer-faces hence the multiplication by six, - // see https://www.opengl.org/wiki/Texture_Storage#Immutable_storage - GL.TexStorage3D((TextureTarget3d)TextureTarget, Levels, InternalFormat, Size, Size, 6 * Layers); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/TextureFactory.cs b/ObjectTK/Textures/TextureFactory.cs deleted file mode 100644 index ebcf338..0000000 --- a/ObjectTK/Textures/TextureFactory.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// TextureFactory.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Linq; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Provides methods for creating texture objects in ways not covered by constructors. - /// </summary> - public static class TextureFactory - { - /// <summary> - /// Creates a new Texture2D instance using the given texture handle.<br/> - /// The width, height and internal format are queried from OpenGL and passed to the instance. - /// The number of mipmap levels can not be queried and must be specified, otherwise it is set to one. - /// TODO: somehow find out the number of mipmap levels because otherwise <see cref="Texture.AssertLevel"/> does not work correctly. - /// </summary> - /// <param name="textureHandle">An active handle to a 2D texture.</param> - /// <param name="levels">The number of mipmap levels.</param> - /// <returns>A new Texture2D instance.</returns> - public static Texture2D AquireTexture2D(int textureHandle, int levels = 1) - { - int width, height, internalFormat; - GL.BindTexture(TextureTarget.Texture2D, textureHandle); - GL.GetTexLevelParameter(TextureTarget.Texture2D, 0, GetTextureParameter.TextureWidth, out width); - GL.GetTexLevelParameter(TextureTarget.Texture2D, 0, GetTextureParameter.TextureHeight, out height); - GL.GetTexLevelParameter(TextureTarget.Texture2D, 0, GetTextureParameter.TextureInternalFormat, out internalFormat); - return new Texture2D(textureHandle, (SizedInternalFormat)internalFormat, width, height, levels); - } - - /// <summary> - /// Calculates the maximum number of mipmap levels allowed, based on the size of all dimensions given. - /// </summary> - /// <param name="dimensions">Specifies the size in all dimensions.</param> - /// <returns>The maximum number of mipmap levels allowed. The last level would consist of 1 texel.</returns> - public static int CalculateMaxMipmapLevels(params int[] dimensions) - { - return 1 + (int)Math.Floor(Math.Log(dimensions.Max())); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Textures/TextureRectangle.cs b/ObjectTK/Textures/TextureRectangle.cs deleted file mode 100644 index 048ee27..0000000 --- a/ObjectTK/Textures/TextureRectangle.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// TextureRectangle.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK.Textures -{ - /// <summary> - /// Represents a rectangle texture.<br/> - /// The image in this texture (only one image. No mipmapping) is 2-dimensional. - /// Texture coordinates used for these textures are not normalized. - /// </summary> - public sealed class TextureRectangle - : Texture - { - public override TextureTarget TextureTarget { get { return TextureTarget.TextureRectangle; } } - public override bool SupportsMipmaps { get { return false; } } - - /// <summary> - /// The width of the texture. - /// </summary> - public int Width { get; private set; } - - /// <summary> - /// The height of the texture. - /// </summary> - public int Height { get; private set; } - - /// <summary> - /// Allocates immutable texture storage with the given parameters. - /// </summary> - /// <param name="internalFormat">The internal format to allocate.</param> - /// <param name="width">The width of the texture.</param> - /// <param name="height">The height of the texture.</param> - public TextureRectangle(SizedInternalFormat internalFormat, int width, int height) - : base(internalFormat, 1) - { - Width = width; - Height = height; - GL.BindTexture(TextureTarget, Handle); - GL.TexStorage2D((TextureTarget2d)TextureTarget, 1, InternalFormat, Width, Height); - CheckError(); - } - } -} \ No newline at end of file diff --git a/ObjectTK/Utility.cs b/ObjectTK/Utility.cs deleted file mode 100644 index 7d4ec84..0000000 --- a/ObjectTK/Utility.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// Utility.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using ObjectTK.Exceptions; -using OpenTK.Graphics.OpenGL; - -namespace ObjectTK -{ - internal static class Utility - { - private static readonly Logging.IObjectTKLogger Logger = Logging.LogFactory.GetLogger(typeof(Utility)); - - public static void Assert(string errorMessage) - { - Assert(GL.GetError(), ErrorCode.NoError, errorMessage); - } - - public static void Assert(ErrorCode desiredErrorCode, string errorMessage) - { - Assert(GL.GetError(), desiredErrorCode, errorMessage); - } - - public static void Assert<T>(T value, T desiredValue, string errorMessage) - { - if (desiredValue.Equals(value)) return; - Logger?.Error(string.Format("Assert failed: {0}\n{1}", value, errorMessage)); - throw new ObjectTKException(string.Format("ErrorCode: {0}\n{1}", value, errorMessage)); - } - } -} diff --git a/ObjectTK/Vector3i.cs b/ObjectTK/Vector3i.cs deleted file mode 100644 index e00968b..0000000 --- a/ObjectTK/Vector3i.cs +++ /dev/null @@ -1,413 +0,0 @@ -// -// Vector3i.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// - -using System; -using System.Runtime.InteropServices; - -namespace ObjectTK -{ - /// <summary>Represents a 3D vector using three 32-bit integer values.</summary> - /// <remarks> - /// The Vector3i structure is suitable for interoperation with unmanaged code requiring three consecutive integers. - /// </remarks> - [Serializable] - public struct Vector3i : IEquatable<Vector3i> - { - #region Fields - - /// <summary> - /// The X component of the Vector3i. - /// </summary> - public int X; - - /// <summary> - /// The Y component of the Vector3i. - /// </summary> - public int Y; - - /// <summary> - /// The Z component of the Vector3i. - /// </summary> - public int Z; - - #endregion - - #region Constructors - - /// <summary> - /// Constructs a new Vector3i. - /// </summary> - /// <param name="x">The x coordinate of the net Vector3i.</param> - /// <param name="y">The y coordinate of the net Vector3i.</param> - /// <param name="z">The z coordinate of the net Vector3i.</param> - public Vector3i(int x, int y, int z) - { - X = x; - Y = y; - Z = z; - } - - #endregion - - #region Public Members - - #region Static - - #region Fields - - /// <summary> - /// Defines a unit-length Vector3i that points towards the X-axis. - /// </summary> - public static readonly Vector3i UnitX = new Vector3i(1, 0, 0); - - /// <summary> - /// Defines a unit-length Vector3i that points towards the Y-axis. - /// </summary> - public static readonly Vector3i UnitY = new Vector3i(0, 1, 0); - - /// <summary> - /// Defines a unit-length Vector3i that points towards the Z-axis. - /// </summary> - public static readonly Vector3i UnitZ = new Vector3i(0, 0, 1); - - /// <summary> - /// Defines a zero-length Vector3i. - /// </summary> - public static readonly Vector3i Zero = new Vector3i(0, 0, 0); - - /// <summary> - /// Defines an instance with all components set to 1. - /// </summary> - public static readonly Vector3i One = new Vector3i(1, 1, 1); - - /// <summary> - /// Defines the size of the Vector3i struct in bytes. - /// </summary> - public static readonly int SizeInBytes = Marshal.SizeOf(new Vector3i()); - - #endregion - - #region Add - - /// <summary> - /// Adds two vectors. - /// </summary> - /// <param name="a">Left operand.</param> - /// <param name="b">Right operand.</param> - /// <returns>Result of operation.</returns> - public static Vector3i Add(Vector3i a, Vector3i b) - { - Add(ref a, ref b, out a); - return a; - } - - /// <summary> - /// Adds two vectors. - /// </summary> - /// <param name="a">Left operand.</param> - /// <param name="b">Right operand.</param> - /// <param name="result">Result of operation.</param> - public static void Add(ref Vector3i a, ref Vector3i b, out Vector3i result) - { - result = new Vector3i(a.X + b.X, a.Y + b.Y, a.Z + b.Z); - } - - #endregion - - #region Subtract - - /// <summary> - /// Subtract one Vector from another - /// </summary> - /// <param name="a">First operand</param> - /// <param name="b">Second operand</param> - /// <returns>Result of subtraction</returns> - public static Vector3i Subtract(Vector3i a, Vector3i b) - { - Subtract(ref a, ref b, out a); - return a; - } - - /// <summary> - /// Subtract one Vector from another - /// </summary> - /// <param name="a">First operand</param> - /// <param name="b">Second operand</param> - /// <param name="result">Result of subtraction</param> - public static void Subtract(ref Vector3i a, ref Vector3i b, out Vector3i result) - { - result = new Vector3i(a.X - b.X, a.Y - b.Y, a.Z - b.Z); - } - - #endregion - - #region Abs - - /// <summary> - /// Applies component-wise absolute evaluation - /// </summary> - /// <param name="value">Absolute operation applies to this vector's components</param> - /// <returns>A vector whose components have absolute value of given vector</returns> - public static Vector3i Abs(Vector3i value) - { - Vector3i result; - Abs(ref value, out result); - return result; - } - - /// <summary> - /// Applies component-wise absolute evaluation - /// </summary> - /// <param name="value">Absolute operation applies to this vector's components</param> - /// <param name="result">A vector whose components have absolute value of given vector <paramref name="value"/></param> - public static void Abs(ref Vector3i value, out Vector3i result) - { - result = new Vector3i(Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z)); - } - - /// <summary> - /// Applies component-wise absolute evaluation - /// </summary> - /// <param name="value">Absolute operation applies to this vector's components</param> - public static void Abs(ref Vector3i value) - { - Abs(ref value, out value); - } - - #endregion - - #region ComponentMin - - /// <summary> - /// Calculate the component-wise minimum of two vectors - /// </summary> - /// <param name="a">First operand</param> - /// <param name="b">Second operand</param> - /// <returns>The component-wise minimum</returns> - public static Vector3i ComponentMin(Vector3i a, Vector3i b) - { - a.X = a.X < b.X ? a.X : b.X; - a.Y = a.Y < b.Y ? a.Y : b.Y; - a.Z = a.Z < b.Z ? a.Z : b.Z; - return a; - } - - /// <summary> - /// Calculate the component-wise minimum of two vectors - /// </summary> - /// <param name="a">First operand</param> - /// <param name="b">Second operand</param> - /// <param name="result">The component-wise minimum</param> - public static void ComponentMin(ref Vector3i a, ref Vector3i b, out Vector3i result) - { - result.X = a.X < b.X ? a.X : b.X; - result.Y = a.Y < b.Y ? a.Y : b.Y; - result.Z = a.Z < b.Z ? a.Z : b.Z; - } - - #endregion - - #region ComponentMax - - /// <summary> - /// Calculate the component-wise maximum of two vectors - /// </summary> - /// <param name="a">First operand</param> - /// <param name="b">Second operand</param> - /// <returns>The component-wise maximum</returns> - public static Vector3i ComponentMax(Vector3i a, Vector3i b) - { - a.X = a.X > b.X ? a.X : b.X; - a.Y = a.Y > b.Y ? a.Y : b.Y; - a.Z = a.Z > b.Z ? a.Z : b.Z; - return a; - } - - /// <summary> - /// Calculate the component-wise maximum of two vectors - /// </summary> - /// <param name="a">First operand</param> - /// <param name="b">Second operand</param> - /// <param name="result">The component-wise maximum</param> - public static void ComponentMax(ref Vector3i a, ref Vector3i b, out Vector3i result) - { - result.X = a.X > b.X ? a.X : b.X; - result.Y = a.Y > b.Y ? a.Y : b.Y; - result.Z = a.Z > b.Z ? a.Z : b.Z; - } - - #endregion - - #region Clamp - - /// <summary> - /// Clamp a vector to the given minimum and maximum vectors - /// </summary> - /// <param name="vec">Input vector</param> - /// <param name="min">Minimum vector</param> - /// <param name="max">Maximum vector</param> - /// <returns>The clamped vector</returns> - public static Vector3i Clamp(Vector3i vec, Vector3i min, Vector3i max) - { - vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; - vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; - vec.Z = vec.Z < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; - return vec; - } - - /// <summary> - /// Clamp a vector to the given minimum and maximum vectors - /// </summary> - /// <param name="vec">Input vector</param> - /// <param name="min">Minimum vector</param> - /// <param name="max">Maximum vector</param> - /// <param name="result">The clamped vector</param> - public static void Clamp(ref Vector3i vec, ref Vector3i min, ref Vector3i max, out Vector3i result) - { - result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; - result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; - result.Z = vec.Z < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; - } - - #endregion - - #endregion - - #region Operators - - /// <summary> - /// Adds the specified instances. - /// </summary> - /// <param name="left">Left operand.</param> - /// <param name="right">Right operand.</param> - /// <returns>Result of addition.</returns> - public static Vector3i operator +(Vector3i left, Vector3i right) - { - left.X += right.X; - left.Y += right.Y; - left.Z += right.Z; - return left; - } - - /// <summary> - /// Subtracts the specified instances. - /// </summary> - /// <param name="left">Left operand.</param> - /// <param name="right">Right operand.</param> - /// <returns>Result of subtraction.</returns> - public static Vector3i operator -(Vector3i left, Vector3i right) - { - left.X -= right.X; - left.Y -= right.Y; - left.Z -= right.Z; - return left; - } - - /// <summary> - /// Negates the specified instance. - /// </summary> - /// <param name="vec">Operand.</param> - /// <returns>Result of negation.</returns> - public static Vector3i operator -(Vector3i vec) - { - vec.X = -vec.X; - vec.Y = -vec.Y; - vec.Z = -vec.Z; - return vec; - } - - /// <summary> - /// Compares the specified instances for equality. - /// </summary> - /// <param name="left">Left operand.</param> - /// <param name="right">Right operand.</param> - /// <returns>True if both instances are equal; false otherwise.</returns> - public static bool operator ==(Vector3i left, Vector3i right) - { - return left.Equals(right); - } - - /// <summary> - /// Compares the specified instances for inequality. - /// </summary> - /// <param name="left">Left operand.</param> - /// <param name="right">Right operand.</param> - /// <returns>True if both instances are not equal; false otherwise.</returns> - public static bool operator !=(Vector3i left, Vector3i right) - { - return !left.Equals(right); - } - - #endregion - - #region Overrides - - #region public override string ToString() - - /// <summary> - /// Returns a System.String that represents the current Vector3i. - /// </summary> - /// <returns></returns> - public override string ToString() - { - return String.Format("({0}, {1}, {2})", X, Y, Z); - } - - #endregion - - #region public override int GetHashCode() - - /// <summary> - /// Returns the hashcode for this instance. - /// </summary> - /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> - public override int GetHashCode() - { - return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); - } - - #endregion - - #region public override bool Equals(object obj) - - /// <summary> - /// Indicates whether this instance and a specified object are equal. - /// </summary> - /// <param name="obj">The object to compare to.</param> - /// <returns>True if the instances are equal; false otherwise.</returns> - public override bool Equals(object obj) - { - if (!(obj is Vector3i)) - return false; - - return this.Equals((Vector3i)obj); - } - - #endregion - - #endregion - - #endregion - - #region IEquatable<Vector3i> Members - - /// <summary>Indicates whether the current vector is equal to another vector.</summary> - /// <param name="other">A vector to compare with this vector.</param> - /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> - public bool Equals(Vector3i other) - { - return - X == other.X && - Y == other.Y && - Z == other.Z; - } - - #endregion - } -} \ No newline at end of file diff --git a/ObjectTK/packages.config b/ObjectTK/packages.config deleted file mode 100644 index 338f3df..0000000 --- a/ObjectTK/packages.config +++ /dev/null @@ -1,5 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<packages> - <package id="log4net" version="2.0.3" targetFramework="net40" /> - <package id="OpenTK" version="1.1.1589.5942" targetFramework="net40" /> -</packages> \ No newline at end of file diff --git a/README.md b/README.md index 739de4b..ff386a4 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,41 @@ -What is ObjectTK? -====== - -ObjectTK is a thin abstraction layer on top of OpenTK to provide OpenGL features in an object-oriented and mostly type-safe manner with modern C#-style. -It is fully aimed at modern OpenGL and compatible to the OpenGL4 core profile. - -Currently there are types for the following OpenGL features: -* Programs and Shaders -* Textures -* Vertex array objects -* Buffer objects -* Sampler objects -* Query objects -* Framebuffers -* Renderbuffers - -The main advantages of using these types are: -* Cleaner interface than using the OpenGL API directly. -* Type-safety when suitable. -* Removes the necessary but error-prone boilerplate code from your project. -* Immediate detection of leaked resources. -* Information log via log4net. -* The Debug-Build also includes additional sanity-checks which help tracking down common errors. - -ObjectTK does not force you to use its functionality and skip the OpenGL API at all. It is perfectly fine to use the OpenGL API directly and the ObjectTK types side-by-side, because ObjectTK does not explicitly keep track of any OpenGL state which might get corrupted when you call the OpenGL API without it knowing. This is an essential feature which makes ObjectTK very usable even if it is not a "complete" wrapper around every corner of OpenGL. - -## What about performance? -Just like any wrapper it introduces another layer between the things you want to get done and the hardware, so it may theoretically slow things down a bit, but there are two things to consider: -- When using modern OpenGL, which is the main target of ObjectTK, the number of API-calls is much lower than it used to be. That means that the overhead of each API-call is not that important anymore. -- The wrapper really is very thin, more often than not there is just a single method call between you and the OpenGL API for functionality which might get used very often. For initialization-related stuff the layer may be a little thicker because it does things right, with all possible error-checking and so forth. - -## Examples -For examples please have a look at the Examples project and the wiki pages: [Basic example](https://github.com/JcBernack/ObjectTK/wiki/Basic-example) +ObjectTK +====== + + +ObjectTK is an extensible convenience layer for OpenGL. By itself, ObjectTK does not attempt to OO-ify the OpenGL API, but rather provide useful everyday classes which consolidate and simplify OpenGL operations. + +ObjectTK is currently under rapid active development. + +Features +======== + +- Highest possible performance. +- Full interop with "normal" OpenGL. +- Well-defined data types for all GL objects. +- Easy shader compiler. +- Highly extensible object model. +- Zero-overhead abstraction. + +ObjectTK is directly run and managed by [The OpenTK Team](https://opentk.github.io/). + +We'd love you to come and join us on the Discord! +[](https://discord.gg/GZTYR4s) + +## Getting started: + +1. [Install via NuGet](https://www.nuget.org/packages/ObjectTk) +2. Create things you need via `GLFactory`. + +## Build instructions + +Need Help? +========== + +Come chat with us on [Discord](https://discord.gg/6HqD48s). + +We're happy to help with anything from learning OpenGL to advanced OpenTK questions. + +License +======= + +ObjectTK is distributed under the permissive MIT license and is absolutely free. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 0000000..5b9fe34 --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,32 @@ +### 2.0.0-pre.9 + * Vertex buffer improvements + * New fast GLFactory.Buffer methods on lists. + +### 2.0.0-pre.8 + * Fix mipmap generation + +### 2.0.0-pre.7 + * Fix texture labelling + +### 2.0.0-pre.6 + * Add texture config default object + copy method. + +### 2.0.0-pre.5 + * Add textures to GLFactory + TextureConfig + * Add Zoom functionality to Camera2D + + +### 2.0.0-pre.4 + * Fix component count error in buffers. + +### 2.0.0-pre.3 + * Fix labelling error. + +### 2.0.0-pre.2 + * Fix error in shader compiler. + * Add support for indexed vertex arrays. + + +### 2.0.0-pre.1 + * Start of release notes for v2. + * Initial testing of build automation. diff --git a/build.cmd b/build.cmd new file mode 100644 index 0000000..0b3d544 --- /dev/null +++ b/build.cmd @@ -0,0 +1,8 @@ +REM Install .NET Core (https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-install-script) + +@powershell -NoProfile -ExecutionPolicy unrestricted -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; &([scriptblock]::Create((Invoke-WebRequest -useb 'https://dot.net/v1/dotnet-install.ps1'))) --version 3.1.100" + +SET PATH=%LOCALAPPDATA%\Microsoft\dotnet;%PATH% +.paket\paket.bootstrapper.exe +dotnet tool restore +dotnet fake run build.fsx %* \ No newline at end of file diff --git a/build.fsx b/build.fsx new file mode 100644 index 0000000..ca657b3 --- /dev/null +++ b/build.fsx @@ -0,0 +1,285 @@ +open System +open System.IO +open System.Threading +open Fake.Core +open Fake.DotNet +open Fake.DotNet.NuGet +open Fake.IO + +#r "paket: +storage: packages +nuget Fake.IO.FileSystem +nuget Fake.DotNet.MSBuild +nuget Fake.DotNet.Testing.XUnit2 +nuget Fake.DotNet.AssemblyInfoFile +nuget Fake.DotNet.NuGet prerelease +nuget Fake.DotNet.Paket +nuget Fake.DotNet.Cli +nuget Fake.Core.Target +nuget Fake.Net.Http +nuget Fake.Api.Github +nuget xunit.runner.console +nuget NuGet.CommandLine +nuget Fake.Core.ReleaseNotes //" + +#load "./.fake/build.fsx/intellisense.fsx" + +open Fake.IO +open Fake.IO.FileSystemOperators +open Fake.IO.Globbing.Operators + +// --------- +// Configuration +// --------- + +let project = "ObjectTK" + +let authors = [ "Team OpenTK" ] + +let summary = "High-performance, extensible and unopinionated implementation of Data types and utilities for OpenGL & game development. A convenience layer above OpenTK aiming to speed up and simplify common tasks." + +let license = "https://opensource.org/licenses/MIT" + +let projectUrl = "https://github.com/opentk/objecttk" + +let iconUrl = "https://raw.githubusercontent.com/opentk/opentk/master/docs/files/img/logo.png" + +let description = + "High-performance, extensible and unopinionated implementation of Data types and utilities for OpenGL & game development. A convenience layer above OpenTK aiming to speed up and simplify common tasks. + + OpenTK comes with simple and easy to follow tutorials for learning *modern* OpenGL. These are written by the community and represent all of the best practices to get you started. + Learn how to use OpenTK here: + https://opentk.net/learn/index.html + + Sample projects that accompany the tutorial can be found here: + https://github.com/opentk/LearnOpenTK + + We have a very active discord server, if you need help, want to help, or are just curious, come join us! + https://discord.gg/6HqD48s + + " + +let tags = "ObjectTK OpenTK OpenGL OpenGLES GLES OpenAL OpenCL C# F# .NET Mono Vector Math Game Graphics Sound" + +let copyright = "Copyright (c) 2020 The OpenTK Team." + +let solutionFile = "OpenTK.sln" + +let gitOwner = "opentk" + +let gitHome = "https://github.com/" + gitOwner + +// The name of the project on GitHub +let gitName = "objecttk" + +// The url for the raw files hosted +let gitRaw = Environment.environVarOrDefault "gitRaw" "https://raw.github.com/objecttk" + +// Read additional information from the release notes document +let release = ReleaseNotes.load "RELEASE_NOTES.md" + +// --------- +// Properties +// --------- + +let binDir = "./bin/" +let buildDir = binDir </> "build" +let nugetDir = binDir </> "nuget" +let testDir = binDir </> "test" + +// --------- +// Projects & Assemblies +// --------- + + +let releaseProjects = + !! "src/ObjectTK.Core/*.??proj" + ++ "src/ObjectTK.2D/*.??proj" + + +// Absolutely all test projects. +let allTestProjects = + !! "tests/**/*.??proj" + +// Test projects excluding integration tests (don't run on CI). +let ciTestProjects = + allTestProjects + -- "tests/**/*.Integration.??proj" + +let nugetCommandRunnerPath = + ".fake/build.fsx/packages/NuGet.CommandLine/tools/NuGet.exe" |> Fake.IO.Path.convertWindowsToCurrentPath + +// --------- +// Other Targets +// --------- + +// Lazily install DotNet SDK in the correct version if not available +let install = + lazy + (if (DotNet.getVersion id).StartsWith "3" then id + else DotNet.install (fun options -> { options with Version = DotNet.Version "3.1.100" })) + +// Define general properties across various commands (with arguments) +let inline withWorkDir wd = DotNet.Options.lift install.Value >> DotNet.Options.withWorkingDirectory wd + +// Set general properties without arguments +let inline dotnetSimple arg = DotNet.Options.lift install.Value arg + +module DotNet = + let run optionsFn framework projFile args = + DotNet.exec (dotnetSimple >> optionsFn) "run" (sprintf "-f %s -p \"%s\" %s" framework projFile args) + + let runWithDefaultOptions framework projFile args = run id framework projFile args + +let asArgs args = args |> String.concat " " + +// --------- +// Build Targets +// --------- + +Target.create "Clean" <| fun _ -> + !! ("./src" </> "OpenTK.Graphics" </> "**/*.*") + ++ (nugetDir </> "*.nupkg") + -- ("./src" </> "OpenTK.Graphics" </> "Enums/*.cs") + -- ("./src" </> "OpenTK.Graphics" </> "*.cs") + -- ("./src" </> "OpenTK.Graphics" </> "*.csproj") + -- ("./src" </> "OpenTK.Graphics" </> "ES11/Helper.cs") + -- ("./src" </> "OpenTK.Graphics" </> "ES20/Helper.cs") + -- ("./src" </> "OpenTK.Graphics" </> "ES30/Helper.cs") + -- ("./src" </> "OpenTK.Graphics" </> "OpenGL2/Helper.cs") + -- ("./src" </> "OpenTK.Graphics" </> "OpenGL4/Helper.cs") + -- ("./src" </> "OpenTK.Graphics" </> "paket") + |> Seq.iter(Shell.rm) + +Target.create "Restore" (fun _ -> DotNet.restore dotnetSimple "ObjectTK.sln" |> ignore) + +Target.create "Build"( fun _ -> + let setOptions a = + let customParams = sprintf "/p:DontGenBindings=true/p:PackageVersion=%s/p:ProductVersion=%s" release.AssemblyVersion release.NugetVersion + DotNet.Options.withCustomParams (Some customParams) (dotnetSimple a) + + for proj in releaseProjects do + DotNet.build setOptions proj + ) + +open System.IO + +Target.create "CreateNuGetPackage" (fun _ -> + Directory.CreateDirectory nugetDir |> ignore + let notes = release.Notes |> List.reduce (fun s1 s2 -> s1 + "\n" + s2) + + for proj in releaseProjects do + Trace.logf "Creating nuget package for Project: %s" proj + + let dir = Path.GetDirectoryName proj + let templatePath = Path.Combine(dir, "paket") + let oldTmplCont = File.ReadAllText templatePath + let newTmplCont = oldTmplCont.Insert(oldTmplCont.Length, sprintf "\nversion \n\t%s\nauthors \n\t%s\nowners \n\t%s\n" + release.NugetVersion + (authors |> List.reduce (fun s a -> s + " " + a)) + (authors |> List.reduce (fun s a -> s + " " + a))).Replace("#VERSION#", release.NugetVersion) + File.WriteAllText(templatePath + ".template", newTmplCont) + let setParams (p:Paket.PaketPackParams) = + { p with + ReleaseNotes = notes + OutputPath = Path.GetFullPath(nugetDir) + WorkingDir = dir + Version = release.NugetVersion + } + Paket.pack setParams + ) + +Target.create "CreateMetaPackage" (fun _ -> + let notes = release.Notes |> List.reduce (fun s1 s2 -> s1 + "\n" + s2) + + let deps = + releaseProjects + |> Seq.toList + |> List.map (fun p -> Path.GetFileNameWithoutExtension(p), release.NugetVersion) + + let setParams (p:NuGet.NuGetParams) = + { p with + Version = release.NugetVersion + Authors = authors + Project = project + Dependencies = deps + Summary = summary + Description = description + Copyright = copyright + WorkingDir = binDir + OutputPath = nugetDir +// AccessKey = myAccessKey + Publish = false + ReleaseNotes = notes + Tags = tags + Properties = [ + "Configuration", Environment.environVarOrDefault "buildMode" "Release" + ] + } + Trace.logf "Creating metapackage from objecttk.nuspec" + NuGet.NuGet setParams "objecttk.nuspec" + ) + +// --------- +// Release Targets +// --------- + +open Fake.Api + +Target.create "ReleaseOnGitHub" (fun _ -> + let token = + match Environment.environVarOrDefault "opentk_github_token" "" with + | s when not (System.String.IsNullOrWhiteSpace s) -> s + | _ -> + failwith + "please set the github_token environment variable to a github personal access token with repro access." + + let files = !!"bin/*" |> Seq.toList + + GitHub.createClientWithToken token + |> GitHub.draftNewRelease gitOwner gitName release.NugetVersion (release.SemVer.PreRelease <> None) release.Notes + //|> GitHub.uploadFiles files + |> GitHub.publishDraft + |> Async.RunSynchronously) + +Target.create "ReleaseOnNuGet" (fun _ -> + let apiKey = + match Environment.environVarOrDefault "opentk_nuget_api_key" "" with + | s when not (System.String.IsNullOrWhiteSpace s) -> s + | _ -> failwith "please set the nuget_api_key environment variable to a nuget access token." + + !! (nugetDir </> "*.nupkg") + |> Seq.iter + (DotNet.nugetPush (fun opts -> + { opts with + PushParams = + { opts.PushParams with + ApiKey = Some apiKey + Source = Some "nuget.org" } }))) + +Target.create "ReleaseOnAll" ignore + +// --------- +// Target relations +// --------- + +Target.create "All" ignore + +open Fake.Core.TargetOperators + +"Clean" + ==> "Restore" + ==> "Build" + ==> "All" + ==> "CreateNuGetPackage" + ==> "CreateMetaPackage" + ==> "ReleaseOnNuGet" + ==> "ReleaseOnGithub" + ==> "ReleaseOnAll" + +// --------- +// Startup +// --------- + +// Run all targets by default. Invoke 'build <Target>' to override +Target.runOrDefault "All" diff --git a/build.fsx.lock b/build.fsx.lock new file mode 100644 index 0000000..e7c4796 --- /dev/null +++ b/build.fsx.lock @@ -0,0 +1,326 @@ +STORAGE: PACKAGES +RESTRICTION: == netstandard2.0 +NUGET + remote: https://api.nuget.org/v3/index.json + BlackFox.VsWhere (1.1) + FSharp.Core (>= 4.2.3) + Microsoft.Win32.Registry (>= 4.7) + Fake.Api.Github (5.20.3) + FSharp.Core (>= 4.7.2) + Octokit (>= 0.48) + Fake.Core.CommandLineParsing (5.20.3) + FParsec (>= 1.1.1) + FSharp.Core (>= 4.7.2) + Fake.Core.Context (5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.Environment (5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.FakeVar (5.20.3) + Fake.Core.Context (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.Process (5.20.3) + Fake.Core.Environment (>= 5.20.3) + Fake.Core.FakeVar (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + Fake.IO.FileSystem (>= 5.20.3) + FSharp.Core (>= 4.7.2) + System.Collections.Immutable (>= 1.7.1) + Fake.Core.ReleaseNotes (5.20.3) + Fake.Core.SemVer (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.SemVer (5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.String (5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.Target (5.20.3) + Fake.Core.CommandLineParsing (>= 5.20.3) + Fake.Core.Context (>= 5.20.3) + Fake.Core.Environment (>= 5.20.3) + Fake.Core.FakeVar (>= 5.20.3) + Fake.Core.Process (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + FSharp.Control.Reactive (>= 4.4.2) + FSharp.Core (>= 4.7.2) + Fake.Core.Tasks (5.20.3) + Fake.Core.Trace (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.Trace (5.20.3) + Fake.Core.Environment (>= 5.20.3) + Fake.Core.FakeVar (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Core.Xml (5.20.3) + Fake.Core.String (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.DotNet.AssemblyInfoFile (5.20.3) + Fake.Core.Environment (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + Fake.IO.FileSystem (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.DotNet.Cli (5.20.3) + Fake.Core.Environment (>= 5.20.3) + Fake.Core.Process (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + Fake.DotNet.MSBuild (>= 5.20.3) + Fake.DotNet.NuGet (>= 5.20.3) + Fake.IO.FileSystem (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Mono.Posix.NETStandard (>= 1.0) + Newtonsoft.Json (>= 12.0.3) + Fake.DotNet.MSBuild (5.20.3) + BlackFox.VsWhere (>= 1.1) + Fake.Core.Environment (>= 5.20.3) + Fake.Core.Process (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + Fake.IO.FileSystem (>= 5.20.3) + FSharp.Core (>= 4.7.2) + MSBuild.StructuredLogger (>= 2.1.176) + Fake.DotNet.NuGet (5.20.3) + Fake.Core.Environment (>= 5.20.3) + Fake.Core.Process (>= 5.20.3) + Fake.Core.SemVer (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Tasks (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + Fake.Core.Xml (>= 5.20.3) + Fake.IO.FileSystem (>= 5.20.3) + Fake.Net.Http (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Newtonsoft.Json (>= 12.0.3) + NuGet.Protocol (>= 5.6) + Fake.DotNet.Paket (5.20.3) + Fake.Core.Process (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + Fake.DotNet.Cli (>= 5.20.3) + Fake.IO.FileSystem (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.DotNet.Testing.XUnit2 (5.20.3) + Fake.Core.Process (>= 5.20.3) + Fake.Core.String (>= 5.20.3) + Fake.Core.Trace (>= 5.20.3) + Fake.IO.FileSystem (>= 5.20.3) + Fake.Testing.Common (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.IO.FileSystem (5.20.3) + Fake.Core.String (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Net.Http (5.20.3) + Fake.Core.Trace (>= 5.20.3) + FSharp.Core (>= 4.7.2) + Fake.Testing.Common (5.20.3) + Fake.Core.Trace (>= 5.20.3) + FSharp.Core (>= 4.7.2) + FParsec (1.1.1) + FSharp.Core (>= 4.3.4) + FSharp.Control.Reactive (4.4.2) + FSharp.Core (>= 4.7.2) + System.Reactive (>= 4.4.1) + FSharp.Core (5.0) + Microsoft.Build (16.7) + Microsoft.Build.Framework (16.7) + System.Security.Permissions (>= 4.7) + Microsoft.Build.Tasks.Core (16.7) + Microsoft.Build.Framework (>= 16.7) + Microsoft.Build.Utilities.Core (>= 16.7) + Microsoft.Win32.Registry (>= 4.3) + System.CodeDom (>= 4.4) + System.Collections.Immutable (>= 1.5) + System.Reflection.Metadata (>= 1.6) + System.Reflection.TypeExtensions (>= 4.1) + System.Resources.Extensions (>= 4.6) + System.Security.Permissions (>= 4.7) + System.Threading.Tasks.Dataflow (>= 4.9) + Microsoft.Build.Utilities.Core (16.7) + Microsoft.Build.Framework (>= 16.7) + Microsoft.Win32.Registry (>= 4.3) + System.Collections.Immutable (>= 1.5) + System.Security.Permissions (>= 4.7) + System.Text.Encoding.CodePages (>= 4.0.1) + Microsoft.NETCore.Platforms (5.0) + Microsoft.NETCore.Targets (5.0) + Microsoft.Win32.Registry (5.0) + System.Buffers (>= 4.5.1) + System.Memory (>= 4.5.4) + System.Security.AccessControl (>= 5.0) + System.Security.Principal.Windows (>= 5.0) + Mono.Posix.NETStandard (1.0) + MSBuild.StructuredLogger (2.1.215) + Microsoft.Build (>= 16.4) + Microsoft.Build.Framework (>= 16.4) + Microsoft.Build.Tasks.Core (>= 16.4) + Microsoft.Build.Utilities.Core (>= 16.4) + Newtonsoft.Json (12.0.3) + NuGet.CommandLine (5.7) + NuGet.Common (5.8) + NuGet.Frameworks (>= 5.8) + NuGet.Configuration (5.8) + NuGet.Common (>= 5.8) + System.Security.Cryptography.ProtectedData (>= 4.4) + NuGet.Frameworks (5.8) + NuGet.Packaging (5.7) + Newtonsoft.Json (>= 9.0.1) + NuGet.Configuration (>= 5.7) + NuGet.Versioning (>= 5.7) + System.Dynamic.Runtime (>= 4.3) + System.Security.Cryptography.Cng (>= 5.0.0-preview.3.20214.6) + System.Security.Cryptography.Pkcs (>= 5.0.0-preview.3.20214.6) + NuGet.Protocol (5.7) + NuGet.Packaging (>= 5.7) + System.Dynamic.Runtime (>= 4.3) + NuGet.Versioning (5.8) + Octokit (0.48) + System.Buffers (4.5.1) + System.CodeDom (5.0) + System.Collections (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Runtime (>= 4.3) + System.Collections.Immutable (5.0) + System.Memory (>= 4.5.4) + System.Diagnostics.Debug (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Runtime (>= 4.3) + System.Dynamic.Runtime (4.3) + System.Collections (>= 4.3) + System.Diagnostics.Debug (>= 4.3) + System.Linq (>= 4.3) + System.Linq.Expressions (>= 4.3) + System.ObjectModel (>= 4.3) + System.Reflection (>= 4.3) + System.Reflection.Emit (>= 4.3) + System.Reflection.Emit.ILGeneration (>= 4.3) + System.Reflection.Primitives (>= 4.3) + System.Reflection.TypeExtensions (>= 4.3) + System.Resources.ResourceManager (>= 4.3) + System.Runtime (>= 4.3) + System.Runtime.Extensions (>= 4.3) + System.Threading (>= 4.3) + System.Formats.Asn1 (5.0) + System.Buffers (>= 4.5.1) + System.Memory (>= 4.5.4) + System.Globalization (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Runtime (>= 4.3) + System.IO (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Runtime (>= 4.3) + System.Text.Encoding (>= 4.3) + System.Threading.Tasks (>= 4.3) + System.Linq (4.3) + System.Collections (>= 4.3) + System.Diagnostics.Debug (>= 4.3) + System.Resources.ResourceManager (>= 4.3) + System.Runtime (>= 4.3) + System.Runtime.Extensions (>= 4.3) + System.Linq.Expressions (4.3) + System.Collections (>= 4.3) + System.Diagnostics.Debug (>= 4.3) + System.Globalization (>= 4.3) + System.IO (>= 4.3) + System.Linq (>= 4.3) + System.ObjectModel (>= 4.3) + System.Reflection (>= 4.3) + System.Reflection.Emit (>= 4.3) + System.Reflection.Emit.ILGeneration (>= 4.3) + System.Reflection.Emit.Lightweight (>= 4.3) + System.Reflection.Extensions (>= 4.3) + System.Reflection.Primitives (>= 4.3) + System.Reflection.TypeExtensions (>= 4.3) + System.Resources.ResourceManager (>= 4.3) + System.Runtime (>= 4.3) + System.Runtime.Extensions (>= 4.3) + System.Threading (>= 4.3) + System.Memory (4.5.4) + System.Buffers (>= 4.5.1) + System.Numerics.Vectors (>= 4.4) + System.Runtime.CompilerServices.Unsafe (>= 4.5.3) + System.Numerics.Vectors (4.5) + System.ObjectModel (4.3) + System.Collections (>= 4.3) + System.Diagnostics.Debug (>= 4.3) + System.Resources.ResourceManager (>= 4.3) + System.Runtime (>= 4.3) + System.Threading (>= 4.3) + System.Reactive (4.4.1) + System.Runtime.InteropServices.WindowsRuntime (>= 4.3) + System.Threading.Tasks.Extensions (>= 4.5.4) + System.Reflection (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.IO (>= 4.3) + System.Reflection.Primitives (>= 4.3) + System.Runtime (>= 4.3) + System.Reflection.Emit (4.7) + System.Reflection.Emit.ILGeneration (>= 4.7) + System.Reflection.Emit.ILGeneration (4.7) + System.Reflection.Emit.Lightweight (4.7) + System.Reflection.Emit.ILGeneration (>= 4.7) + System.Reflection.Extensions (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Reflection (>= 4.3) + System.Runtime (>= 4.3) + System.Reflection.Metadata (5.0) + System.Collections.Immutable (>= 5.0) + System.Reflection.Primitives (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Runtime (>= 4.3) + System.Reflection.TypeExtensions (4.7) + System.Resources.Extensions (5.0) + System.Memory (>= 4.5.4) + System.Resources.ResourceManager (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Globalization (>= 4.3) + System.Reflection (>= 4.3) + System.Runtime (>= 4.3) + System.Runtime (4.3.1) + Microsoft.NETCore.Platforms (>= 1.1.1) + Microsoft.NETCore.Targets (>= 1.1.3) + System.Runtime.CompilerServices.Unsafe (5.0) + System.Runtime.Extensions (4.3.1) + Microsoft.NETCore.Platforms (>= 1.1.1) + Microsoft.NETCore.Targets (>= 1.1.3) + System.Runtime (>= 4.3.1) + System.Runtime.InteropServices.WindowsRuntime (4.3) + System.Runtime (>= 4.3) + System.Security.AccessControl (5.0) + System.Security.Principal.Windows (>= 5.0) + System.Security.Cryptography.Cng (5.0) + System.Security.Cryptography.Pkcs (5.0) + System.Buffers (>= 4.5.1) + System.Formats.Asn1 (>= 5.0) + System.Memory (>= 4.5.4) + System.Security.Cryptography.Cng (>= 5.0) + System.Security.Cryptography.ProtectedData (5.0) + System.Memory (>= 4.5.4) + System.Security.Permissions (5.0) + System.Security.AccessControl (>= 5.0) + System.Security.Principal.Windows (5.0) + System.Text.Encoding (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Runtime (>= 4.3) + System.Text.Encoding.CodePages (5.0) + System.Runtime.CompilerServices.Unsafe (>= 5.0) + System.Threading (4.3) + System.Runtime (>= 4.3) + System.Threading.Tasks (>= 4.3) + System.Threading.Tasks (4.3) + Microsoft.NETCore.Platforms (>= 1.1) + Microsoft.NETCore.Targets (>= 1.1) + System.Runtime (>= 4.3) + System.Threading.Tasks.Dataflow (5.0) + System.Threading.Tasks.Extensions (4.5.4) + System.Runtime.CompilerServices.Unsafe (>= 4.5.3) + xunit.runner.console (2.4.1) diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..8e0c9e2 --- /dev/null +++ b/build.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +set -e -o + +function version_compare() { + ver1=(${1//./ }) + ver2=(${2//./ }) + + len1=${#ver1[@]} + len2=${#ver2[@]} + + vlen=$(($len1 < $len2 ? $len1 : $len2)) + + for ((i=0;i<vlen;i++)) + do + if [ ${ver1[$i]} -gt ${ver2[$i]} ]; then + return 1 + fi + done + return 0 +} + +MINIMAL_DOTNET_VERSION=3.1.100 + +EXIT_CODE=0 + +CURRENT_DOTNET_VERSION=$(dotnet --version 2> /dev/null) || EXIT_CODE=$? + +if (($EXIT_CODE == 0)) && version_compare "$MINIMAL_DOTNET_VERSION" "$CURRENT_DOTNET_VERSION"; then + echo "dotnet command already installed" +else + # Install .NET Core (https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-install-script) + curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --version 3.1.100 + + PATH="~/.dotnet:$PATH" +fi + +dotnet tool restore +dotnet fake run build.fsx $@ \ No newline at end of file diff --git a/objectTK.nuspec b/objectTK.nuspec new file mode 100644 index 0000000..580e9aa --- /dev/null +++ b/objectTK.nuspec @@ -0,0 +1,16 @@ +<?xml version="1.0"?> +<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> + <metadata> + <id>ObjectTK</id> + <version>1</version> + <copyright>@copyright@</copyright> + <tags>@tags@</tags> + <description>@description@</description> + <authors>@authors@</authors> + <releaseNotes>@releaseNotes@</releaseNotes> + <projectUrl>https://github.com/opentk/opentk</projectUrl> + <license type="expression">MIT</license> + <iconUrl>https://api.nuget.org/v3-flatcontainer/opentk/3.1.0/icon</iconUrl> + @dependencies@ + </metadata> +</package> diff --git a/packages/repositories.config b/packages/repositories.config deleted file mode 100644 index bb8e188..0000000 --- a/packages/repositories.config +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<repositories> - <repository path="..\Examples\packages.config" /> - <repository path="..\ObjectTK.Compiler\packages.config" /> - <repository path="..\ObjectTK.Tools\packages.config" /> - <repository path="..\ObjectTK\packages.config" /> -</repositories> \ No newline at end of file diff --git a/paket.dependencies b/paket.dependencies new file mode 100644 index 0000000..8843b6a --- /dev/null +++ b/paket.dependencies @@ -0,0 +1,7 @@ +framework: netcoreapp3.1 + +source https://api.nuget.org/v3/index.json + +// open packages +nuget FAKE ~> 4.62 +nuget OpenTK >= 4.1 \ No newline at end of file diff --git a/paket.lock b/paket.lock new file mode 100644 index 0000000..1db978f --- /dev/null +++ b/paket.lock @@ -0,0 +1,36 @@ +RESTRICTION: == netcoreapp3.1 +NUGET + remote: https://api.nuget.org/v3/index.json + FAKE (4.64.18) + OpenTK (4.1) + OpenTK.Compute (>= 4.1) + OpenTK.Core (>= 4.1) + OpenTK.Graphics (>= 4.1) + OpenTK.Input (>= 4.1) + OpenTK.Mathematics (>= 4.1) + OpenTK.OpenAL (>= 4.1) + OpenTK.Windowing.Common (>= 4.1) + OpenTK.Windowing.Desktop (>= 4.1) + OpenTK.Windowing.GraphicsLibraryFramework (>= 4.1) + OpenTK.Compute (4.1) + OpenTK.Core (4.1) + OpenTK.Graphics (4.1) + OpenTK.Core (>= 4.1 < 4.2) + OpenTK.Mathematics (>= 4.1 < 4.2) + OpenTK.Input (4.1) + OpenTK.Mathematics (4.1) + OpenTK.OpenAL (4.1) + OpenTK.Core (>= 4.1 < 4.2) + OpenTK.Mathematics (>= 4.1 < 4.2) + OpenTK.redist.glfw (3.3.0-pre20200830200122) + OpenTK.Windowing.Common (4.1) + OpenTK.Core (>= 4.1 < 4.2) + OpenTK.Mathematics (>= 4.1 < 4.2) + OpenTK.Windowing.Desktop (4.1) + OpenTK.Core (>= 4.1 < 4.2) + OpenTK.Mathematics (>= 4.1 < 4.2) + OpenTK.Windowing.Common (>= 4.1 < 4.2) + OpenTK.Windowing.GraphicsLibraryFramework (>= 4.1 < 4.2) + OpenTK.Windowing.GraphicsLibraryFramework (4.1) + OpenTK.Core (>= 4.1 < 4.2) + OpenTK.redist.glfw (>= 3.3.0-pre20200830200122 < 3.4.0-pre) diff --git a/Examples/Data/Shaders/ExampleShader.glsl b/src/Examples/Data/Shaders/BasicShader.glsl similarity index 76% rename from Examples/Data/Shaders/ExampleShader.glsl rename to src/Examples/Data/Shaders/BasicShader.glsl index 2f68514..f415ada 100644 --- a/Examples/Data/Shaders/ExampleShader.glsl +++ b/src/Examples/Data/Shaders/BasicShader.glsl @@ -1,8 +1,8 @@ --- Version +-- Version #version 140 -- Vertex -#include ExampleShader.Version +#include BasicShader.Version in vec3 InPosition; uniform mat4 ModelViewProjectionMatrix; @@ -12,7 +12,7 @@ void main() } -- Fragment -#include ExampleShader.Version +#include BasicShader.Version out vec4 FragColor; void main() diff --git a/src/Examples/Entry.cs b/src/Examples/Entry.cs new file mode 100644 index 0000000..6cd3b01 --- /dev/null +++ b/src/Examples/Entry.cs @@ -0,0 +1,45 @@ +using System; +using System.Linq; +using System.Reflection; +using Examples.Examples; +using OpenTK.Windowing.Desktop; + +namespace Examples { + internal class Entry { + private static void Main(string[] args) { + using var gw = new HelloTriangle(); + gw.Run(); + // + // var Examples = Assembly.GetExecutingAssembly().GetTypes() + // .Where(_ => _ != typeof(ExampleWindow) && typeof(ExampleWindow).IsAssignableFrom(_)) + // .Select(Type => + // new { + // Caption = Type.GetCustomAttributes<ExampleProjectAttribute>(false).FirstOrDefault()?.Caption ?? nameof(Type), Type + // }).ToArray(); + // + // while (PromptForExample(out var Example)) { + // using (var ExampleWindow = (GameWindow) Activator.CreateInstance(Example)) { + // ExampleWindow.Run(); + // } + // } + // + // bool PromptForExample(out Type Example) { + // Example = null; + // var Count = 1; + // Console.WriteLine("Select example: "); + // + // foreach (var Pair in Examples) { + // Console.WriteLine($"{Count++} - {Pair.Caption}"); + // } + // + // var input = Console.ReadLine(); + // if (int.TryParse(input, out var Selection) && Selection - 1 >= 0 && Selection - 1 < Examples.Length) { + // Example = Examples[Selection - 1].Type; + // return true; + // } + // + // return false; + // } + } + } +} diff --git a/src/Examples/ExampleProjectAttribute.cs b/src/Examples/ExampleProjectAttribute.cs new file mode 100644 index 0000000..db196d5 --- /dev/null +++ b/src/Examples/ExampleProjectAttribute.cs @@ -0,0 +1,11 @@ +using System; + +namespace Examples { + [AttributeUsage(AttributeTargets.Class)] + public class ExampleProjectAttribute : Attribute { + public readonly string Caption; + public ExampleProjectAttribute(string Caption) { + this.Caption = Caption; + } + } +} diff --git a/src/Examples/ExampleWindow.cs b/src/Examples/ExampleWindow.cs new file mode 100644 index 0000000..22f0c91 --- /dev/null +++ b/src/Examples/ExampleWindow.cs @@ -0,0 +1,69 @@ +using ObjectTK.Tools; +using OpenTK.Mathematics; +using OpenTK.Windowing.Common; +using OpenTK.Windowing.Desktop; +using OpenTK.Windowing.GraphicsLibraryFramework; +using System; + +namespace Examples { + public class ExampleWindow : CameraWindow { + private string OriginalTitle { get; set; } + + private float CameraPitch { get; set; } = 0; + private float CameraYaw { get; set; } = (float)Math.PI; + + public ExampleWindow() : base(800, 600, "ExampleWindow") { + + } + + protected override void OnLoad() { + base.OnLoad(); + // maximize window + WindowState = WindowState.Maximized; + // remember original title + OriginalTitle = Title; + + ActiveCamera.Rotation = Quaternion.FromAxisAngle(Vector3.UnitY, CameraYaw) * Quaternion.FromAxisAngle(Vector3.UnitX, CameraPitch); + + } + + protected override void OnRenderFrame(FrameEventArgs e) { + base.OnRenderFrame(e); + // display FPS in the window title + Title = string.Format("ObjectTK example: {0} - FPS {1}", OriginalTitle, FrameTimer.FpsBasedOnFramesRendered); + } + + protected override void OnUpdateFrame(FrameEventArgs e) { + base.OnUpdateFrame(e); + HandleCameraInput((float)e.Time); + } + + private void HandleCameraInput(float DeltaSeconds) { + Vector3 Direction = Vector3.Zero; + if (KeyboardState.IsKeyDown(Keys.W)) Direction += ActiveCamera.Forward; + if (KeyboardState.IsKeyDown(Keys.S)) Direction -= ActiveCamera.Forward; + if (KeyboardState.IsKeyDown(Keys.D)) Direction += ActiveCamera.Right; + if (KeyboardState.IsKeyDown(Keys.A)) Direction -= ActiveCamera.Right; + if (KeyboardState.IsKeyDown(Keys.Space)) Direction += ActiveCamera.Up; + if (KeyboardState.IsKeyDown(Keys.LeftControl)) Direction -= ActiveCamera.Up; + if (Direction.LengthSquared > 0) ActiveCamera.Position += Direction.Normalized() * DeltaSeconds; + } + + protected override void OnKeyDown(KeyboardKeyEventArgs e) { + base.OnKeyDown(e); + if (e.Key == Keys.Escape) Close(); + } + + + protected override void OnMouseMove(MouseMoveEventArgs e) { + base.OnMouseMove(e); + if (MouseState.IsButtonDown(MouseButton.Button2)) { + CameraPitch -= e.DeltaY * 0.005f; + CameraPitch = Math.Clamp(CameraPitch, -MathHelper.PiOver2, MathHelper.PiOver2); + CameraYaw += e.DeltaX * 0.005f; + ActiveCamera.Rotation = Quaternion.FromAxisAngle(-Vector3.UnitY, CameraYaw) * Quaternion.FromAxisAngle(-Vector3.UnitX, CameraPitch); + } + } + + } +} \ No newline at end of file diff --git a/src/Examples/Examples.csproj b/src/Examples/Examples.csproj new file mode 100644 index 0000000..79f5b38 --- /dev/null +++ b/src/Examples/Examples.csproj @@ -0,0 +1,21 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>netcoreapp3.1</TargetFramework> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\ObjectTK.2D\ObjectTK.2D.csproj" /> + <ProjectReference Include="..\ObjectTK.Core\ObjectTK.Core.csproj" /> + <ProjectReference Include="..\ObjectTK.Extensions\ObjectTK.Extensions.csproj" /> + <ProjectReference Include="..\ObjectTK.Tools\ObjectTK.Tools.csproj" /> + </ItemGroup> + + <ItemGroup> + <None Update="Data\Shaders\BasicShader.glsl"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + +</Project> diff --git a/src/Examples/Examples/ExtensionPrograms/BasicProgram.cs b/src/Examples/Examples/ExtensionPrograms/BasicProgram.cs new file mode 100644 index 0000000..ef2aee9 --- /dev/null +++ b/src/Examples/Examples/ExtensionPrograms/BasicProgram.cs @@ -0,0 +1,15 @@ +using ObjectTK.Extensions.Shaders; +using ObjectTK.Extensions.Variables; +using ObjectTK.GLObjects; +using OpenTK.Mathematics; + +namespace Examples.Examples.Programs { + [VertexShaderSource("BasicShader.Vertex")] + [FragmentShaderSource("BasicShader.Fragment")] + public class BasicProgram { + [VertexAttrib()] + public ShaderAttributeInfo InPosition { get; set; } + + public ShaderUniformInfo<Matrix4> ModelViewProjectionMatrix { get; set; } + } +} \ No newline at end of file diff --git a/src/Examples/Examples/HelloTriangle.cs b/src/Examples/Examples/HelloTriangle.cs new file mode 100644 index 0000000..d2ec1b5 --- /dev/null +++ b/src/Examples/Examples/HelloTriangle.cs @@ -0,0 +1,112 @@ +using System.Drawing; +using ObjectTK; +using ObjectTK._2D; +using ObjectTK.GLObjects; +using OpenTK.Graphics.OpenGL; +using OpenTK.Mathematics; +using OpenTK.Windowing.Common; +using OpenTK.Windowing.Desktop; + +namespace Examples.Examples { + internal static class ShaderSource { + public const string Vertex = @" + #version 330 core + + uniform mat4 ModelViewProjectionMatrix; + + layout(location = 0) in vec3 InPosition; + layout(location = 1) in vec4 InColor; + + + out vec4 VColor; + + void main(void) { + gl_Position = ModelViewProjectionMatrix * vec4(InPosition, 1.0); + VColor = InColor; + } + "; + + public const string Fragment = @" + #version 330 + + in vec4 VColor; + + out vec4 FragColor; + + void main() + { + FragColor = VColor; + } + "; + } + + [ExampleProject("Hello Triangle")] + public sealed class HelloTriangle : GameWindow { + + private static readonly NativeWindowSettings WindowSettings = new NativeWindowSettings { + Size = new Vector2i(800, 600), + Title = "Hello Triangle (Basic)", + }; + private static readonly GameWindowSettings GameWindowSettings = new GameWindowSettings(); + + private ShaderProgram _shaderProgram; + private VertexArray _vao; + private Buffer<Vector3> _positionsVbo; + private Buffer<Color4> _colorsVbo; + private readonly Camera2D _camera = new Camera2D(); + + public HelloTriangle() + : base(GameWindowSettings, WindowSettings) { + } + + protected override void OnLoad() { + base.OnLoad(); + + // create the shader program + _shaderProgram = GLFactory.Shader.VertexFrag("Vertex Color", ShaderSource.Vertex, ShaderSource.Fragment); + + // create the triangle to draw + var positions = new[] {new Vector3(-1, -1, 0), new Vector3(1, -1, 0), new Vector3(0, 1, 0)}; + var colors = new[] {Color4.Cornsilk, Color4.OrangeRed, Color4.DarkOliveGreen}; + + _positionsVbo = GLFactory.Buffer.ArrayBuffer("Positions", positions); + _colorsVbo = GLFactory.Buffer.ArrayBuffer("Colors", colors); + _vao = GLFactory.VertexArray.FromBuffers("Triangle", _positionsVbo, _colorsVbo); + + } + + protected override void OnRenderFrame(FrameEventArgs e) { + base.OnRenderFrame(e); + // set up the viewport and camera (if the screen size has changed). + GL.Viewport(0, 0, Size.X, Size.Y); + _camera.AspectRatio = (float) Size.X / Size.Y; + + // clear the screen + GL.ClearColor(Color.MidnightBlue); + GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); + + + // set up the shader and the uniforms + GL.UseProgram(_shaderProgram.Handle); + var mvpMatrix = _camera.ViewProjection; + GL.UniformMatrix4(_shaderProgram.Uniforms["ModelViewProjectionMatrix"].Location, false, ref mvpMatrix); + + // draw the triangle + GL.BindVertexArray(_vao.Handle); + GL.DrawArrays(PrimitiveType.Triangles, 0, _vao.ElementCount); + GL.BindVertexArray(0); + + // swap to display on the screen + SwapBuffers(); + } + + protected override void OnUnload() { + base.OnUnload(); + + GL.DeleteProgram(_shaderProgram.Handle); + GL.DeleteVertexArray(_vao.Handle); + GL.DeleteBuffer(_positionsVbo.Handle); + } + } +} + diff --git a/src/Examples/Examples/HelloTriangleWithExtensions.cs b/src/Examples/Examples/HelloTriangleWithExtensions.cs new file mode 100644 index 0000000..e8754dd --- /dev/null +++ b/src/Examples/Examples/HelloTriangleWithExtensions.cs @@ -0,0 +1,68 @@ +using System; +using System.Drawing; +using Examples.Examples.Programs; +using ObjectTK; +using ObjectTK.Extensions.Buffers; +using ObjectTK.Extensions.Shaders; +using ObjectTK.Extensions.Variables; +using ObjectTK.GLObjects; +using OpenTK.Graphics.OpenGL; +using OpenTK.Mathematics; +using OpenTK.Windowing.Common; + +namespace Examples.Examples { + [ExampleProject("Hello Triangle with extensions")] + public class HelloTriangleWithExtensions : ExampleWindow { + + private ShaderProgram<BasicProgram> ShaderProgram; + private Buffer<Vector3> VBO; + private VertexArray VAO; + + protected override void OnLoad() { + base.OnLoad(); + + ShaderProgram = new ProgramFactory() { BaseDirectory = "./Data/Shaders/" }.CreateProgram<BasicProgram>(); + ShaderProgram.Use(); + + var Vertices = new[] { new Vector3(-1, -1, 0), new Vector3(1, -1, 0), new Vector3(0, 1, 0) }; + + VBO = new Buffer<Vector3>("Positions", GL.GenBuffer(), 0); + VBO.BufferData(BufferTarget.ArrayBuffer, Vertices); + + VAO = new VertexArray("Triangle", GL.GenVertexArray(), Vertices.Length,false); + VAO.BindVertexAttribute(ShaderProgram.Variables.InPosition, VBO); + + ActiveCamera.Position = new Vector3(0, 0, 3); + + GL.ClearColor(Color.MidnightBlue); + } + + private void OnUnload(object sender, EventArgs e) { + base.OnUnload(); + + GL.DeleteProgram(ShaderProgram.Handle); + GL.DeleteVertexArray(VAO.Handle); + GL.DeleteBuffer(VBO.Handle); + } + + protected override void OnRenderFrame(FrameEventArgs e) { + base.OnRenderFrame(e); + GL.Viewport(0, 0, Size.X, Size.Y); + GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); + + for (int X = 0; X < 20; X++) { + for (int Y = 0; Y < 20; Y++) { + for (int Z = 0; Z < 20; Z++) { + + Matrix4 MVP = Matrix4.CreateTranslation(new Vector3(X * 2, Y * 2, Z * 2)) * ActiveCamera.ViewProjectionMatrix; + ShaderProgram.Variables.ModelViewProjectionMatrix.Set(MVP); + GL.DrawArrays(PrimitiveType.Triangles, 0, VBO.ElementCount); + + } + } + } + + SwapBuffers(); + } + } +} diff --git a/src/ObjectTK.2D/Camera2D.cs b/src/ObjectTK.2D/Camera2D.cs new file mode 100644 index 0000000..9d24c1f --- /dev/null +++ b/src/ObjectTK.2D/Camera2D.cs @@ -0,0 +1,50 @@ +using JetBrains.Annotations; +using OpenTK.Mathematics; + +namespace ObjectTK._2D { + public class Camera2D { + public Transform2D Transform { get; } = new Transform2D(); + + /// The near clipping plane for this camera. + public int NearClip { get; set; } = 1; + + /// The far clipping plane for this camera. + public int FarClip { get; set; } = 100; + + + /// The number of units covered in the vertical of this camera. + public float VerticalSize { get; set; } = 10; + + /// Given by viewport/screen width/height<br/> + /// The aspect ratio of the viewport. This should match the window or viewport's aspect ratio. + /// This is used to derive the horizontal size from the vertical height. + /// <see cref="VerticalSize" /> + public float AspectRatio { get; set; } = 1; + + public Vector2 Position { + get => Transform.Position; + set => Transform.Position = value; + } + + public float Rotation { + get => Transform.Rotation; + set => Transform.Rotation = value; + } + + public float HorizontalSize => VerticalSize * AspectRatio; + + public Matrix4 Projection => Matrix4.CreateOrthographic(HorizontalSize, VerticalSize, NearClip, FarClip); + + public Matrix4 View => Matrix4.CreateRotationZ(Rotation) * Matrix4.CreateTranslation(Position.X, Position.Y, -10); + + public Matrix4 ViewProjection => View * Projection; + + /// 'Zooms in' the camera by a percentage by manipulating the VerticalSize relative to its current value. + /// Zoom delta is expressed in percent: + /// 1.0 = 1%. + /// 100.0 = 100% Zoom. + public void ZoomIn([NotNull] float zoomDelta) { + VerticalSize += zoomDelta * VerticalSize / 100.0f; + } + } +} diff --git a/src/ObjectTK.2D/ObjectTK.2D.csproj b/src/ObjectTK.2D/ObjectTK.2D.csproj new file mode 100644 index 0000000..b5f7d45 --- /dev/null +++ b/src/ObjectTK.2D/ObjectTK.2D.csproj @@ -0,0 +1,20 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>netcoreapp3.1</TargetFramework> + <RootNamespace>ObjectTK._2D</RootNamespace> + </PropertyGroup> + + <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> + <DocumentationFile>bin\Release\ObjectTK.2D.xml</DocumentationFile> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="JetBrains.Annotations" Version="2020.1.0" /> + <PackageReference Include="OpenTK" Version="4.1.0" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\ObjectTK.Core\ObjectTK.Core.csproj" /> + </ItemGroup> +</Project> diff --git a/src/ObjectTK.2D/Transform2D.cs b/src/ObjectTK.2D/Transform2D.cs new file mode 100644 index 0000000..48cf524 --- /dev/null +++ b/src/ObjectTK.2D/Transform2D.cs @@ -0,0 +1,14 @@ +using OpenTK.Mathematics; + +namespace ObjectTK._2D { + public class Transform2D { + + /// The position of this object on the X/Y plane. + public Vector2 Position { get; set; } + /// [DEGREES]. The orientation of this object, clockwise about the Z Axis (through the screen).<br/> + /// 0 degrees = pointing up to the top of the screen.<br/> + /// 90 degrees = pointing to the right of the screen.<br/> + /// etc. + public float Rotation { get; set; } + } +} diff --git a/src/ObjectTK.2D/paket b/src/ObjectTK.2D/paket new file mode 100644 index 0000000..9481fae --- /dev/null +++ b/src/ObjectTK.2D/paket @@ -0,0 +1,8 @@ +type file +id ObjectTK.2D +description + Holds 2D specific parts of ObjectTK. +files + bin\Release\netcoreapp3.1\ObjectTK.2D.dll ==> lib\netcoreapp3.1 + bin\Release\netcoreapp3.1\ObjectTK.2D.xml ==> lib\netcoreapp3.1 + bin\Release\netcoreapp3.1\ObjectTK.2D.pdb ==> lib\netcoreapp3.1 \ No newline at end of file diff --git a/src/ObjectTK.Core/AttributeExtensions.cs b/src/ObjectTK.Core/AttributeExtensions.cs new file mode 100644 index 0000000..f2dea01 --- /dev/null +++ b/src/ObjectTK.Core/AttributeExtensions.cs @@ -0,0 +1,62 @@ +using System; +using OpenTK.Graphics.OpenGL; +using AAT = OpenTK.Graphics.OpenGL.ActiveAttribType; +using VAPT = OpenTK.Graphics.OpenGL.VertexAttribPointerType; + + +namespace ObjectTK { + public static class AttributeExtensions { + + public static VAPT ToVertexAttribPointerType(this AAT attrib) { + switch (attrib) { + // + case AAT.Int: + case AAT.IntVec2: + case AAT.IntVec3: + case AAT.IntVec4: + return VAPT.Int; + // + case AAT.UnsignedInt: + case AAT.UnsignedIntVec2: + case AAT.UnsignedIntVec3: + case AAT.UnsignedIntVec4: + return VAPT.UnsignedInt; + // + case AAT.Float: + case AAT.FloatVec2: + case AAT.FloatVec3: + case AAT.FloatVec4: + case AAT.FloatMat2: + case AAT.FloatMat3: + case AAT.FloatMat4: + case AAT.FloatMat2x3: + case AAT.FloatMat2x4: + case AAT.FloatMat3x2: + case AAT.FloatMat3x4: + case AAT.FloatMat4x2: + case AAT.FloatMat4x3: + return VAPT.Float; + // + case AAT.Double: + case AAT.DoubleMat2: + case AAT.DoubleMat3: + case AAT.DoubleMat4: + case AAT.DoubleMat2x3: + case AAT.DoubleMat2x4: + case AAT.DoubleMat3x2: + case AAT.DoubleMat3x4: + case AAT.DoubleMat4x2: + case AAT.DoubleMat4x3: + case AAT.DoubleVec2: + case AAT.DoubleVec3: + case AAT.DoubleVec4: + return VAPT.Double; + case AAT.None: + throw new ArgumentOutOfRangeException(nameof(attrib), attrib, $"{nameof(ActiveAttribType.None)} does not have a valid conversion."); + default: + throw new ArgumentOutOfRangeException(nameof(attrib), attrib, null); + } + } + + } +} diff --git a/src/ObjectTK.Core/Factories/GLBufferFactory.cs b/src/ObjectTK.Core/Factories/GLBufferFactory.cs new file mode 100644 index 0000000..2098788 --- /dev/null +++ b/src/ObjectTK.Core/Factories/GLBufferFactory.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using JetBrains.Annotations; +using ObjectTK.GLObjects; +using ObjectTK.Internal; +using OpenTK.Graphics.OpenGL; + +// ReSharper disable once CheckNamespace +namespace ObjectTK { + [EditorBrowsable(EditorBrowsableState.Advanced)] + public sealed class GLBufferFactory { + public static GLBufferFactory Instance { get; } = new GLBufferFactory(); + private GLBufferFactory() { } + + // Hide the default members of this object for a cleaner API. + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + // ReSharper disable once BaseObjectEqualsIsObjectEquals + return base.Equals(obj); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode + return base.GetHashCode(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + // ReSharper disable once AnnotateCanBeNullTypeMember + public override string ToString() + { + return base.ToString(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [NotNull] + // ReSharper disable once UnusedMember.Global + public new Type GetType() { + return base.GetType(); + } + + + [NotNull] + [MustUseReturnValue] + public Buffer<T> ArrayBuffer<T>(string name, [NotNull] T[] vertices, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) where T: unmanaged { + var vbo = GL.GenBuffer(); + var label = $"Buffer: {name}"; + GL.BindBuffer(BufferTarget.ArrayBuffer, vbo); + GL.ObjectLabel(ObjectLabelIdentifier.Buffer, vbo,label.Length, label); + int elemSize; + unsafe { + elemSize = sizeof(T); + } + GL.BufferData(BufferTarget.ArrayBuffer, elemSize * vertices.Length, vertices, usageHint); + GL.BindBuffer(BufferTarget.ArrayBuffer, 0); + return new Buffer<T>(name, vbo, vertices.Length); + } + + /// Creates an array buffer from a List. + /// This does not perform any memory copy or allocation, as this directly accesses the internal array used by the list. + /// This has identical performance to the T[] overloads. + [Pure] + [MustUseReturnValue] + public Buffer<T> ArrayBuffer<T>(string name, List<T> list, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) where T : unmanaged { + var arr = list.GetInternalArray(); + return ArrayBuffer(name, arr, usageHint); + } + + /// Creates an array buffer from a List. This matches against the type, trying to find a number of fast-path options.<br></br> + /// If those fast-paths are found, then this does not perform any memory copy or allocation as this directly accesses the internal array used by the list. + /// In this case, this has identical performance to the T[] overloads.<br></br> + /// Supported fast-paths are:<br></br> + /// T[]<br></br> + /// List<T><br></br> + [NotNull] + [MustUseReturnValue] + public Buffer<T> ArrayBuffer<T>(string name, IReadOnlyList<T> list, BufferUsageHint usageHint = BufferUsageHint.StaticDraw) where T : unmanaged { + if (list is T[] arr) { + return ArrayBuffer(name, arr, usageHint); + } + + if (list is List<T> resizeArr) { + return ArrayBuffer(name, resizeArr, usageHint); + } + // slow path, but whatever: + var copy = new T[list.Count]; + for (var i = 0; i < list.Count; i++) { + copy[i] = list[i]; + } + return ArrayBuffer(name, copy, usageHint); + } + } +} diff --git a/src/ObjectTK.Core/Factories/GLShaderFactory.cs b/src/ObjectTK.Core/Factories/GLShaderFactory.cs new file mode 100644 index 0000000..3ecab4f --- /dev/null +++ b/src/ObjectTK.Core/Factories/GLShaderFactory.cs @@ -0,0 +1,48 @@ +using System; +using System.ComponentModel; +using JetBrains.Annotations; +using ObjectTK.GLObjects; +using ObjectTK.Shaders; + +// ReSharper disable once CheckNamespace +namespace ObjectTK { + [EditorBrowsable(EditorBrowsableState.Advanced)] + public sealed class GLShaderFactory { + public static GLShaderFactory Instance { get; } = new GLShaderFactory(); + private GLShaderFactory() { } + + [MustUseReturnValue] + [NotNull] + public ShaderProgram VertexFrag(string name, string vertexSource, string fragSource) { + return ShaderCompiler.VertexFrag(name, vertexSource, fragSource); + } + + // Hide the default members of this object for a cleaner API. + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + // ReSharper disable once BaseObjectEqualsIsObjectEquals + return base.Equals(obj); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode + return base.GetHashCode(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + // ReSharper disable once AnnotateCanBeNullTypeMember + public override string ToString() + { + return base.ToString(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [NotNull] + public new Type GetType() { + return base.GetType(); + } + } +} diff --git a/src/ObjectTK.Core/Factories/GLTextureFactory.cs b/src/ObjectTK.Core/Factories/GLTextureFactory.cs new file mode 100644 index 0000000..fb10e9d --- /dev/null +++ b/src/ObjectTK.Core/Factories/GLTextureFactory.cs @@ -0,0 +1,76 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Imaging; +using JetBrains.Annotations; +using ObjectTK.GLObjects; +using OpenTK.Graphics.OpenGL; + +// ReSharper disable once CheckNamespace +namespace ObjectTK { + [EditorBrowsable(EditorBrowsableState.Advanced)] + public sealed class GLTextureFactory { + public static GLTextureFactory Instance { get; } = new GLTextureFactory(); + private GLTextureFactory() { } + + /// Creates a texture from a raw pointer. + /// This is typically used for creation from a bitmap. + [NotNull] + [MustUseReturnValue] + public Texture2D Create2D(string name, [NotNull] TextureConfig cfg, int width, int height, IntPtr data) { + var t = GL.GenTexture(); + var label = $"Texture2D: {name}"; + GL.BindTexture(TextureTarget.Texture2D, t); + GL.TexImage2D(TextureTarget.Texture2D, 0, cfg.InternalFormat, width, height, 0, cfg.PixelFormat, cfg.PixelType, data); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) cfg.MagFilter); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) cfg.MinFilter); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) cfg.WrapS); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) cfg.WrapS); + GL.ObjectLabel(ObjectLabelIdentifier.Texture, t, label.Length, label); + if (cfg.GenerateMipmaps) { + GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); + } + + GL.BindTexture(TextureTarget.Texture2D, 0); + return new Texture2D(t, name, cfg.InternalFormat, width, height); + } + + /// Creates a 2D texture from a bitmap. + [NotNull] + [MustUseReturnValue] + public Texture2D FromBitmap([NotNull] string name, [NotNull] TextureConfig cfg, [NotNull] Bitmap bmp) { + var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); + var bitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + return Create2D(name, cfg, bmp.Width, bmp.Height, bitmapData.Scan0); + } + + + // Hide the default members of this object for a cleaner API. + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + // ReSharper disable once BaseObjectEqualsIsObjectEquals + return base.Equals(obj); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode + return base.GetHashCode(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + // ReSharper disable once AnnotateCanBeNullTypeMember + public override string ToString() + { + return base.ToString(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [NotNull] + public new Type GetType() { + return base.GetType(); + } + } +} diff --git a/src/ObjectTK.Core/Factories/GLVertexArrayFactory.cs b/src/ObjectTK.Core/Factories/GLVertexArrayFactory.cs new file mode 100644 index 0000000..38d10a7 --- /dev/null +++ b/src/ObjectTK.Core/Factories/GLVertexArrayFactory.cs @@ -0,0 +1,88 @@ +using System; +using System.ComponentModel; +using JetBrains.Annotations; +using ObjectTK.GLObjects; +using OpenTK.Graphics.OpenGL; +using Buffer = ObjectTK.GLObjects.Buffer; + +// ReSharper disable once CheckNamespace +namespace ObjectTK { + [EditorBrowsable(EditorBrowsableState.Advanced)] + public sealed class GLVertexArrayFactory { + public static GLVertexArrayFactory Instance { get; } = new GLVertexArrayFactory(); + private GLVertexArrayFactory() { } + + // Hide the default members of this object for a cleaner API. + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + // ReSharper disable once BaseObjectEqualsIsObjectEquals + return base.Equals(obj); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode + return base.GetHashCode(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + // ReSharper disable once AnnotateCanBeNullTypeMember + public override string ToString() + { + return base.ToString(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [NotNull] + // ReSharper disable once UnusedMember.Global + public new Type GetType() { + return base.GetType(); + } + + [NotNull] + [MustUseReturnValue] + public VertexArray FromBuffers([NotNull] string name, [NotNull] params Buffer[] buffers) { + var length = buffers[0].ElementCount; + #if DEBUG + for (int i = 0; i < buffers.Length; i++) { + var b = buffers[i]; + if (b.ElementCount != length) { + throw new ArgumentException($"The provided buffers must have the same number of elements.\n" + + $"The buffer {b.Name} with length {b.ElementCount} did not match the expected length of {length}"); + } + } + #endif + + var vao = GL.GenVertexArray(); + var label = $"VertexArray: {name}"; + GL.BindVertexArray(vao); + GL.ObjectLabel(ObjectLabelIdentifier.VertexArray,vao, name.Length, label); + for (int i = 0; i < buffers.Length; i++) { + var buffer = buffers[i]; + GL.BindBuffer(BufferTarget.ArrayBuffer, buffer.Handle); + GL.EnableVertexAttribArray(i); + GL.VertexAttribPointer(i, buffer.ComponentCount, buffer.AttribType, false, buffer.ElementSize,0); + } + // clean up: + GL.BindBuffer(BufferTarget.ArrayBuffer, 0); + GL.BindVertexArray(0); + + return new VertexArray(name, vao, buffers, null); + } + + /// Creates a vertex array from the provided index and vertex buffers. + [Pure] + [NotNull] + public VertexArray IndexAndVertexBuffers([NotNull] string name, Buffer<int> indexBuffer, params Buffer[] vertexBuffers) { + var b = FromBuffers(name, vertexBuffers); + GL.BindVertexArray(b.Handle); + GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBuffer.Handle); + GL.BindVertexArray(0); + b.IndexBuffer = indexBuffer; + return b; + } + } +} diff --git a/src/ObjectTK.Core/GLFactory.cs b/src/ObjectTK.Core/GLFactory.cs new file mode 100644 index 0000000..1921689 --- /dev/null +++ b/src/ObjectTK.Core/GLFactory.cs @@ -0,0 +1,16 @@ +namespace ObjectTK { + /// Extensible, top-level class responsible for creating all OpenGL objects.<br></br> + /// ------<br></br> + /// Usage: GLFactory.Shader.VertexFrag()<br></br> + /// <br></br> + /// To extend this class, add extension methods to the GLxFactory types, where 'x' is one of the field names.<br></br> + /// e.g. <see cref="GLShaderFactory"/> or <see cref="GLVertexArrayFactory"/> + public static class GLFactory { + + public static readonly GLShaderFactory Shader = GLShaderFactory.Instance; + public static readonly GLBufferFactory Buffer = GLBufferFactory.Instance; + public static readonly GLVertexArrayFactory VertexArray = GLVertexArrayFactory.Instance; + public static readonly GLTextureFactory Texture = GLTextureFactory.Instance; + } + +} diff --git a/src/ObjectTK.Core/GLObjects/Buffer.cs b/src/ObjectTK.Core/GLObjects/Buffer.cs new file mode 100644 index 0000000..82a25d7 --- /dev/null +++ b/src/ObjectTK.Core/GLObjects/Buffer.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using OpenTK.Graphics.OpenGL; +using OpenTK.Mathematics; + +namespace ObjectTK.GLObjects { + + /// Corresponds to an OpenGL Buffer. + /// Typically this is a vertex/index/whatever buffer. + public class Buffer { + /// The name of this buffer + public string Name { get; set; } + /// The OpenGL Handle for this. + public int Handle { get; } + /// The GL data type (float, int, etc). (Vector2 -> float) + public VertexAttribPointerType AttribType { get; } + /// The number of components in each element. (Vector2 -> 2) + public int ComponentCount { get; } + /// Size in bytes of each element in the buffer (Vector2 -> 8 bytes) + public int ElementSize { get; } + /// The number of elements in this buffer. (based on the data set in this buffer) + public int ElementCount { get; set; } + + public Buffer(string name, int handle, VertexAttribPointerType attribType, int componentCount, int elementSize, int elementCount) { + Name = name; + Handle = handle; + AttribType = attribType; + ComponentCount = componentCount; + ElementSize = elementSize; + ElementCount = elementCount; + } + } + + internal static class BufferHelper { + internal struct TypeToGLInfoCache { + public VertexAttribPointerType AttribPointerType; + public int ComponentCount; + + public TypeToGLInfoCache(VertexAttribPointerType attribPointerType, int componentCount) { + AttribPointerType = attribPointerType; + ComponentCount = componentCount; + } + } + + private static readonly Dictionary<Type, TypeToGLInfoCache> InfoCache = new Dictionary<Type, TypeToGLInfoCache>(); + + private static void Add<T2>(VertexAttribPointerType vapt, int componentCount) { + InfoCache[typeof(T2)] = new TypeToGLInfoCache(vapt, componentCount); + } + + static BufferHelper() { + Add<byte>(VertexAttribPointerType.Byte, 1); + Add<sbyte>(VertexAttribPointerType.UnsignedByte, 1); + + Add<Color>(VertexAttribPointerType.UnsignedByte, 4); + + Add<short>(VertexAttribPointerType.Short, 1); + Add<ushort>(VertexAttribPointerType.UnsignedShort, 1); + + Add<uint>(VertexAttribPointerType.UnsignedInt, 1); + + Add<int>(VertexAttribPointerType.Int, 1); + Add<Vector2i>(VertexAttribPointerType.Int, 2); + Add<Vector3i>(VertexAttribPointerType.Int, 3); + Add<Vector4i>(VertexAttribPointerType.Int, 4); + + Add<Half>(VertexAttribPointerType.HalfFloat, 1); + Add<Vector2h>(VertexAttribPointerType.HalfFloat, 2); + Add<Vector3h>(VertexAttribPointerType.HalfFloat, 3); + Add<Vector4h>(VertexAttribPointerType.HalfFloat, 4); + + Add<float>(VertexAttribPointerType.Float, 1); + Add<Vector2>(VertexAttribPointerType.Float, 2); + Add<Vector3>(VertexAttribPointerType.Float, 3); + Add<Vector4>(VertexAttribPointerType.Float, 4); + Add<Color4>(VertexAttribPointerType.Float, 4); + + Add<double>(VertexAttribPointerType.Double, 1); + Add<Vector2d>(VertexAttribPointerType.Double, 2); + Add<Vector3d>(VertexAttribPointerType.Double, 3); + Add<Vector4d>(VertexAttribPointerType.Double, 4); + + Add<Quaternion>(VertexAttribPointerType.Float, 4); + Add<Quaterniond>(VertexAttribPointerType.Double, 4); + + // numerics + + Add<System.Numerics.Vector2>(VertexAttribPointerType.Float, 2); + Add<System.Numerics.Vector3>(VertexAttribPointerType.Float, 3); + Add<System.Numerics.Vector4>(VertexAttribPointerType.Float, 4); + + } + + internal static TypeToGLInfoCache GetData<T>() { + return InfoCache[typeof(T)]; + } + } + + /// Corresponds to an OpenGL Buffer. + /// Typically this is a vertex/index/whatever buffer. + /// Strongly typed buffer. This can be upcast to a normal buffer if generic usage is required. + public class Buffer<T> : Buffer where T : unmanaged { + + + public unsafe Buffer(string name, int handle, int elementCount) : base(name, handle, BufferHelper.GetData<T>().AttribPointerType, + BufferHelper.GetData<T>().ComponentCount, sizeof(T), elementCount) { + + } + } +} diff --git a/src/ObjectTK.Core/GLObjects/ShaderAttributeInfo.cs b/src/ObjectTK.Core/GLObjects/ShaderAttributeInfo.cs new file mode 100644 index 0000000..ee08c5f --- /dev/null +++ b/src/ObjectTK.Core/GLObjects/ShaderAttributeInfo.cs @@ -0,0 +1,25 @@ +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.GLObjects { + public class ShaderAttributeInfo { + public string Name { get; set; } + public int Location { get; set; } + /// The size of the attribute, in units of the attribute type. + public int Size { get; set; } + /// + public ActiveAttribType ActiveAttribType { get; set; } + + public VertexAttribPointerType VertexAttribPointerType => ActiveAttribType.ToVertexAttribPointerType(); + + // + // public ShaderAttributeInfo(string name, int index, int components, ActiveAttribType activeAttribType, VertexAttribPointerType vertexAttribPointerType, bool normalized) { + // this.Name = name; + // this.Index = index; + // this.Components = components; + // this.ActiveAttribType = activeAttribType; + // this.VertexAttribPointerType = vertexAttribPointerType; + // this.Normalized = normalized; + // } + } + +} diff --git a/src/ObjectTK.Core/GLObjects/ShaderProgram.cs b/src/ObjectTK.Core/GLObjects/ShaderProgram.cs new file mode 100644 index 0000000..5ac8c5c --- /dev/null +++ b/src/ObjectTK.Core/GLObjects/ShaderProgram.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; + +namespace ObjectTK.GLObjects { + + /// See: https://www.khronos.org/opengl/wiki/Shader + public class ShaderProgram { + /// The OpenGL Handle + public int Handle { get; } + /// The individual stages making up this program in the order they are used. + public ShaderStage[] Stages { get; set; } + /// The uniforms on this shader. + public Dictionary<string, ShaderUniformInfo> Uniforms { get; set; } + /// The vertex attributes on this shader. + public Dictionary<string, ShaderAttributeInfo> Attributes { get; set; } + + public ShaderProgram(int handle, + ShaderStage[] stages, + Dictionary<string, ShaderUniformInfo> uniforms, + Dictionary<string, ShaderAttributeInfo> attributes) { + Handle = handle; + Stages = stages; + Uniforms = uniforms; + Attributes = attributes; + } + } +} diff --git a/src/ObjectTK.Core/GLObjects/ShaderStage.cs b/src/ObjectTK.Core/GLObjects/ShaderStage.cs new file mode 100644 index 0000000..4236785 --- /dev/null +++ b/src/ObjectTK.Core/GLObjects/ShaderStage.cs @@ -0,0 +1,18 @@ +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.GLObjects { + /// https://www.khronos.org/opengl/wiki/Shader#Stages + public class ShaderStage { + + public string Name { get; } + public ShaderType Type { get; } + public int Handle { get; } + public string Source { get; } + + public ShaderStage(ShaderType type, int handle, string source) { + Type = type; + Handle = handle; + Source = source; + } + } +} diff --git a/src/ObjectTK.Core/GLObjects/ShaderUniformInfo.cs b/src/ObjectTK.Core/GLObjects/ShaderUniformInfo.cs new file mode 100644 index 0000000..e8691d1 --- /dev/null +++ b/src/ObjectTK.Core/GLObjects/ShaderUniformInfo.cs @@ -0,0 +1,23 @@ +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.GLObjects { + public class ShaderUniformInfo { + //TODO FIXME: Name[] for array uniform variables can be challenging. + /// The name of this uniform in the array + public string Name { get; set; } + /// The uniform location. used with GL.SetUniform() + public int Location { get; } + /// If this uniform is an array, then this is the number of items in the array. + public int Size { get; } + /// The data type in the shader for this uniform. + public ActiveUniformType Type { get; } + + public ShaderUniformInfo(string name, int location, + int uniformSize, ActiveUniformType uniformType) { + Name = name; + Location = location; + Size = uniformSize; + Type = uniformType; + } + } +} diff --git a/src/ObjectTK.Core/GLObjects/Textures.cs b/src/ObjectTK.Core/GLObjects/Textures.cs new file mode 100644 index 0000000..10d7cae --- /dev/null +++ b/src/ObjectTK.Core/GLObjects/Textures.cs @@ -0,0 +1,208 @@ +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.GLObjects { + public interface ITexture { + int Handle { get; } + string Name { get; set; } + TextureTarget TextureTarget { get; } + PixelInternalFormat InternalFormat { get; set; } + } + + public class Texture1D : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.Texture1D; + public int Width { get; set; } + public int MipLevels { get; set; } + public Texture1D(int handle, string name, PixelInternalFormat internalFormat, int width, int mipLevels) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Width = width; + MipLevels = mipLevels; + } + } + + public class Texture2D : ITexture { + public int Handle { get; } + public string Name { get; set; } + public TextureTarget TextureTarget => TextureTarget.Texture2D; + public PixelInternalFormat InternalFormat { get; set; } + public int Width { get; set; } + public int Height { get; set; } + + /// The ratio of Width/Height + public float AspectRatio => (float) Width / Height; + + public Texture2D(int handle, string name, PixelInternalFormat internalFormat, int width, int height) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Width = width; + Height = height; + } + } + + public class Texture1DArray : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.Texture1DArray; + public int Width { get; set; } + public int Layers { get; set; } + public int MipLevels { get; set; } + public Texture1DArray(int handle, string name, PixelInternalFormat internalFormat, int width, int layers, int mipLevels) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Width = width; + Layers = layers; + MipLevels = mipLevels; + } + } + + public class Texture2DArray : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.Texture2DArray; + public int Width { get; set; } + public int Height { get; set; } + public int Layers { get; set; } + public int MipLevels { get; set; } + public Texture2DArray(int handle, string name, PixelInternalFormat internalFormat, int width, int height, int layers, int mipLevels) { + this.Handle = handle; + this.Name = name; + this.InternalFormat = internalFormat; + this.Width = width; + this.Height = height; + this.Layers = layers; + this.MipLevels = mipLevels; + } + } + + public class Texture2DMultisample : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.Texture2DMultisample; + public int Width { get; set; } + public int Height { get; set; } + public int Samples { get; set; } + public bool FixedSampleLocations { get; set; } + public Texture2DMultisample(int handle, string name, PixelInternalFormat internalFormat, int width, int height, int samples, bool fixedSampleLocations) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Width = width; + Height = height; + Samples = samples; + FixedSampleLocations = fixedSampleLocations; + } + } + + public class Texture2DMultisampleArray : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.Texture2DMultisampleArray; + public int Width { get; set; } + public int Height { get; set; } + public int Samples { get; set; } + public bool FixedSampleLocations { get; set; } + public int Layers { get; set; } + public Texture2DMultisampleArray(int handle, string name, PixelInternalFormat internalFormat, int width, int height, int layers, int samples, bool fixedSampleLocations) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Width = width; + Height = height; + Layers = layers; + Samples = samples; + FixedSampleLocations = fixedSampleLocations; + } + } + + public class TextureRectangle : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.TextureRectangle; + public int Width { get; set; } + public int Height { get; set; } + public TextureRectangle(int handle, string name, PixelInternalFormat internalFormat, int width, int height) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Width = width; + Height = height; + } + } + + public class TextureCubeMap : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.TextureCubeMap; + public int Size { get; set; } + public int MipLevels { get; set; } + public TextureCubeMap(int handle, string name, PixelInternalFormat internalFormat, int size, int mipLevels) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Size = size; + MipLevels = mipLevels; + } + } + + public sealed class TextureCubeMapArray : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.TextureCubeMapArray; + public int Size { get; set; } + public int Layers { get; set; } + public int MipLevels { get; set; } + public TextureCubeMapArray(int handle, string name, PixelInternalFormat internalFormat, int size, int layers, int mipLevels) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Size = size; + Layers = layers; + MipLevels = mipLevels; + } + } + + public class TextureBuffer : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.TextureBuffer; + //TODO: I don't know much about this texture type + public TextureBuffer(int handle, string name, PixelInternalFormat internalFormat) { + Handle = handle; + InternalFormat = internalFormat; + } + } + + public class Texture3D : ITexture { + public int Handle { get; } + public string Name { get; set; } + public PixelInternalFormat InternalFormat { get; set; } + public TextureTarget TextureTarget => TextureTarget.Texture3D; + public int Width { get; set; } + public int Height { get; set; } + public int Layers { get; set; } + public int MipLevels { get; set; } + public Texture3D(int handle, string name, PixelInternalFormat internalFormat, int width, int height, int layers, int mipLevels) { + Handle = handle; + Name = name; + InternalFormat = internalFormat; + Width = width; + Height = height; + Layers = layers; + MipLevels = mipLevels; + } + } +} diff --git a/src/ObjectTK.Core/GLObjects/VertexArray.cs b/src/ObjectTK.Core/GLObjects/VertexArray.cs new file mode 100644 index 0000000..c014335 --- /dev/null +++ b/src/ObjectTK.Core/GLObjects/VertexArray.cs @@ -0,0 +1,46 @@ +using JetBrains.Annotations; + +namespace ObjectTK.GLObjects { + + /// An OpenGL Vertex array object. + public class VertexArray { + + /// The name of this object. + public string Name { get; } + + /// The OpenGL handle. Use this to interact with OpenGL. + public int Handle { get; } + + /// The buffers associated with this vertex array. + [NotNull] + [ItemNotNull] + public Buffer[] Buffers { get; set; } + + + /// The element array buffer for this object. + /// If this is present, the vertex array should be displayed using indexed drawing. + [CanBeNull] + public Buffer IndexBuffer { get; set; } + + + /// The number of elements to draw. If there is an element buffer, this is the length. + /// If there is no element buffer, this is the length of the first buffer in the <see cref="Buffers"/> array. + public int ElementCount { + get + { + if (IndexBuffer != null) { + return IndexBuffer.ElementCount; + } + + return Buffers[0].ElementCount; + } + } + + public VertexArray(string name, int handle, [NotNull] Buffer[] buffers, [CanBeNull] Buffer indexBuffer) { + Name = name; + Handle = handle; + Buffers = buffers; + IndexBuffer = indexBuffer; + } + } +} diff --git a/src/ObjectTK.Core/Internal/ListExtensions.cs b/src/ObjectTK.Core/Internal/ListExtensions.cs new file mode 100644 index 0000000..54ef20c --- /dev/null +++ b/src/ObjectTK.Core/Internal/ListExtensions.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Reflection.Emit; + +namespace ObjectTK.Internal { + internal static class UnsafeListExtensions { + private static class ArrayAccessor<T> + { + internal static readonly Func<List<T>, T[]> GetUnderlyingArray; + + static ArrayAccessor() + { + var dm = new DynamicMethod("get", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(T[]), new[] { typeof(List<T>) }, typeof(ArrayAccessor<T>), true); + var il = dm.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); // Load List<T> argument + il.Emit(OpCodes.Ldfld, typeof(List<T>).GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance)!); // Replace argument by field + il.Emit(OpCodes.Ret); // Return field + GetUnderlyingArray = (Func<List<T>, T[]>)dm.CreateDelegate(typeof(Func<List<T>, T[]>)); + } + } + + // ReSharper disable once ReturnTypeCanBeEnumerable.Global + internal static T[] GetInternalArray<T>(this List<T> list) + { + return ArrayAccessor<T>.GetUnderlyingArray(list); + } + } +} diff --git a/src/ObjectTK.Core/ObjectTK.Core.csproj b/src/ObjectTK.Core/ObjectTK.Core.csproj new file mode 100644 index 0000000..13e5277 --- /dev/null +++ b/src/ObjectTK.Core/ObjectTK.Core.csproj @@ -0,0 +1,19 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>netcoreapp3.1</TargetFramework> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <RootNamespace>ObjectTK</RootNamespace> + </PropertyGroup> + + <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> + <DocumentationFile>bin\Release\ObjectTK.Core.xml</DocumentationFile> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="JetBrains.Annotations" Version="2020.1.0" /> + <PackageReference Include="OpenTK" Version="4.1.0" /> + <PackageReference Include="System.Drawing.Common" Version="5.0.0" /> + </ItemGroup> + +</Project> diff --git a/src/ObjectTK.Core/Shaders/Material.cs b/src/ObjectTK.Core/Shaders/Material.cs new file mode 100644 index 0000000..f9301da --- /dev/null +++ b/src/ObjectTK.Core/Shaders/Material.cs @@ -0,0 +1,5 @@ +namespace ObjectTK.Shaders { + public class Material { + } + +} diff --git a/src/ObjectTK.Core/Shaders/ShaderCompiler.cs b/src/ObjectTK.Core/Shaders/ShaderCompiler.cs new file mode 100644 index 0000000..32b70be --- /dev/null +++ b/src/ObjectTK.Core/Shaders/ShaderCompiler.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using JetBrains.Annotations; +using ObjectTK.GLObjects; +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.Shaders { + + public static class ShaderCompiler { + + /// Helper method that compiles a shader stage (part of a ShaderProgram) or throws an exception if failure occurs. + [MustUseReturnValue] + [NotNull] + public static ShaderStage CompileShaderStage(ShaderType shaderType, string name, string source) + { + var handle = GL.CreateShader(shaderType); + var objLabel = $"ShaderStage: {name}-{shaderType}"; + GL.ObjectLabel(ObjectLabelIdentifier.Shader, handle, objLabel.Length, objLabel); + GL.ShaderSource(handle, source); + GL.CompileShader(handle); + GL.GetShader(handle, ShaderParameter.CompileStatus, out var compileStatus); + if (compileStatus == 0) + { + var vertLog = GL.GetShaderInfoLog(handle); + //TODO: needs a proper exception type. + var msg = $"Failed to compile shader '{name}' of type {shaderType}. Error:\n{vertLog}"; + throw new Exception(msg); + } + return new ShaderStage(shaderType, handle, source); + } + + [NotNull] + [MustUseReturnValue] + public static ShaderProgram Introspect(int prog, ShaderStage[] stages) { + // inspect the attributes: + var attributes = new Dictionary<string, ShaderAttributeInfo>(StringComparer.Ordinal); + + GL.GetProgram(prog, GetProgramParameterName.ActiveAttributes, out var attribCount); + for (var i = 0; i < attribCount; i++) + { + var attrName = GL.GetActiveAttrib(prog, i, out var count, out var attrType); + var attrLoc = GL.GetAttribLocation(prog, attrName); + attributes[attrName] = new ShaderAttributeInfo() { + Name = attrName, + Location = attrLoc, + Size = count, + ActiveAttribType = attrType, + }; + } + + // inspect the uniforms + var uniforms = new Dictionary<string, ShaderUniformInfo>(StringComparer.Ordinal); + + GL.GetProgram(prog, GetProgramParameterName.ActiveUniforms, out var uniformCount); + for (var i = 0; i < uniformCount; i++) + { + var uniName = GL.GetActiveUniform(prog, i, out var uniSize, out var uniType); + var uniLoc = GL.GetUniformLocation(prog, uniName); + uniforms[uniName] = new ShaderUniformInfo(uniName, uniLoc, uniSize, uniType); + } + + return new ShaderProgram(prog, stages, uniforms, attributes); + } + + [MustUseReturnValue] + [NotNull] + public static ShaderProgram VertexFrag(string name, string vertSource, string fragSource) { + + var vert = CompileShaderStage(ShaderType.VertexShader, name, vertSource); + var frag = CompileShaderStage(ShaderType.FragmentShader, name, fragSource); + var stages = new[] {vert, frag}; + + int handle = GL.CreateProgram(); + var label = $"ShaderProgram: {name}"; + GL.ObjectLabel(ObjectLabelIdentifier.Program, handle, label.Length, label); + + GL.AttachShader(handle, vert.Handle); + GL.AttachShader(handle, frag.Handle); + GL.LinkProgram(handle); + + GL.GetProgram(handle, GetProgramParameterName.LinkStatus, out int linkStatus); + if (linkStatus == 0) + { + var linkLog = GL.GetProgramInfoLog(handle); + //TODO: needs a proper exception type. + var msg = $"Failed to link shader '{name}'. Error:\n{linkLog}"; + throw new Exception(msg); + } + + return Introspect(handle, stages); + } + } +} diff --git a/src/ObjectTK.Core/TextureConfig.cs b/src/ObjectTK.Core/TextureConfig.cs new file mode 100644 index 0000000..c1b2ccf --- /dev/null +++ b/src/ObjectTK.Core/TextureConfig.cs @@ -0,0 +1,77 @@ +using System; +using System.ComponentModel; +using JetBrains.Annotations; +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK { + + public sealed class TextureConfig { + + public TextureMagFilter MagFilter { get; set; } = TextureMagFilter.Linear; + public TextureMinFilter MinFilter { get; set; } = TextureMinFilter.LinearMipmapNearest; + + public TextureWrapMode WrapS { get; set; } = TextureWrapMode.Repeat; + public TextureWrapMode WrapT { get; set; } = TextureWrapMode.Repeat; + public TextureWrapMode WrapR { get; set; } = TextureWrapMode.Repeat; + + /// The format the OpenGL stores this texture data in, internally. + /// By default, this is an RGBA 8BPP (8 bits per pixel) format. + public PixelInternalFormat InternalFormat { get; set; } = PixelInternalFormat.Rgba; + + /// The format of the data used to create this texture. + public PixelFormat PixelFormat { get; set; } = PixelFormat.Bgra; + /// The data type of each pixel's channel used to create this texture. + public PixelType PixelType { get; set; } = PixelType.UnsignedByte; + + /// If mipmaps should be generated for this texture. + /// You almost certainly want this to be on. + public bool GenerateMipmaps { get; set; } = true; + + /// The default texture configuration. Should be good for most cases. + [NotNull] + public static TextureConfig Default => new TextureConfig(); + + /// Creates a copy of this <see cref="TextureConfig"/> + [Pure] + [NotNull] + public TextureConfig Copy() { + return new TextureConfig { + GenerateMipmaps = GenerateMipmaps, + InternalFormat = InternalFormat, + MagFilter = MagFilter, + MinFilter = MinFilter, + PixelFormat = PixelFormat, + PixelType = PixelType + }; + } + + // Hide the default members of this object for a cleaner API. + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + // ReSharper disable once BaseObjectEqualsIsObjectEquals + return base.Equals(obj); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode + return base.GetHashCode(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + // ReSharper disable once AnnotateCanBeNullTypeMember + public override string ToString() + { + return base.ToString(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [NotNull] + public new Type GetType() { + return base.GetType(); + } + } + +} diff --git a/src/ObjectTK.Core/paket b/src/ObjectTK.Core/paket new file mode 100644 index 0000000..0cf12d8 --- /dev/null +++ b/src/ObjectTK.Core/paket @@ -0,0 +1,8 @@ +type file +id ObjectTK.Core +description + Holds fundamental abstractions of OpenGL and core components of ObjectTK. +files + bin\Release\netcoreapp3.1\ObjectTK.Core.dll ==> lib\netcoreapp3.1 + bin\Release\netcoreapp3.1\ObjectTK.Core.xml ==> lib\netcoreapp3.1 + bin\Release\netcoreapp3.1\ObjectTK.Core.pdb ==> lib\netcoreapp3.1 \ No newline at end of file diff --git a/src/ObjectTK.Extensions/Buffers/BufferExtensions.cs b/src/ObjectTK.Extensions/Buffers/BufferExtensions.cs new file mode 100644 index 0000000..9305ae8 --- /dev/null +++ b/src/ObjectTK.Extensions/Buffers/BufferExtensions.cs @@ -0,0 +1,15 @@ +using ObjectTK.GLObjects; +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.Extensions.Buffers { + public static class BufferExtensions { + + public static void BufferData<T>(this Buffer<T> Buffer, BufferTarget BufferTarget, T[] Data, BufferUsageHint BufferUsageHint = BufferUsageHint.StaticDraw) where T : unmanaged { + Buffer.ElementCount = Data.Length; + GL.BindBuffer(BufferTarget, Buffer.Handle); + GL.BufferData(BufferTarget, Buffer.ElementSize * Buffer.ElementCount, Data, BufferUsageHint); + } + + + } +} diff --git a/src/ObjectTK.Extensions/Buffers/VertexArrayExtensions.cs b/src/ObjectTK.Extensions/Buffers/VertexArrayExtensions.cs new file mode 100644 index 0000000..535f6d4 --- /dev/null +++ b/src/ObjectTK.Extensions/Buffers/VertexArrayExtensions.cs @@ -0,0 +1,25 @@ +using JetBrains.Annotations; +using ObjectTK.GLObjects; +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.Extensions.Buffers { + public static class VertexArrayExtensions { + + + public static void Bind([NotNull] this VertexArray vertexArray) { + GL.BindVertexArray(vertexArray.Handle); + } + + public static void Unbind([NotNull] this VertexArray vertexArray) { + GL.BindVertexArray(0); + } + + public static void BindVertexAttribute<T>(this VertexArray vertexArray, ShaderAttributeInfo shaderAttributeInfo, Buffer<T> Buffer) where T : unmanaged { + vertexArray.Bind(); + GL.VertexAttribPointer(shaderAttributeInfo.Location, Buffer.ElementCount, VertexAttribPointerType.Float, false, Buffer.ElementSize, 0); + GL.EnableVertexAttribArray(shaderAttributeInfo.Location); + GL.BindBuffer(BufferTarget.ArrayBuffer, Buffer.Handle); + } + + } +} diff --git a/src/ObjectTK.Extensions/ObjectTK.Extensions.csproj b/src/ObjectTK.Extensions/ObjectTK.Extensions.csproj new file mode 100644 index 0000000..1856cfc --- /dev/null +++ b/src/ObjectTK.Extensions/ObjectTK.Extensions.csproj @@ -0,0 +1,11 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>netcoreapp3.1</TargetFramework> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\ObjectTK.Core\ObjectTK.Core.csproj" /> + </ItemGroup> + +</Project> diff --git a/src/ObjectTK.Extensions/Shaders/Material.cs b/src/ObjectTK.Extensions/Shaders/Material.cs new file mode 100644 index 0000000..a005455 --- /dev/null +++ b/src/ObjectTK.Extensions/Shaders/Material.cs @@ -0,0 +1,44 @@ +#region License + +// ObjectTK License +// Copyright (C) 2013-2015 J.C.Bernack +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see <http://www.gnu.org/licenses/>. + +#endregion + +using System; +using System.Reflection; +using ObjectTK.GLObjects; + +namespace ObjectTK.Extensions.Shaders { + public class Material<T> where T : class, new() { + public ShaderProgram<T> ShaderProgram { get; set; } + public T Variables { get; set; } + + public Material() { + + foreach (PropertyInfo Prop in ShaderProgram.UniformInfoProperties) { + Type UniformType = Prop.PropertyType.GetGenericArguments()[0]; + object DefaultValue = Activator.CreateInstance(UniformType); + ShaderUniformInfo PropValue = Prop.GetValue(ShaderProgram.Variables) as ShaderUniformInfo; + } + } + + public void Use() { + ShaderProgram.Use(); + } + + } +} \ No newline at end of file diff --git a/src/ObjectTK.Extensions/Shaders/ProgramExtensions.cs b/src/ObjectTK.Extensions/Shaders/ProgramExtensions.cs new file mode 100644 index 0000000..53eab25 --- /dev/null +++ b/src/ObjectTK.Extensions/Shaders/ProgramExtensions.cs @@ -0,0 +1,28 @@ +using ObjectTK.Extensions.Variables; +using OpenTK.Graphics.OpenGL; +using System.Collections.Generic; +using System.Reflection; +using ObjectTK.GLObjects; +using ObjectTK.Shaders; + +namespace ObjectTK.Extensions.Shaders { + + public static class ProgramExtensions { + + public static void Use(this ShaderProgram shaderProgram) { + GL.UseProgram(shaderProgram.Handle); + } + + } + public class ShaderProgram<T> : ShaderProgram where T : class, new() { + public T Variables { get; set; } + internal List<PropertyInfo> UniformInfoProperties { get; set; } + internal List<PropertyInfo> VertexAttributeInfoProperties { get; set; } + + public ShaderProgram(int handle, ShaderStage[] stages, + Dictionary<string, ShaderUniformInfo> uniforms, + Dictionary<string, ShaderAttributeInfo> attributes) : + base(handle, stages, uniforms, attributes) { + } + } +} diff --git a/src/ObjectTK.Extensions/Shaders/ProgramFactory.cs b/src/ObjectTK.Extensions/Shaders/ProgramFactory.cs new file mode 100644 index 0000000..ef66ac0 --- /dev/null +++ b/src/ObjectTK.Extensions/Shaders/ProgramFactory.cs @@ -0,0 +1,143 @@ +using ObjectTK.Extensions.Variables; +using OpenTK.Graphics.OpenGL; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using ObjectTK.GLObjects; +using ObjectTK.Shaders; + +namespace ObjectTK.Extensions.Shaders { + public class ProgramFactory { + + public string BaseDirectory { get; set; } = "./"; + public string ShaderExtension { get; set; } = "glsl"; + + public ShaderProgram<T> CreateProgram<T>() where T : class, new() { + + List<ShaderSourceAttribute> Attributes = typeof(T).GetCustomAttributes<ShaderSourceAttribute>(true).ToList(); + List<ShaderStage> Shaders = new List<ShaderStage>(); + + int ProgramHandle = GL.CreateProgram(); + + foreach (ShaderSourceAttribute Attribute in Attributes) { + string Source = GetEffectSource(Attribute.EffectKey); + + int ShaderHandle = GL.CreateShader(Attribute.Type); + GL.ShaderSource(ShaderHandle, Source); + GL.CompileShader(ShaderHandle); + GL.AttachShader(ProgramHandle, ShaderHandle); + + switch (Attribute.Type) { + case ShaderType.FragmentShader: + Shaders.Add(new ShaderStage(ShaderType.FragmentShader, ShaderHandle, Source)); + break; + case ShaderType.VertexShader: + Shaders.Add(new ShaderStage(ShaderType.VertexShader, ShaderHandle, Source)); + break; + default: + break; + } + } + + GL.LinkProgram(ProgramHandle); + + foreach (ShaderStage Shader in Shaders) { + GL.DetachShader(ProgramHandle, Shader.Handle); + GL.DeleteShader(Shader.Handle); + } + + ShaderProgram<T> ShaderProgram = new ShaderProgram<T>(ProgramHandle, null, new Dictionary<string, ShaderUniformInfo>(), new Dictionary<string, ShaderAttributeInfo>()); + InitializeProgramVariables(ShaderProgram); + + return ShaderProgram; + } + + private string GetEffectSource(string EffectKey, Dictionary<string, string> Effects = null) { + + Effects ??= new Dictionary<string, string>(); + + string EffectFile = Path.ChangeExtension(EffectKey, null); + string FilePath = Path.Join(BaseDirectory, Path.ChangeExtension(EffectKey, "glsl")); + string FullSource = File.ReadAllText(FilePath); + + ExtractEffects(EffectFile, FullSource, Effects); + + Effects.TryGetValue(EffectKey, out string EffectSource); + return EffectSource ?? throw new Exception($"Error loading effect with key: {EffectKey}"); + } + private void ExtractEffects(string EffectFile, string FullSource, Dictionary<string, string> Effects) { + + const string EffectToken = "--"; + const string EffectFileSeparator = "."; + const string IncludeToken = "#include"; + + string[] Lines = FullSource.Split('\n'); + + StringBuilder Effect = new StringBuilder(); + string EffectKey = null; + + foreach(string Line in Lines) { + if (Line.StartsWith(EffectToken) && Line.Length > EffectToken.Length) { + if(EffectKey != null) { + Effects.Add(EffectKey, Effect.ToString()); + Effect.Clear(); + EffectKey = null; + } + EffectKey = $"{EffectFile}{EffectFileSeparator}{Line.Substring(EffectToken.Length).Trim()}"; + continue; + } + + if(EffectKey != null) { + if(Line.StartsWith(IncludeToken) && Line.Length > IncludeToken.Length) { + string IncludedEffect = Line.Substring(IncludeToken.Length).Trim(); + if(!Effects.TryGetValue(IncludedEffect, out string EffectSource)) { + EffectSource = GetEffectSource(IncludedEffect, Effects); + } + Effect.AppendLine(EffectSource); + } else { + Effect.AppendLine(Line); + } + } + } + if (EffectKey != null) { + Effects.Add(EffectKey, Effect.ToString()); + Effect.Clear(); + } + } + + private void InitializeProgramVariables<T>(ShaderProgram<T> shaderProgram) where T : class, new() { + + shaderProgram.Variables = new T(); + + PropertyInfo[] Properties = typeof(T).GetProperties(); + shaderProgram.UniformInfoProperties = Properties.Where(Prop => typeof(ShaderUniformInfo).IsAssignableFrom(Prop.PropertyType)).ToList(); + shaderProgram.VertexAttributeInfoProperties = Properties.Where(Prop => typeof(ShaderAttributeInfo).IsAssignableFrom(Prop.PropertyType)).ToList(); + + foreach (PropertyInfo Prop in shaderProgram.UniformInfoProperties) { + int UniformLocation = GL.GetUniformLocation(shaderProgram.Handle, Prop.Name); + GL.GetActiveUniform(shaderProgram.Handle, UniformLocation, out int UniformSize, out ActiveUniformType UniformType); + ShaderUniformInfo Value = Activator.CreateInstance(Prop.PropertyType, shaderProgram.Handle, Prop.Name, UniformLocation, UniformSize, UniformType, UniformLocation > -1) as ShaderUniformInfo; + Prop.SetValue(shaderProgram.Variables, Value); + shaderProgram.Uniforms.Add(Prop.Name, Value); + } + + foreach (PropertyInfo Prop in shaderProgram.VertexAttributeInfoProperties) { + int AttribIndex = GL.GetAttribLocation(shaderProgram.Handle, Prop.Name); + GL.GetActiveAttrib(shaderProgram.Handle, AttribIndex, out int Size, out ActiveAttribType AttribType); + VertexAttribAttribute Attribute = Prop.GetCustomAttribute<VertexAttribAttribute>(); + if(Attribute == null) { + throw new Exception($"VertexAttributeInfo {typeof(T).FullName}.{Prop.Name} is not decorated with the 'VertexAttrib' Attribute, which is necessary for some metadata as it cannot be determined by the shader itself."); + } + VertexAttribPointerType VertexAttribPointerType = Attribute.VertexAttribPointerType; + ShaderAttributeInfo Value = Activator.CreateInstance(Prop.PropertyType, shaderProgram.Handle, Prop.Name, AttribIndex > -1, AttribIndex, Size, AttribType, VertexAttribPointerType, false) as ShaderAttributeInfo; + Prop.SetValue(shaderProgram.Variables, Value); + shaderProgram.Attributes.Add(Prop.Name, Value); + } + + } + } + +} diff --git a/src/ObjectTK.Extensions/Shaders/ShaderAttributes.cs b/src/ObjectTK.Extensions/Shaders/ShaderAttributes.cs new file mode 100644 index 0000000..252581a --- /dev/null +++ b/src/ObjectTK.Extensions/Shaders/ShaderAttributes.cs @@ -0,0 +1,32 @@ +using OpenTK.Graphics.OpenGL; +using System; + +namespace ObjectTK.Extensions.Shaders { + + [AttributeUsage(AttributeTargets.Class)] + public class ShaderSourceAttribute : Attribute { + + public ShaderType Type { get; private set; } + + public string EffectKey { get; private set; } + + public ShaderSourceAttribute(ShaderType Type, string EffectKey) { + this.Type = Type; + this.EffectKey = EffectKey; + } + + } + + public class VertexShaderSourceAttribute : ShaderSourceAttribute { + public VertexShaderSourceAttribute(string EffectKey) : base(ShaderType.VertexShader, EffectKey) { + + } + } + + public class FragmentShaderSourceAttribute : ShaderSourceAttribute { + public FragmentShaderSourceAttribute(string EffectKey) : base(ShaderType.FragmentShader, EffectKey) { + + } + } + +} diff --git a/src/ObjectTK.Extensions/Shaders/ShaderExtensions.cs b/src/ObjectTK.Extensions/Shaders/ShaderExtensions.cs new file mode 100644 index 0000000..a1cb186 --- /dev/null +++ b/src/ObjectTK.Extensions/Shaders/ShaderExtensions.cs @@ -0,0 +1,30 @@ +using ObjectTK.GLObjects; +using ObjectTK.Shaders; +using OpenTK.Graphics.OpenGL; + +namespace ObjectTK.Extensions.Shaders { + + public static class ShaderFactory { + public static ShaderStage CreateVertexShader(string Source) { + int handle = GL.CreateShader(ShaderType.VertexShader); + GL.ShaderSource(handle, Source); + GL.CompileShader(handle); + return new ShaderStage(ShaderType.VertexShader, handle, Source); + } + public static ShaderStage CreateFragmentShader(string Source) { + int handle = GL.CreateShader(ShaderType.FragmentShader); + GL.ShaderSource(handle, Source); + GL.CompileShader(handle); + return new ShaderStage(ShaderType.FragmentShader, handle, Source); + } + } + + public static class ShaderExtensions { + public static void Compile(this ShaderStage shaderStage) { + GL.CompileShader(shaderStage.Handle); + } + public static void ShaderSource(this ShaderStage shaderStage) { + GL.ShaderSource(shaderStage.Handle, shaderStage.Source); + } + } +} diff --git a/src/ObjectTK.Extensions/Variables/UniformInfoExtensions.cs b/src/ObjectTK.Extensions/Variables/UniformInfoExtensions.cs new file mode 100644 index 0000000..d660995 --- /dev/null +++ b/src/ObjectTK.Extensions/Variables/UniformInfoExtensions.cs @@ -0,0 +1,74 @@ +using OpenTK.Graphics.OpenGL; +using OpenTK.Mathematics; +using System; +using System.Collections.Generic; +using System.Drawing; +using ObjectTK.GLObjects; + +namespace ObjectTK.Extensions.Variables { + public static class UniformInfoExtensions { + + public static void Set<T>(this ShaderUniformInfo<T> shaderUniform, T Value) { + shaderUniform.SetAction?.Invoke(shaderUniform.Location, Value); + } + } + + public class ShaderUniformInfo<T> : ShaderUniformInfo { + + internal Action<int, T> SetAction; + + public ShaderUniformInfo(int ProgramHandle, string Name, int Location, int UniformSize, ActiveUniformType UniformType, bool Active) : + base(Name, Location, UniformSize, UniformType) { + SetAction = UniformSetAction.FindAction<T>(); + } + + public class UniformSetAction { + + public static Action<int, V> FindAction<V>() { + if (SetActions.TryGetValue(typeof(V), out UniformSetAction SetAction)) { + return (SetAction as GenericUniformSetAction<V>).Action; + } + throw new Exception($"Uniform type not supported: {typeof(T).FullName}"); + } + + private static Dictionary<Type, UniformSetAction> SetActions; + static UniformSetAction() { + SetActions = new Dictionary<Type, UniformSetAction>() + { + { typeof(bool), new GenericUniformSetAction<bool> ((Location, Value) => GL.Uniform1(Location, Value ? 1 : 0)) }, + { typeof(int), new GenericUniformSetAction<int> (GL.Uniform1) }, + { typeof(uint), new GenericUniformSetAction<uint> (GL.Uniform1) }, + { typeof(float), new GenericUniformSetAction<float> (GL.Uniform1) }, + { typeof(double), new GenericUniformSetAction<double> (GL.Uniform1) }, + { typeof(Half), new GenericUniformSetAction<Half> ((Location, Half) => GL.Uniform1(Location, Half)) }, + { typeof(Color), new GenericUniformSetAction<Color> ((Location, Color) => GL.Uniform4(Location, Color)) }, + { typeof(Vector2), new GenericUniformSetAction<Vector2> (GL.Uniform2) }, + { typeof(Vector3), new GenericUniformSetAction<Vector3> (GL.Uniform3) }, + { typeof(Vector4), new GenericUniformSetAction<Vector4> (GL.Uniform4) }, + { typeof(Vector2d), new GenericUniformSetAction<Vector2d> ((Location, Vector) => GL.Uniform2(Location, Vector.X, Vector.Y)) }, + { typeof(Vector2h), new GenericUniformSetAction<Vector2h> ((Location, Vector) => GL.Uniform2(Location, Vector.X, Vector.Y)) }, + { typeof(Vector3d), new GenericUniformSetAction<Vector3d> ((Location, Vector) => GL.Uniform3(Location, Vector.X, Vector.Y, Vector.Z)) }, + { typeof(Vector3h), new GenericUniformSetAction<Vector3h> ((Location, Vector) => GL.Uniform3(Location, Vector.X, Vector.Y, Vector.Z)) }, + { typeof(Vector4d), new GenericUniformSetAction<Vector4d> ((Location, Vector) => GL.Uniform4(Location, Vector.X, Vector.Y, Vector.Z, Vector.W)) }, + { typeof(Vector4h), new GenericUniformSetAction<Vector4h> ((Location, Vector) => GL.Uniform4(Location, Vector.X, Vector.Y, Vector.Z, Vector.W)) }, + { typeof(Matrix2), new GenericUniformSetAction<Matrix2> ((Location, Matrix) => GL.UniformMatrix2(Location, false, ref Matrix)) }, + { typeof(Matrix3), new GenericUniformSetAction<Matrix3> ((Location, Matrix) => GL.UniformMatrix3(Location, false, ref Matrix)) }, + { typeof(Matrix4), new GenericUniformSetAction<Matrix4> ((Location, Matrix) => GL.UniformMatrix4(Location, false, ref Matrix)) }, + { typeof(Matrix2x3), new GenericUniformSetAction<Matrix2x3> ((Location, Matrix) => GL.UniformMatrix2x3(Location, false, ref Matrix)) }, + { typeof(Matrix2x4), new GenericUniformSetAction<Matrix2x4> ((Location, Matrix) => GL.UniformMatrix2x4(Location, false, ref Matrix)) }, + { typeof(Matrix3x2), new GenericUniformSetAction<Matrix3x2> ((Location, Matrix) => GL.UniformMatrix3x2(Location, false, ref Matrix)) }, + { typeof(Matrix3x4), new GenericUniformSetAction<Matrix3x4> ((Location, Matrix) => GL.UniformMatrix3x4(Location, false, ref Matrix)) }, + { typeof(Matrix4x2), new GenericUniformSetAction<Matrix4x2> ((Location, Matrix) => GL.UniformMatrix4x2(Location, false, ref Matrix)) }, + { typeof(Matrix4x3), new GenericUniformSetAction<Matrix4x3> ((Location, Matrix) => GL.UniformMatrix4x3(Location, false, ref Matrix)) } + }; + } + + public class GenericUniformSetAction<U> : UniformSetAction { + public Action<int, U> Action { get; set; } + public GenericUniformSetAction(Action<int, U> Action) { + this.Action = Action; + } + } + } + } +} diff --git a/src/ObjectTK.Extensions/Variables/VertexAttributeInfoExtensions.cs b/src/ObjectTK.Extensions/Variables/VertexAttributeInfoExtensions.cs new file mode 100644 index 0000000..5bc6fe4 --- /dev/null +++ b/src/ObjectTK.Extensions/Variables/VertexAttributeInfoExtensions.cs @@ -0,0 +1,30 @@ +using OpenTK.Graphics.OpenGL; +using System; + +namespace ObjectTK.Extensions.Variables { + public static class VertexAttributeInfoExtensions { + + + } + // + // public class ShaderAttributeInfo<T> : ShaderAttributeInfo { + // public ShaderAttributeInfo(int ProgramHandle, string Name, bool Active, int Index, int Components, ActiveAttribType ActiveAttribType, VertexAttribPointerType VertexAttribPointerType, bool Normalized) : + // base(Name, Active, Index, Components, ActiveAttribType, VertexAttribPointerType, Normalized) { + // } + // } + + [AttributeUsage(AttributeTargets.Property)] + public class VertexAttribAttribute : Attribute { + public VertexAttribPointerType VertexAttribPointerType { get; protected set; } + public bool Normalized { get; protected set; } + + /// <summary> + /// Defines some metadata for VertexAttributeInfo objects that cannot be gathered from OpenGL. + /// </summary> + public VertexAttribAttribute(VertexAttribPointerType VertexAttribPointerType = VertexAttribPointerType.Float, bool Normalized = false) { + this.VertexAttribPointerType = VertexAttribPointerType; + this.Normalized = Normalized; + } + } + +} diff --git a/src/ObjectTK.Tools/CameraWindow.cs b/src/ObjectTK.Tools/CameraWindow.cs new file mode 100644 index 0000000..6f1bd9f --- /dev/null +++ b/src/ObjectTK.Tools/CameraWindow.cs @@ -0,0 +1,41 @@ +using System; + +namespace ObjectTK.Tools { + using ObjectTK.Tools.Cameras; + using OpenTK.Mathematics; + using OpenTK.Windowing.Common; + using OpenTK.Windowing.Desktop; + + public abstract class CameraWindow : GameWindow { + + protected readonly FrameTimer FrameTimer; + + + private Camera _ActiveCamera = new Camera(); + protected Camera ActiveCamera { + get { + return _ActiveCamera; + } + set { + _ActiveCamera = value; + _ActiveCamera.Viewport = new Box2i(Vector2i.Zero, Size); + } + } + + protected CameraWindow(int width, int height, string title) + : base(new GameWindowSettings { }, new NativeWindowSettings { Size = new Vector2i(width, height), Title = title }) { + FrameTimer = new FrameTimer(); + } + + protected override void OnResize(ResizeEventArgs resizeEventArgs) { + base.OnResize(resizeEventArgs); + _ActiveCamera.Viewport = new Box2i(Vector2i.Zero, Size); + } + + protected override void OnUpdateFrame(FrameEventArgs frameEventArgs) { + base.OnUpdateFrame(frameEventArgs); + FrameTimer.Time(); + } + + } +} \ No newline at end of file diff --git a/src/ObjectTK.Tools/Cameras/Camera.cs b/src/ObjectTK.Tools/Cameras/Camera.cs new file mode 100644 index 0000000..e1a1e2b --- /dev/null +++ b/src/ObjectTK.Tools/Cameras/Camera.cs @@ -0,0 +1,58 @@ +using ObjectTK.Tools.Mathematics; +using OpenTK.Mathematics; + +namespace ObjectTK.Tools.Cameras { + public class Camera { + public Vector3 Position { get; set; } = Vector3.Zero; + public Quaternion Rotation { get; set; } = Quaternion.Identity; + public Vector3 Forward => Vector3.Transform(Vector3.UnitZ, Rotation).Normalized(); + public Vector3 Up => Vector3.Transform(Vector3.UnitY, Rotation).Normalized(); + public Vector3 Right => Vector3.Cross(Forward, Up); + public float PerspectiveFieldOfView { get; set; } = MathHelper.PiOver2; + public float AspectRatio => Viewport.Size.X / (float)Viewport.Size.Y; + public Matrix4 ViewMatrix => Matrix4.LookAt(Position, Position + Forward, Up); + + public CameraProjectionType CameraProjectionType { get; set; } = CameraProjectionType.Perspective; + public Matrix4 ProjectionMatrix => CameraProjectionType switch + { + CameraProjectionType.Perspective => Matrix4.CreatePerspectiveFieldOfView(PerspectiveFieldOfView, AspectRatio, NearClippingPlaneDistance, FarClippingPlaneDistance), + CameraProjectionType.Orthographic => Matrix4.CreateOrthographic(OrthographicVerticalSize * AspectRatio, OrthographicVerticalSize, NearClippingPlaneDistance, FarClippingPlaneDistance), + _ => Matrix4.CreatePerspectiveFieldOfView(PerspectiveFieldOfView, AspectRatio, NearClippingPlaneDistance, FarClippingPlaneDistance) + }; + + public Matrix4 ViewProjectionMatrix => ViewMatrix * ProjectionMatrix; + public Box2i Viewport { get; set; } + public float OrthographicVerticalSize { get; set; } = 5.0f; + public float NearClippingPlaneDistance { get; set; } = 0.1f; + public float FarClippingPlaneDistance { get; set; } = 1000.0f; + + public Ray GetPickingRay(Vector2 MousePosition) { + Matrix4 unViewProjectionMatrix = Matrix4.Invert(ViewProjectionMatrix); + + Vector3 Near = Vector3.Unproject( + new Vector3(MousePosition.X, Viewport.Size.Y - MousePosition.Y, NearClippingPlaneDistance), + Viewport.Min.X, + Viewport.Min.Y, + Viewport.Size.X, + Viewport.Size.Y, + NearClippingPlaneDistance, + FarClippingPlaneDistance, + unViewProjectionMatrix); + + Vector3 Far = Vector3.Unproject( + new Vector3(MousePosition.X, Viewport.Size.Y - MousePosition.Y, FarClippingPlaneDistance), + Viewport.Min.X, + Viewport.Min.Y, + Viewport.Size.X, + Viewport.Size.Y, + NearClippingPlaneDistance, + FarClippingPlaneDistance, + unViewProjectionMatrix); + + Vector3 Direction = (Far - Near).Normalized(); + + return new Ray { Origin = Position, Direction = Direction, Length = 1.0f }; + } + + } +} diff --git a/src/ObjectTK.Tools/Cameras/CameraProjectionType.cs b/src/ObjectTK.Tools/Cameras/CameraProjectionType.cs new file mode 100644 index 0000000..345b56b --- /dev/null +++ b/src/ObjectTK.Tools/Cameras/CameraProjectionType.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ObjectTK.Tools.Cameras { + public enum CameraProjectionType { + Perspective, + Orthographic + } +} diff --git a/ObjectTK.Tools/FrameTimer.cs b/src/ObjectTK.Tools/FrameTimer.cs similarity index 81% rename from ObjectTK.Tools/FrameTimer.cs rename to src/ObjectTK.Tools/FrameTimer.cs index 81517e7..a8f36b2 100644 --- a/ObjectTK.Tools/FrameTimer.cs +++ b/src/ObjectTK.Tools/FrameTimer.cs @@ -1,21 +1,7 @@ -// -// FrameTimer.cs -// -// Copyright (C) 2018 OpenTK -// -// This software may be modified and distributed under the terms -// of the MIT license. See the LICENSE file for details. -// +using System.Diagnostics; -using System.Diagnostics; - -namespace ObjectTK.Tools -{ - /// <summary> - /// Handles frame timing and fps calculation. - /// </summary> - public class FrameTimer - { +namespace ObjectTK.Tools { + public class FrameTimer { /// <summary> /// Total number of frames rendered. /// </summary> @@ -50,8 +36,7 @@ public class FrameTimer /// <summary> /// Initializes a new instance of the FrameTimer class. /// </summary> - public FrameTimer() - { + public FrameTimer() { _stopwatch = new Stopwatch(); //Application.Idle += (sender, args) => Time(); _stopwatch.Start(); @@ -61,20 +46,18 @@ public FrameTimer() /// Calculates timings based on the intervals between subsequent calls. Call once each frame.<br/> /// Determines frames per seconds and other statistics. /// </summary> - public void Time() - { + public void Time() { // retrieve time spent since last frame FrameTime = _stopwatch.Elapsed.TotalMilliseconds; _stopwatch.Restart(); // count time running TimeRunning += FrameTime; // calculate fps based on time spent on one frame - FpsBasedOnFrameTime = (int) (1000/FrameTime); + FpsBasedOnFrameTime = (int)(1000 / FrameTime); // calculate fps based on frames rendered during one second _elapsed += FrameTime; _fpsFrameCounter++; - if (_elapsed > 1000) - { + if (_elapsed > 1000) { _elapsed -= 1000; FpsBasedOnFramesRendered = _fpsFrameCounter; _fpsFrameCounter = 0; @@ -88,12 +71,11 @@ public void Time() /// <summary> /// Calculates the interval between two subsequent calls in milliseconds. /// </summary> - public double IntermediateTiming() - { + public double IntermediateTiming() { var elapsed = _stopwatch.Elapsed.TotalMilliseconds; var time = elapsed - _lastIntermediateTime; _lastIntermediateTime = elapsed; return time; } } -} \ No newline at end of file +} diff --git a/src/ObjectTK.Tools/Mathematics/Ray.cs b/src/ObjectTK.Tools/Mathematics/Ray.cs new file mode 100644 index 0000000..8cdf63a --- /dev/null +++ b/src/ObjectTK.Tools/Mathematics/Ray.cs @@ -0,0 +1,9 @@ +using OpenTK.Mathematics; + +namespace ObjectTK.Tools.Mathematics { + public class Ray { + public Vector3 Origin { get; set; } + public Vector3 Direction { get; set; } + public float Length { get; set; } + } +} diff --git a/src/ObjectTK.Tools/ObjectTK.Tools.csproj b/src/ObjectTK.Tools/ObjectTK.Tools.csproj new file mode 100644 index 0000000..b3651ea --- /dev/null +++ b/src/ObjectTK.Tools/ObjectTK.Tools.csproj @@ -0,0 +1,15 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>netcoreapp3.1</TargetFramework> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="OpenTK" Version="4.1.0" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\ObjectTK.Core\ObjectTK.Core.csproj" /> + </ItemGroup> + +</Project>