Giter VIP home page Giter VIP logo

vistrace's Introduction

Banner
GitHub Workflow Status GitHub Open Issues Discord
GitHub Release Downloads Steam Workshop Subscribers


VisTrace allows tracing visual meshes in Garry's Mod at high speeds on the CPU using https://github.com/madmann91/bvh, allowing for far higher fidelity scenes in Lua tracers without the massive performance cost of Lua mesh intersection.

Installation

Simply get the latest binary for your architecture from releases, and place it into garrysmod/lua/bin, then require("VisTrace-vX.X") in GLua.
For a more user friendly experience, get the Steam Workshop addon, which will automatically require the applicable version of the module, and provide integration with other addons (currently StarfallEx and Expression 2 #22).

Compiling

While it's recommended to just download the latest release binary, if you want to test WIP features before a full release, or you want to help develop the module, then you'll need to set up your toolchain to compile VisTrace and its dependencies.

Prerequesits

  • CMake 3.20 or newer
  • Ninja
  • clang - Clang with MSVC backend to use OpenMP while being ABI compatible with source

First time setup

  1. Clone the repository with the --recursive flag to init all submodules
  2. Open the cloned folder in your editor of choice
  3. Select a preset to compile (relwithsymbols for debugging as building with full debug mode breaks ABI compatibility with Source)
  4. Compile (compiled dll can be found in out/build/{presetname})

Extensions

VisTrace versions v0.10.0 and newer support user made extensions that can use and extend VisTrace's objects via interfaces in include.
A quick start repository template is available here

Additionally, an svg badge is provided to include in your readmes to show that your addon/binary module is VisTrace compatible:

Markdown Preview
[![VisTrace EXTENSION](https://github.com/Derpius/VisTrace/blob/branding/extension.svg?raw=true)](https://github.com/Derpius/VisTrace) VisTrace EXTENSION

Showcase

If you'd like to submit any images/videos showcasing your use of VisTrace, please submit a PR/Issue on the branding branch.

Please note that any content submitted may be used on VisTrace's GitHub, and Workshop pages, as well as the website.
See the readme on the branding branch for the naming convention.

Usage

MOVING TO WIKI

Example Code

For more detailed examples, see the Examples folder.
Will be moving to a dedicated branch

This will load the module, build the acceleration structure from all prop_physics entities (and the world), get an entity to use as a hit marker, and traverse the scene each frame placing the hit marker at the trace hit position if we hit:

-- Instead of manually checking realm/vistrace version, and requiring by hand
-- You could use the VisTraceInit hook which will be called by the binary if
-- everything loaded OK (this however needs the VisTrace addon to be installed)
if SERVER then error("VisTrace can only be used on the client!") end
require("VisTrace-vX.X") -- Put current version here
local accel = vistrace.CreateAccel(ents.FindByClass("prop_physics")--[[, false]]) -- Pass false here to disable tracing world (useful if you just want to interact with entities)

local plr = LocalPlayer()

-- Change the entity ID here to one you want to use as a hit marker
-- hard coded here for simplicity of the example,
-- and assuming no addons that change this are mounted,
-- will be the first prop created on flatgrass in singleplayer
local hitMarker = Entity(68) 


hook.Add("Think", "vistraceTest", function()
	local hitData = accel:Traverse(plr:EyePos(), plr:GetAimVector())
	if hitData then
		hitMarker:SetPos(hitData:Pos())
	end
end)

vistrace's People

Contributors

derpius avatar yogwoggf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

yogwoggf

vistrace's Issues

[bug] RebuildAccel doesn't handle NULL entities or those without a valid model

Describe the bug
A NULL entity will currently throw a generic GLua error (this may be adequate, however untested), and an entity with either no model or a model not present on client hasn't been tested (depending on how util.GetModelMeshes works, this either works fine, by just not adding any meshes, or if it returns nil then it will throw an error).

[feature] Handle face flexes

Describe the solution you'd like
Transform face vertices using a ragdoll's face flex data.
The rigging data needed to apply flexes isn't exposed to GLua, so I'll need to write a model parser

E2 Support

E2 support in VisTrace is extremely convoluted as it stands due to GetModelMeshes not being present on the server at the time, and the performance implications of many BVH traversals at the same time on the server

However now that OpenMP is in use, I'll see how fast it builds an accel struct when given the entire world using BSPParser, and if it's reasonable, I'll make a server binary and make the API in SF shared, along with rewriting the E2 API to use server calls

[feature] Render target saving to and loading from image

Describe the solution you'd like
IRenderTarget:Load(filename) which would load the contents of the file into the render target, resizing the RT as needed, and IRenderTarget:Save(filename, mip = 0) which would save the contents of the render target at the specified mip to a file.
The file path would be relative to garrysmod/data/vistrace and should sanitise out things like /../ (should be easy to do with the filesystem library).

Describe alternatives you've considered
Instead of scaling the RT to fit an image, it may be better to scale the image to fit the RT and add avistrace.LoadImage() function to automatically size the RT.
This would allow loading images at a consistent resolution for post processing, or loading an image into a specific MIP level.

[feature] Primitive entities

Describe the solution you'd like
Add a selection of SENTs that are interpreted by VisTrace as primitives, allowing for things like mathematically perfect spheres, while being no less performant than a triangle intersection.

These could also have built in configuration options for material properties and dimensions.

[feature] Correct normals to avoid issues with shading backfaces in TraceResult

Is your feature request related to a problem? Please describe.
When a ray hits the front face of a tri, but the smoothed/mapped normal faces away, an artificial backface hit is generated

Describe the solution you'd like
Copy Falcor's method of solving this

Describe alternatives you've considered
Should this be a helper function like CalcRayOrigin?

[feature] Emissive light sampler

Describe the solution you'd like
Implement an emissive mesh light importance sampler.

This could just be a uniform sampler, but taking the luminance of the surfaces into account produces far less noise with multiple lights of varying importance.
Additionally integrating emissive textures into the weighting would be great, however adds a lot of complexity and simply including tris that have any emissive pixels would suffice for now.

[bug] Add font fallbacks to extension badge

Describe the bug
While Windows has the Franklin Gothic font used by the VisTrace logo bundled in most cases, Mac/iOS/iPadOS and possibly other operating systems do not, causing it to fall back to Times New Roman

Expected behaviour
The font should fall back through a Verdana font stack.
Additionally a font stack for Verdana should be added to the EXTENSION text.

Screenshots
D9377867-5F6E-4C44-B5FC-EF4BF8F80146

Additional context
https://www.cssfontstack.com/Franklin-Gothic-Medium
Verdana font stack: Verdana, "Verdana Ref", sans-serif;

[feature] Decal support

Describe the solution you'd like
Automatically apply decals (at the very least map decals).
Not sure how these are instanced in game, and would need to see how they're applied in the shaders, but it's probably gonna involve implementing projected textures.

[feature] Implement texture scaling

Is your feature request related to a problem? Please describe.
Textures are incorrectly scaled on many surfaces

Describe the solution you'd like
Multiply UV coordinates by the texture transforms before being used in sampling and texture LoD calculations

Additional context
Code from the Source SDK for initialising a 2x4 mat from a 3x4 mat

void CBaseVSShader::SetVertexShaderTextureTransform( int vertexReg, int transformVar )
{
	Vector4D transformation[2];
	IMaterialVar* pTransformationVar = s_ppParams[transformVar];
	if (pTransformationVar && (pTransformationVar->GetType() == MATERIAL_VAR_TYPE_MATRIX))
	{
		const VMatrix &mat = pTransformationVar->GetMatrixValue();
		transformation[0].Init( mat[0][0], mat[0][1], mat[0][2], mat[0][3] );
		transformation[1].Init( mat[1][0], mat[1][1], mat[1][2], mat[1][3] );
	}
	else
	{
		transformation[0].Init( 1.0f, 0.0f, 0.0f, 0.0f );
		transformation[1].Init( 0.0f, 1.0f, 0.0f, 0.0f );
	}
	s_pShaderAPI->SetVertexShaderConstant( vertexReg, transformation[0].Base(), 2 ); 
}

[feature] Eye textures

Describe the solution you'd like
Eye textures are currently either white or missing textures due to the different shader they use.
Pretty sure eyes are implemented using rendertargets that move an iris around, which obviously isn't applicable to VisTrace's static acceleration structure, so I need a method to generate an applicable texture at build (or cache a copy of the RT if possible).

[feature] Rewrite readme

Readme is outdated, and will be massively outdated when 0.9 releases
It could also do with a compilation guide

[feature] Collapse vectors into single Entity vector

Is your feature request related to a problem? Please describe.
The old implementation of storing each individual piece of data in its own vector is no longer applicable with the amount of disparate types of data i need to store

Describe the solution you'd like
Replace all the per-entity vectors with a single vector of entity structs, and all per-triangle/vertex vectors with a single vector of triangle structs

[bug] Some meshes are rotated by more than their display in-game

Describe the bug
Some entities' meshes returned by util.GetModelMeshes are either under or over rotated compared to their display in-game, seemingly always by 90 degrees.

To Reproduce
Place the GMod logo prop down and trace, it will be rotated 90 degrees about its up vector.

[feature] Expose more of the module as extension interfaces

Describe the solution you'd like
Expose every object VisTrace can put onto the stack as an interface, allowing extensions to both call methods on VisTrace types from C++, but implement their own versions of the classes which can be passed to VisTrace functions using the same metatable id

[bug] Error entities trigger Lua errors on the client

Too late to make a proper description so here's enough for me to remember tomorrow:
Probably due to being an error on the client, the bigcity gnome causes argument 7 of some internal function call in RebuildAccel to be nil instead of an expected table (no idea what the function that throws this is), most likely fix would just be moving the GetModelMeshes nil checks higher in the function.

[feature] OpenMP support

Is your feature request related to a problem? Please describe.
Currently, even without a map loaded, it takes a while to build the acceleration structure

Describe the solution you'd like
Compiling in such a way that I maintain source ABI compatibility, and have access to the full set of OpenMP 4 features that the BVH library requires

Describe alternatives you've considered
Moving accel building to a detatched thread and adding a callback to the lua function, making it async

Additional context
Currently the best way it seems to get both OpenMP 4 support and maintain ABI compatibility with MSVC is to use Clang

[feature] Improve BVH building

Describe the solution you'd like
Right now it uses the most basic method for building an acceleration structure, however other options for not just the core construction method, but post build optimisations are available

Additionally, implementing refitting would possibly allow for rapid tracing of an animated scene

[feature] Detail textures

Implement detail texture blending

Additional context
Take a look at the Source SDK's DirectX 9 pixel shaders to see how they're incorporated into LightmapLitGeneric and VertexLitGeneric

[feature] StarfallEx support

Describe the solution you'd like
Add SF function bindings, preferably from within the module using pure stack code.

Describe alternatives you've considered
Manually setting instance.env.vistrace, however that's a hacky solution.

[feature] More robust map detection

Is your feature request related to a problem? Please describe.
Due to the reliance on the GM:Initialise hook to prevent trying to load the map before game.GetMap() returns valid data, it is no longer possible to load VisTrace outside of autorun.

Describe the solution you'd like
Either checking if GetMap returns invalid data (if it ever returns invalid data, need to test) or using some other method to get the current map that doesn't need to wait for the gamemode to initialise.

Additional context
https://wiki.facepunch.com/gmod/game.GetMap

Large client lag spike on spawning any E2 chip

Describe the bug
With the E2 Vistrace extension enabled, spawning/updating ANY expression chip will cause your client to freeze for a moment (700ms+). Disabling the Vistrace E2 extension stops the lag spikes. Speculating this is from acceleration structures being built regardless of the chip's content.

To Reproduce

  1. Enable E2 Vistrace extension
  2. Spawn any E2 chip to freeze for 700ms+

Expected Behaviour
Spawning chips shouldn't lag spike the client unless Vistrace is actually used in the chip and requires acceleration structures to be built.

[bug] Fix BTDF

Describe the bug
Either the material inputted to the BTDF is incorrect, or the port of Falcor's BTDF is incorrect, as transmissive materials are completely broken.

I can't find any renders of transmissive materials from when the BSDF was implemented either, so it may never have worked.

Screenshots

[feature] GLua API documentation

Currently only the Starfall API is documented, and while it mirrors the GLua API, dedicated GLua docs are needed for anyone not using Starfall

[bug] Ent ids are saved when building accel, but not verified after traverse

Describe the bug
When you build the acceleration structure, the entity ids are cached for lookup later (allowing the user to get information on the hit entity), however given the accel struct is not updated constantly, there is a high likelihood that an entity that was valid when building, is now invalid, or points to a completely different entity that just happens to have the same id.

To Reproduce
Steps to reproduce the behaviour:

  1. Spawn a prop
  2. Build accel
  3. Remove prop and spawn another (which will get the id that was just freed)
  4. Hit prop with traversal and print the entity (it'll be the second prop, not the one we hit)

Expected behaviour
Either a generic invalid entity would be given, the id would be given (allowing the user to cache the required entity data when building accel, then index that table with the id), or allow the user to pass a table along with the entity table, which would be indexed when a traversal hits an entity, and the contents at that index passed out through a new HitResult parameter, UserData.

[feature] Automate builds with GitHub Workflows

Is your feature request related to a problem? Please describe.
Using the bleeding edge features on master requires compiling from source, and to submit a Lua PR you'd still need to compile from source to test against the latest commits

Describe the solution you'd like
Using Travis CI or similar automate builds on pull requests and pushes, as well as requiring a successful build before a PR can be merged

[feature] Refactor material loading

Describe the solution you'd like
Currently it loads material flags on hit, which is a legacy from debugging, however this is extremely slow

Solution is to just cache material parameters at accel build time

Additional context
Would need to implement #16 first for cleanly storing all the data at build time

[feature] Load MRAOs

I already have everything implemented for using MRAO textures, however the material loading code currently doesnt populate the fields in the material

They'll probably be stored along with any future PBR maps in materials/vistrace

[feature] Rigged mesh support

Describe the solution you'd like
Transform meshes that contain bones using bone matrices and weights.

Additional context
While the wiki page for MeshVertex does not show bone weights as a member, I'm sure I've seen them present in prints of MeshVertex structs in the past.

[feature] Implement my BSP parser

Describe the solution you'd like
Replace the existing call to traceline with my BSP parser

Additional context
As it currently stands, the parser only works correctly when compiled with GCC
Compiling with MSVC (which is needed for source ABI compatibility) causes normal mapping to break

[feature] Energy loss compensation

Is your feature request related to a problem? Please describe.
Single scattering GGX at high roughness significantly reduces energy, especially at grazing angles, causing a black halo and an overall darkened appearance

Describe the solution you'd like
Yocto-GL provides a ready made compensator for schlick's based conductors based on https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf, however seems to provide no ready made solution for dielectrics (which makes sense given the drastically increased complexity).

Energy compensation is already used in the conductor, and somewhat integrated into the glossy dielectric BSDF in the form of the Frostbite normalised Disney diffuse, which is pretty much fine given the specular is far less noticeable.
However the specular transmission BSDF is severely affected by the single scattering energy loss, and should compensate for it.

Describe alternatives you've considered
Instead of using energy compensation on the transmission BSDF, we could stochastically sample multiple scattering, given the energy loss is so severe on rough dielectric transmissive surfaces, however it's slow and cumbersome to implement, along with introducing additional variance
https://eheitzresearch.wordpress.com/240-2/

[bug] Manual linking of libomp.lib required

Describe the bug
For some reason (at least on my machine) libomp.lib needs to be explicitly linked in CMake, despite using OpenMP::OpenMP_CXX and I have no idea why.

To Reproduce
Steps to reproduce the behaviour:

  1. Clone repo, set up, and compile to windows (any architecture)
  2. Remove the line that adds libomp.lib
  3. Recompile
  4. Undefined reference errors to all OpenMP functions

Expected behaviour
We should not need to link libomp.lib manually.

[feature] Implement TraceResult userdata object

Is your feature request related to a problem? Please describe.
Constructing a replica of the TraceResult table is extremely inefficient

Describe the solution you'd like
Implementing a userdata object would not only be orders of magnitude less stack code, but would allow lazy loading of certain fields (for instance, only normal mapping if the user calls TraceResult:GetNormal()

[feature] More streamlined integration

Idea

Rather than just providing a standalone dll that needs to be manually loaded and provides no documentation for the Starfall integration due to being sideloaded in, an optional GLua component could be used, that would automatically detect and require the binary, as well as populate documentation at runtime and provide fallbacks to the Starfall functions that check if the module was loaded, and throw a specific error explaining the issue if it's not (which would allow loading this VisTrace GLua component onto servers, to provide easier distribution of VisTrace Starfalls within the server compared to throwing a generic index error).

Installation Options

While providing this GLua component zipped with each release would work, it makes it unnecessarily annoying to install (having to manually update not only a binary but an addon too), the obvious solution to this is to distribute the GLua component on the Steam workshop with links back to here for the module, the downside to this however is it requires maintaining two separate instances of VisTrace, and version control with workshop seems to be far less sophisticated than Git, but should only need to be done once per full release.

[bug] Crash in HDRI sampling function

Describe the bug
Indexing out of range into the pdf version of the hdri
This happens seemingly randomly

Screenshots
image
image

Additional context
The HDRI's PDFs have been somewhat broken recently, possibly as a result of the port to Clang

[feature] Handle effects

Is your feature request related to a problem? Please describe.
Effects will render as melons

Describe the solution you'd like
We can't just blindly use the prop_dynamic stored in an effect, as the user may pass those entities explicitly.
The only possible solutions involve disabling rendering of an effect's model, then either requiring the user to explicitly pass the prop_dynamic (easy solution with obvious behaviour), or get the real entity off the effect and check whether the user already passed it explicitly (complex solution and the behaviour is inconsistent depending on whether you pass a dynamic prop along with an effect SENT.

I'll probably go with the former

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.