file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
2.5
98.5
max_line_length
int64
5
993
alphanum_fraction
float64
0.27
0.91
aws-samples/nvidia-omniverse-nucleus-on-amazon-ec2/src/lambda/common/aws_utils/ec2.py
# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: LicenseRef-.amazon.com.-AmznSL-1.0 # Licensed under the Amazon Software License http://aws.amazon.com/asl/ import os import logging import boto3 from botocore.exceptions import ClientError LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG") logger = logging.getLogger() logger.setLevel(LOG_LEVEL) client = boto3.client("ec2") ec2_resource = boto3.resource("ec2") autoscaling = boto3.client("autoscaling") def get_instance_public_dns_name(instanceId): instance = get_instance_description(instanceId) if instance is None: return None return instance["PublicDnsName"] def get_instance_private_dns_name(instanceId): instance = get_instance_description(instanceId) if instance is None: return None return instance["PrivateDnsName"] def get_instance_description(instanceId): response = client.describe_instances( InstanceIds=[instanceId], ) instances = response["Reservations"][0]["Instances"] if not instances: return None return instances[0] def get_instance_status(instanceId): response = client.describe_instance_status( Filters=[ { "Name": "string", "Values": [ "string", ], }, ], InstanceIds=[ "string", ], MaxResults=123, NextToken="string", DryRun=True | False, IncludeAllInstances=True | False, ) statuses = response["InstanceStatuses"][0] status = {"instanceStatus": None, "systemStatus": None} if statuses: status = { "instanceStatus": statuses["InstanceStatus"]["Status"], "systemStatus": statuses["SystemStatus"]["Status"], } return status def get_autoscaling_instance(groupName): response = autoscaling.describe_auto_scaling_groups( AutoScalingGroupNames=[groupName] ) logger.debug(response) instances = response['AutoScalingGroups'][0]["Instances"] if not instances: return None instanceIds = [] for i in instances: instanceIds.append(i["InstanceId"]) return instanceIds def update_tag_value(resourceIds: list, tagKey: str, tagValue: str): client.create_tags( Resources=resourceIds, Tags=[{ 'Key': tagKey, 'Value': tagValue }], ) def delete_tag(resourceIds: list, tagKey: str, tagValue: str): response = client.delete_tags( Resources=resourceIds, Tags=[{ 'Key': tagKey, 'Value': tagValue }], ) return response def get_instance_state(id): instance = ec2_resource.Instance(id) return instance.state['Name'] def get_instances_by_tag(tagKey, tagValue): instances = ec2_resource.instances.filter( Filters=[{'Name': 'tag:{}'.format(tagKey), 'Values': [tagValue]}]) if not instances: return None instanceIds = [] for i in instances: instanceIds.append(i.id) return instanceIds def get_instances_by_name(name): instances = get_instances_by_tag("Name", name) if not instances: logger.error(f"ERROR: Failed to get instances by tag: Name, {name}") return None return instances def get_active_instance(instances): for i in instances: instance_state = get_instance_state(i) logger.info(f"Instance: {i}. State: {instance_state}") if instance_state == "running" or instance_state == "pending": return i logger.warn(f"Instances are not active") return None def get_volumes_by_instance_id(id): instance = ec2_resource.Instance(id) volumes = instance.volumes.all() volumeIds = [] for i in volumes: volumeIds.append(i.id) return volumeIds def terminate_instances(instance_ids): response = client.terminate_instances(InstanceIds=instance_ids) logger.info(response) return response
4,068
Python
21.605555
76
0.630285
aws-samples/nvidia-omniverse-nucleus-on-amazon-ec2/src/lambda/common/aws_utils/ssm.py
# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: LicenseRef-.amazon.com.-AmznSL-1.0 # Licensed under the Amazon Software License http://aws.amazon.com/asl/ import os import time import logging import boto3 from botocore.exceptions import ClientError LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG") logger = logging.getLogger() logger.setLevel(LOG_LEVEL) client = boto3.client("ssm") def get_param_value(name) -> str: response = client.get_parameter(Name=name) logger.info(response) return response['Parameter']['Value'] def update_param_value(name, value) -> bool: response = client.put_parameter(Name=name, Value=value, Overwrite=True) logger.info(response) try: return (response['Version'] > 0) except ClientError as e: message = "Error calling SendCommand: {}".format(e) logger.error(message) return False def run_commands( instance_id, commands, document="AWS-RunPowerShellScript", comment="aws_utils.ssm.run_commands" ): """alt document options: AWS-RunShellScript """ # Run Commands logger.info("Calling SendCommand: {} for instance: {}".format( commands, instance_id)) attempt = 0 response = None while attempt < 20: attempt = attempt + 1 try: time.sleep(10 * attempt) logger.info("SendCommand, attempt #: {}".format(attempt)) response = client.send_command( InstanceIds=[instance_id], DocumentName=document, Parameters={"commands": commands}, Comment=comment, CloudWatchOutputConfig={ "CloudWatchLogGroupName": instance_id, "CloudWatchOutputEnabled": True, }, ) logger.info(response) if "Command" in response: break if attempt == 10: message = "Command did not execute successfully in time allowed." raise Exception(message) except ClientError as e: message = "Error calling SendCommand: {}".format(e) logger.error(message) continue if not response: message = "Command did not execute successfully in time allowed." raise Exception(message) # Check Command Status command_id = response["Command"]["CommandId"] logger.info( "Calling GetCommandInvocation for command: {} for instance: {}".format( command_id, instance_id ) ) attempt = 0 result = None while attempt < 10: attempt = attempt + 1 try: time.sleep(10 * attempt) logger.info("GetCommandInvocation, attempt #: {}".format(attempt)) result = client.get_command_invocation( CommandId=command_id, InstanceId=instance_id, ) if result["Status"] == "InProgress": logger.info("Command is running.") continue elif result["Status"] == "Success": logger.info("Command Output: {}".format( result["StandardOutputContent"])) if result["StandardErrorContent"]: message = "Command returned STDERR: {}".format( result["StandardErrorContent"]) logger.warning(message) break elif result["Status"] == "Failed": message = "Error Running Command: {}".format( result["StandardErrorContent"]) logger.error(message) raise Exception(message) else: message = "Command has an unhandled status, will continue: {}".format( e) logger.warning(message) continue except client.exceptions.InvocationDoesNotExist as e: message = "Error calling GetCommandInvocation: {}".format(e) logger.error(message) raise Exception(message) if not result or result["Status"] != "Success": message = "Command did not execute successfully in time allowed." raise Exception(message) return result
4,304
Python
30.195652
99
0.574814
aws-samples/nvidia-omniverse-nucleus-on-amazon-ec2/src/lambda/common/aws_utils/r53.py
# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: LicenseRef-.amazon.com.-AmznSL-1.0 # Licensed under the Amazon Software License http://aws.amazon.com/asl/ import boto3 client = boto3.client("route53") def update_hosted_zone_cname_record(hostedZoneID, rootDomain, domainPrefix, serverAddress): fqdn = f"{domainPrefix}.{rootDomain}" response = client.change_resource_record_sets( HostedZoneId=hostedZoneID, ChangeBatch={ "Comment": "Updating {fqdn}->{serverAddress} CNAME record", "Changes": [ { "Action": "UPSERT", "ResourceRecordSet": { "Name": fqdn, "Type": "CNAME", "TTL": 300, "ResourceRecords": [{"Value": serverAddress}], }, } ], }, ) return response def delete_hosted_zone_cname_record(hostedZoneID, rootDomain, domainPrefix, serverAddress): response = client.change_resource_record_sets( HostedZoneId=hostedZoneID, ChangeBatch={ "Comment": "string", "Changes": [ { "Action": "DELETE", "ResourceRecordSet": { "Name": f"{domainPrefix}.{rootDomain}", "Type": "CNAME", "ResourceRecords": [{"Value": serverAddress}], }, } ], }, ) # botocore.errorfactory.InvalidInput: An error occurred (InvalidInput) when calling the ChangeResourceRecordSets operation: Invalid request: # Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found none in Change with # [Action=DELETE, Name=nucleus-dev.awsps.myinstance.com, Type=CNAME, SetIdentifier=null] return response
1,989
Python
33.310344
144
0.553042
aws-samples/nvidia-omniverse-nucleus-on-amazon-ec2/src/lambda/common/aws_utils/__init__.py
# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: LicenseRef-.amazon.com.-AmznSL-1.0 # Licensed under the Amazon Software License http://aws.amazon.com/asl/
210
Python
41.199992
73
0.766667
aws-samples/nvidia-omniverse-nucleus-on-amazon-ec2/src/lambda/common/aws_utils/sm.py
# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: LicenseRef-.amazon.com.-AmznSL-1.0 # Licensed under the Amazon Software License http://aws.amazon.com/asl/ import json import boto3 SM = boto3.client("secretsmanager") def get_secret(secret_name): response = SM.get_secret_value(SecretId=secret_name) secret = json.loads(response["SecretString"]) return secret
429
Python
25.874998
73
0.745921
aws-samples/nvidia-omniverse-nucleus-on-amazon-ec2/src/lambda/common/config/nucleus.py
def start_nucleus_config() -> list[str]: return ''' cd /opt/ove/base_stack || exit 1 echo "STARTING NUCLEUS STACK ----------------------------------" docker-compose --env-file nucleus-stack.env -f nucleus-stack-ssl.yml start '''.splitlines() def stop_nucleus_config() -> list[str]: return ''' cd /opt/ove/base_stack || exit 1 echo "STOPPING NUCLEUS STACK ----------------------------------" docker-compose --env-file nucleus-stack.env -f nucleus-stack-ssl.yml stop '''.splitlines() def restart_nucleus_config() -> list[str]: return ''' cd /opt/ove/base_stack || exit 1 echo "RESTARTING NUCLEUS STACK ----------------------------------" docker-compose --env-file nucleus-stack.env -f nucleus-stack-ssl.yml restart '''.splitlines() def get_config(artifacts_bucket_name: str, full_domain: str, nucleus_build: str, ov_main_password: str, ov_service_password: str) -> list[str]: return f''' echo "------------------------ NUCLEUS SERVER CONFIG ------------------------" echo "UPDATING AND INSTALLING DEPS ----------------------------------" sudo apt-get update -y -q && sudo apt-get upgrade -y sudo apt-get install dialog apt-utils -y echo "INSTALLING AWS CLI ----------------------------------" sudo curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" sudo apt-get install unzip sudo unzip awscliv2.zip sudo ./aws/install sudo rm awscliv2.zip sudo rm -fr ./aws/install echo "INSTALLING PYTHON ----------------------------------" sudo apt-get -y install python3.9 sudo curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py sudo python3.9 get-pip.py sudo pip3 install --upgrade pip sudo pip3 --version echo "INSTALLING DOCKER ----------------------------------" sudo apt-get remove docker docker-engine docker.io containerd runc sudo apt-get -y install apt-transport-https ca-certificates curl gnupg-agent software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get -y update sudo apt-get -y install docker-ce docker-ce-cli containerd.io sudo systemctl enable --now docker echo "INSTALLING DOCKER COMPOSE ----------------------------------" sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose echo "INSTALLING NUCLEUS TOOLS ----------------------------------" sudo mkdir -p /opt/ove cd /opt/ove || exit 1 aws s3 cp --recursive s3://{artifacts_bucket_name}/tools/nucleusServer/ ./nucleusServer cd nucleusServer || exit 1 sudo pip3 install -r requirements.txt echo "UNPACKAGING NUCLEUS STACK ----------------------------------" sudo tar xzvf stack/{nucleus_build}.tar.gz -C /opt/ove --strip-components=1 cd /opt/ove/base_stack || exit 1 omniverse_data_path=/var/lib/omni/nucleus-data nucleusHost=$(curl -s http://169.254.169.254/latest/meta-data/hostname) sudo nst generate-nucleus-stack-env --server-ip $nucleusHost --reverse-proxy-domain {full_domain} --instance-name nucleus_server --master-password {ov_main_password} --service-password {ov_service_password} --data-root $omniverse_data_path chmod +x ./generate-sample-insecure-secrets.sh ./generate-sample-insecure-secrets.sh echo "PULLING NUCLEUS IMAGES ----------------------------------" docker-compose --env-file nucleus-stack.env -f nucleus-stack-ssl.yml pull echo "STARTING NUCLEUS STACK ----------------------------------" docker-compose --env-file nucleus-stack.env -f nucleus-stack-ssl.yml up -d docker-compose --env-file nucleus-stack.env -f nucleus-stack-ssl.yml ps -a '''.splitlines()
4,176
Python
48.72619
247
0.582136
aws-samples/nvidia-omniverse-nucleus-on-amazon-ec2/src/lambda/common/config/reverseProxy.py
def get_config(artifacts_bucket_name: str, nucleus_address: str, full_domain: str) -> list[str]: return f''' echo "------------------------ REVERSE PROXY CONFIG ------------------------" echo "UPDATING PACKAGES ----------------------------------" sudo yum update -y echo "INSTALLING DEPENDENCIES ----------------------------------" sudo yum install -y aws-cfn-bootstrap gcc openssl-devel bzip2-devel libffi-devel zlib-devel echo "INSTALLING NGINX ----------------------------------" sudo yum install -y amazon-linux-extras sudo amazon-linux-extras enable nginx1 sudo yum install -y nginx sudo nginx -v echo "INSTALLING PYTHON ----------------------------------" sudo wget https://www.python.org/ftp/python/3.9.9/Python-3.9.9.tgz -P /opt/python3.9 cd /opt/python3.9 || exit 1 sudo tar xzf Python-3.9.9.tgz cd Python-3.9.9 || exit 1 sudo ./configure --prefix=/usr --enable-optimizations sudo make install echo "------------------------ REVERSE PROXY CONFIG ------------------------" echo "INSTALLING REVERSE PROXY TOOLS ----------------------------------" cd /opt || exit 1 sudo aws s3 cp --recursive s3://{artifacts_bucket_name}/tools/reverseProxy/ ./reverseProxy cd reverseProxy || exit 1 pip3 --version sudo pip3 install -r requirements.txt sudo rpt generate-nginx-config --domain {full_domain} --server-address {nucleus_address} echo "STARTING NGINX ----------------------------------" sudo service nginx restart '''.splitlines()
1,670
Python
44.162161
99
0.511976
arhix52/Strelka/conanfile.py
import os from conan import ConanFile from conan.tools.cmake import cmake_layout from conan.tools.files import copy class StrelkaRecipe(ConanFile): settings = "os", "compiler", "build_type", "arch" generators = "CMakeToolchain", "CMakeDeps" def requirements(self): self.requires("glm/cci.20230113") self.requires("spdlog/[>=1.4.1]") self.requires("imgui/1.89.3") self.requires("glfw/3.3.8") self.requires("stb/cci.20230920") self.requires("glad/0.1.36") self.requires("doctest/2.4.11") self.requires("cxxopts/3.1.1") self.requires("tinygltf/2.8.19") self.requires("nlohmann_json/3.11.3") def generate(self): copy(self, "*glfw*", os.path.join(self.dependencies["imgui"].package_folder, "res", "bindings"), os.path.join(self.source_folder, "external", "imgui")) copy(self, "*opengl3*", os.path.join(self.dependencies["imgui"].package_folder, "res", "bindings"), os.path.join(self.source_folder, "external", "imgui")) copy(self, "*metal*", os.path.join(self.dependencies["imgui"].package_folder, "res", "bindings"), os.path.join(self.source_folder, "external", "imgui")) def layout(self): cmake_layout(self)
1,294
Python
37.088234
87
0.619784
arhix52/Strelka/BuildOpenUSD.md
USD building: VS2019 + python 3.10 To build debug on windows: python USD\build_scripts\build_usd.py "C:\work\USD_build_debug" --python --materialx --build-variant debug For USD 23.03 you could use VS2022 Linux: * python3 ./OpenUSD/build_scripts/build_usd.py /home/<user>/work/OpenUSD_build/ --python --materialx
315
Markdown
30.599997
106
0.746032
arhix52/Strelka/README.md
# Strelka Path tracing render based on NVIDIA OptiX + NVIDIA MDL and Apple Metal ## OpenUSD Hydra render delegate ![Kitchen Set from OpenUSD](images/Kitchen_2048i_4d_2048spp_0.png) ## Basis curves support ![Hairs](images/hairmat_2_light_10000i_6d_10000spp_0.png) ![Einar](images/einar_1024i_3d_1024spp_0.png) ## Project Dependencies OpenUSD https://github.com/PixarAnimationStudios/OpenUSD * Set evn var: `USD_DIR=c:\work\USD_build` OptiX * Set evn var: `OPTIX_DIR=C:\work\OptiX SDK 8.0.0` Download MDL sdk (for example: mdl-sdk-367100.2992): https://developer.nvidia.com/nvidia-mdl-sdk-get-started * unzip content to /external/mdl-sdk/ LLVM 12.0.1 (https://github.com/llvm/llvm-project/releases/tag/llvmorg-12.0.1) for MDL ptx code generator * for win: https://github.com/llvm/llvm-project/releases/download/llvmorg-12.0.1/LLVM-12.0.1-win64.exe * for linux: https://github.com/llvm/llvm-project/releases/download/llvmorg-12.0.1/clang+llvm-12.0.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz * install it to `c:\work` for example * add to PATH: `c:\work\LLVM\bin` * extract 2 header files files from external/clang12_patched to `C:\work\LLVM\lib\clang\12.0.1\include` Strelka uses conan https://conan.io/ * install conan: `pip install conan` * install ninja [https://ninja-build.org/] build system: `sudo apt install ninja-build` detect conan profile: `conan profile detect --force` 1. `conan install . --build=missing --settings=build_type=Debug` 2. `cd build` 3. `cmake .. -G "Visual Studio 17 2022" -DCMAKE_TOOLCHAIN_FILE=generators\conan_toolchain.cmake` 4. `cmake --build . --config Debug` On Mac/Linux: 1. `conan install . -c tools.cmake.cmaketoolchain:generator=Ninja -c tools.system.package_manager:mode=install -c tools.system.package_manager:sudo=True --build=missing --settings=build_type=Debug` 2. `cd build/Debug` 3. `source ./generators/conanbuild.sh` 4. `cmake ../.. -DCMAKE_TOOLCHAIN_FILE=generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Debug` 5. `cmake --build .` #### Installation #### Launch ## Synopsis Strelka -s <USD Scene path> [OPTION...] positional parameters -s, --scene arg scene path (default: "") -i, --iteration arg Iteration to capture (default: -1) -h, --help Print usage To set log level use `export SPDLOG_LEVEL=debug` The available log levels are: trace, debug, info, warn, and err. ## Example ./Strelka -s misc/coffeemaker.usdc -i 100 ## USD USD env: export USD_DIR=/Users/<user>/work/usd_build/ export PATH=/Users/<user>/work/usd_build/bin:$PATH export PYTHONPATH=/Users/<user>/work/usd_build/lib/python:$PYTHONPATH Install plugin: cmake --install . --component HdStrelka ## License * USD plugin design and material translation code based on Pablo Gatling code: https://github.com/pablode/gatling
2,849
Markdown
33.337349
197
0.713935
arhix52/Strelka/src/HdStrelka/RenderParam.h
#pragma once #include "pxr/pxr.h" #include "pxr/imaging/hd/renderDelegate.h" #include "pxr/imaging/hd/renderThread.h" #include <scene/scene.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaRenderParam final : public HdRenderParam { public: HdStrelkaRenderParam(oka::Scene* scene, HdRenderThread* renderThread, std::atomic<int>* sceneVersion) : mScene(scene), mRenderThread(renderThread), mSceneVersion(sceneVersion) { } virtual ~HdStrelkaRenderParam() = default; /// Accessor for the top-level embree scene. oka::Scene* AcquireSceneForEdit() { mRenderThread->StopRender(); (*mSceneVersion)++; return mScene; } private: oka::Scene* mScene; /// A handle to the global render thread. HdRenderThread* mRenderThread; /// A version counter for edits to mScene. std::atomic<int>* mSceneVersion; }; PXR_NAMESPACE_CLOSE_SCOPE
901
C
24.055555
105
0.694784
arhix52/Strelka/src/HdStrelka/BasisCurves.h
#pragma once #include <pxr/pxr.h> #include <pxr/imaging/hd/basisCurves.h> #include <scene/scene.h> #include <pxr/base/gf/vec2f.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaBasisCurves final : public HdBasisCurves { public: HF_MALLOC_TAG_NEW("new HdStrelkaBasicCurves"); HdStrelkaBasisCurves(const SdfPath& id, oka::Scene* scene); ~HdStrelkaBasisCurves() override; void Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, const TfToken& reprToken) override; HdDirtyBits GetInitialDirtyBitsMask() const override; void _ConvertCurve(); const std::vector<glm::float3>& GetPoints() const; const std::vector<float>& GetWidths() const; const std::vector<uint32_t>& GetVertexCounts() const; const GfMatrix4d& GetPrototypeTransform() const; const char* getName() const; protected: void _InitRepr(const TfToken& reprName, HdDirtyBits* dirtyBits) override; HdDirtyBits _PropagateDirtyBits(HdDirtyBits bits) const override; private: bool _FindPrimvar(HdSceneDelegate* sceneDelegate, const TfToken& primvarName, HdInterpolation& interpolation) const; void _PullPrimvars(HdSceneDelegate* sceneDelegate, VtVec3fArray& points, VtVec3fArray& normals, VtFloatArray& widths, bool& indexedNormals, bool& indexedUVs, GfVec3f& color, bool& hasColor) const; void _UpdateGeometry(HdSceneDelegate* sceneDelegate); oka::Scene* mScene; std::string mName; GfVec3f mColor; VtIntArray mVertexCounts; VtVec3fArray mPoints; VtVec3fArray mNormals; VtFloatArray mWidths; GfMatrix4d m_prototypeTransform; HdBasisCurvesTopology mTopology; std::vector<glm::float3> mCurvePoints; std::vector<float> mCurveWidths; std::vector<uint32_t> mCurveVertexCounts; // std::vector<GfVec2f> m_uvs; }; PXR_NAMESPACE_CLOSE_SCOPE
2,048
C
28.271428
120
0.67334
arhix52/Strelka/src/HdStrelka/Tokens.cpp
#include "Tokens.h" PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PUBLIC_TOKENS(HdStrelkaSettingsTokens, HD_STRELKA_SETTINGS_TOKENS); TF_DEFINE_PUBLIC_TOKENS(HdStrelkaNodeIdentifiers, HD_STRELKA_NODE_IDENTIFIER_TOKENS); TF_DEFINE_PUBLIC_TOKENS(HdStrelkaSourceTypes, HD_STRELKA_SOURCE_TYPE_TOKENS); TF_DEFINE_PUBLIC_TOKENS(HdStrelkaDiscoveryTypes, HD_STRELKA_DISCOVERY_TYPE_TOKENS); TF_DEFINE_PUBLIC_TOKENS(HdStrelkaRenderContexts, HD_STRELKA_RENDER_CONTEXT_TOKENS); TF_DEFINE_PUBLIC_TOKENS(HdStrelkaNodeContexts, HD_STRELKA_NODE_CONTEXT_TOKENS); PXR_NAMESPACE_CLOSE_SCOPE
564
C++
42.461535
85
0.833333
arhix52/Strelka/src/HdStrelka/MdlDiscoveryPlugin.h
#pragma once #include <pxr/usd/ndr/discoveryPlugin.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaMdlDiscoveryPlugin final : public NdrDiscoveryPlugin { public: NdrNodeDiscoveryResultVec DiscoverNodes(const Context& ctx) override; const NdrStringVec& GetSearchURIs() const override; }; PXR_NAMESPACE_CLOSE_SCOPE
317
C
18.874999
71
0.807571
arhix52/Strelka/src/HdStrelka/Material.h
#pragma once #include "materialmanager.h" #include "MaterialNetworkTranslator.h" #include <pxr/imaging/hd/material.h> #include <pxr/imaging/hd/sceneDelegate.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaMaterial final : public HdMaterial { public: HF_MALLOC_TAG_NEW("new HdStrelkaMaterial"); HdStrelkaMaterial(const SdfPath& id, const MaterialNetworkTranslator& translator); ~HdStrelkaMaterial() override; HdDirtyBits GetInitialDirtyBitsMask() const override; void Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) override; const std::string& GetStrelkaMaterial() const; bool isMdl() const { return mIsMdl; } std::string getFileUri() { return mMdlFileUri; } std::string getSubIdentifier() { return mMdlSubIdentifier; } const std::vector<oka::MaterialManager::Param>& getParams() const { return mMaterialParams; } private: const MaterialNetworkTranslator& m_translator; bool mIsMdl = false; std::string mMaterialXCode; // MDL related std::string mMdlFileUri; std::string mMdlSubIdentifier; std::vector<oka::MaterialManager::Param> mMaterialParams; }; PXR_NAMESPACE_CLOSE_SCOPE
1,258
C
21.890909
107
0.709062
arhix52/Strelka/src/HdStrelka/Light.cpp
#include "Light.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/compatibility.hpp> #include <pxr/imaging/hd/instancer.h> #include <pxr/imaging/hd/meshUtil.h> #include <pxr/imaging/hd/smoothNormals.h> #include <pxr/imaging/hd/vertexAdjacency.h> PXR_NAMESPACE_OPEN_SCOPE // Lookup table from: // Colour Rendering of Spectra // by John Walker // https://www.fourmilab.ch/documents/specrend/specrend.c // // Covers range from 1000k to 10000k in 500k steps // assuming Rec709 / sRGB colorspace chromaticity. // // NOTE: 6500K doesn't give a pure white because the D65 // illuminant used by Rec. 709 doesn't lie on the // Planckian Locus. We would need to compute the // Correlated Colour Temperature (CCT) using Ohno's // method to get pure white. Maybe one day. // // Note that the beginning and ending knots are repeated to simplify // boundary behavior. The last 4 knots represent the segment starting // at 1.0. // static GfVec3f const _blackbodyRGB[] = { GfVec3f(1.000000f, 0.027490f, 0.000000f), // 1000 K (Approximation) GfVec3f(1.000000f, 0.027490f, 0.000000f), // 1000 K (Approximation) GfVec3f(1.000000f, 0.149664f, 0.000000f), // 1500 K (Approximation) GfVec3f(1.000000f, 0.256644f, 0.008095f), // 2000 K GfVec3f(1.000000f, 0.372033f, 0.067450f), // 2500 K GfVec3f(1.000000f, 0.476725f, 0.153601f), // 3000 K GfVec3f(1.000000f, 0.570376f, 0.259196f), // 3500 K GfVec3f(1.000000f, 0.653480f, 0.377155f), // 4000 K GfVec3f(1.000000f, 0.726878f, 0.501606f), // 4500 K GfVec3f(1.000000f, 0.791543f, 0.628050f), // 5000 K GfVec3f(1.000000f, 0.848462f, 0.753228f), // 5500 K GfVec3f(1.000000f, 0.898581f, 0.874905f), // 6000 K GfVec3f(1.000000f, 0.942771f, 0.991642f), // 6500 K GfVec3f(0.906947f, 0.890456f, 1.000000f), // 7000 K GfVec3f(0.828247f, 0.841838f, 1.000000f), // 7500 K GfVec3f(0.765791f, 0.801896f, 1.000000f), // 8000 K GfVec3f(0.715255f, 0.768579f, 1.000000f), // 8500 K GfVec3f(0.673683f, 0.740423f, 1.000000f), // 9000 K GfVec3f(0.638992f, 0.716359f, 1.000000f), // 9500 K GfVec3f(0.609681f, 0.695588f, 1.000000f), // 10000 K GfVec3f(0.609681f, 0.695588f, 1.000000f), // 10000 K GfVec3f(0.609681f, 0.695588f, 1.000000f) // 10000 K }; // Catmull-Rom basis static const float _basis[4][4] = { { -0.5f, 1.5f, -1.5f, 0.5f }, { 1.f, -2.5f, 2.0f, -0.5f }, { -0.5f, 0.0f, 0.5f, 0.0f }, { 0.f, 1.0f, 0.0f, 0.0f } }; static inline float _Rec709RgbToLuma(const GfVec3f& rgb) { return GfDot(rgb, GfVec3f(0.2126f, 0.7152f, 0.0722f)); } static GfVec3f _BlackbodyTemperatureAsRgb(float temp) { // Catmull-Rom interpolation of _blackbodyRGB constexpr int numKnots = sizeof(_blackbodyRGB) / sizeof(_blackbodyRGB[0]); // Parametric distance along spline const float u_spline = GfClamp((temp - 1000.0f) / 9000.0f, 0.0f, 1.0f); // Last 4 knots represent a trailing segment starting at u_spline==1.0, // to simplify boundary behavior constexpr int numSegs = (numKnots - 4); const float x = u_spline * numSegs; const int seg = int(floor(x)); const float u_seg = x - seg; // Parameter within segment // Knot values for this segment GfVec3f k0 = _blackbodyRGB[seg + 0]; GfVec3f k1 = _blackbodyRGB[seg + 1]; GfVec3f k2 = _blackbodyRGB[seg + 2]; GfVec3f k3 = _blackbodyRGB[seg + 3]; // Compute cubic coefficients. Could fold constants (zero, one) here // if speed is a concern. GfVec3f a = _basis[0][0] * k0 + _basis[0][1] * k1 + _basis[0][2] * k2 + _basis[0][3] * k3; GfVec3f b = _basis[1][0] * k0 + _basis[1][1] * k1 + _basis[1][2] * k2 + _basis[1][3] * k3; GfVec3f c = _basis[2][0] * k0 + _basis[2][1] * k1 + _basis[2][2] * k2 + _basis[2][3] * k3; GfVec3f d = _basis[3][0] * k0 + _basis[3][1] * k1 + _basis[3][2] * k2 + _basis[3][3] * k3; // Eval cubic polynomial. GfVec3f rgb = ((a * u_seg + b) * u_seg + c) * u_seg + d; // Normalize to the same luminance as (1,1,1) rgb /= _Rec709RgbToLuma(rgb); // Clamp at zero, since the spline can produce small negative values, // e.g. in the blue component at 1300k. rgb[0] = GfMax(rgb[0], 0.f); rgb[1] = GfMax(rgb[1], 0.f); rgb[2] = GfMax(rgb[2], 0.f); return rgb; } HdStrelkaLight::HdStrelkaLight(const SdfPath& id, TfToken const& lightType) : HdLight(id), mLightType(lightType) { } HdStrelkaLight::~HdStrelkaLight() { } void HdStrelkaLight::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) { TF_UNUSED(renderParam); bool pullLight = (*dirtyBits & DirtyBits::DirtyParams); *dirtyBits = DirtyBits::Clean; if (!pullLight) { return; } const SdfPath& id = GetId(); // const VtValue& resource = sceneDelegate->GetMaterialResource(id); // Get the color of the light GfVec3f hdc = sceneDelegate->GetLightParamValue(id, HdLightTokens->color).Get<GfVec3f>(); // Color temperature VtValue enableColorTemperatureVal = sceneDelegate->GetLightParamValue(id, HdLightTokens->enableColorTemperature); if (enableColorTemperatureVal.GetWithDefault<bool>(false)) { VtValue colorTemperatureVal = sceneDelegate->GetLightParamValue(id, HdLightTokens->colorTemperature); if (colorTemperatureVal.IsHolding<float>()) { float colorTemperature = colorTemperatureVal.Get<float>(); hdc = GfCompMult(hdc, _BlackbodyTemperatureAsRgb(colorTemperature)); } } // Intensity float intensity = sceneDelegate->GetLightParamValue(id, HdLightTokens->intensity).Get<float>(); // Exposure float exposure = sceneDelegate->GetLightParamValue(id, HdLightTokens->exposure).Get<float>(); intensity *= powf(2.0f, GfClamp(exposure, -50.0f, 50.0f)); // Transform { GfMatrix4d transform = sceneDelegate->GetTransform(id); glm::float4x4 xform; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { xform[i][j] = (float)transform[i][j]; } } mLightDesc.xform = xform; mLightDesc.useXform = true; } mLightDesc.color = glm::float3(hdc[0], hdc[1], hdc[2]); mLightDesc.intensity = intensity; if (mLightType == HdPrimTypeTokens->rectLight) { mLightDesc.type = 0; float width = 0.0f; float height = 0.0f; VtValue widthVal = sceneDelegate->GetLightParamValue(id, HdLightTokens->width); if (widthVal.IsHolding<float>()) { width = widthVal.Get<float>(); } VtValue heightVal = sceneDelegate->GetLightParamValue(id, HdLightTokens->height); if (heightVal.IsHolding<float>()) { height = heightVal.Get<float>(); } mLightDesc.height = height; mLightDesc.width = width; } else if (mLightType == HdPrimTypeTokens->diskLight || mLightType == HdPrimTypeTokens->sphereLight) { mLightDesc.type = mLightType == HdPrimTypeTokens->diskLight ? 1 : 2; float radius = 0.0; VtValue radiusVal = sceneDelegate->GetLightParamValue(id, HdLightTokens->radius); if (radiusVal.IsHolding<float>()) { radius = radiusVal.Get<float>(); } mLightDesc.radius = radius * mLightDesc.xform[0][0]; // uniform scale } else if (mLightType == HdPrimTypeTokens->distantLight) { float angle = 0.0f; mLightDesc.type = 3; // TODO: move to enum VtValue angleVal = sceneDelegate->GetLightParamValue(id, HdLightTokens->angle); if (angleVal.IsHolding<float>()) { angle = angleVal.Get<float>(); } mLightDesc.halfAngle = angle * 0.5f * (M_PI / 180.0f); mLightDesc.intensity /= M_PI * powf(sin(mLightDesc.halfAngle), 2.0f); } } HdDirtyBits HdStrelkaLight::GetInitialDirtyBitsMask() const { return (DirtyParams | DirtyTransform); } oka::Scene::UniformLightDesc HdStrelkaLight::getLightDesc() { return mLightDesc; } PXR_NAMESPACE_CLOSE_SCOPE
8,162
C++
35.936651
117
0.636486
arhix52/Strelka/src/HdStrelka/MdlParserPlugin.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "MdlParserPlugin.h" #include <pxr/base/tf/staticTokens.h> #include <pxr/usd/sdr/shaderNode.h> #include <pxr/usd/ar/resolver.h> #include "pxr/usd/ar/resolvedPath.h" #include "pxr/usd/ar/asset.h" #include <pxr/usd/ar/ar.h> //#include "Tokens.h" PXR_NAMESPACE_OPEN_SCOPE NDR_REGISTER_PARSER_PLUGIN(HdStrelkaMdlParserPlugin); // clang-format off TF_DEFINE_PRIVATE_TOKENS(_tokens, (mdl) (subIdentifier)); // clang-format on NdrNodeUniquePtr HdStrelkaMdlParserPlugin::Parse(const NdrNodeDiscoveryResult& discoveryResult) { NdrTokenMap metadata = discoveryResult.metadata; metadata[_tokens->subIdentifier] = discoveryResult.subIdentifier; return std::make_unique<SdrShaderNode>(discoveryResult.identifier, discoveryResult.version, discoveryResult.name, discoveryResult.family, _tokens->mdl, discoveryResult.sourceType, discoveryResult.uri, discoveryResult.resolvedUri, NdrPropertyUniquePtrVec{}, metadata); } const NdrTokenVec& HdStrelkaMdlParserPlugin::GetDiscoveryTypes() const { static NdrTokenVec s_discoveryTypes{ _tokens->mdl }; return s_discoveryTypes; } const TfToken& HdStrelkaMdlParserPlugin::GetSourceType() const { return _tokens->mdl; } PXR_NAMESPACE_CLOSE_SCOPE
2,153
C++
34.311475
119
0.681839
arhix52/Strelka/src/HdStrelka/Instancer.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "Instancer.h" #include <pxr/base/gf/quatd.h> #include <pxr/imaging/hd/sceneDelegate.h> PXR_NAMESPACE_OPEN_SCOPE HdStrelkaInstancer::HdStrelkaInstancer(HdSceneDelegate* delegate, const SdfPath& id) : HdInstancer(delegate, id) { } HdStrelkaInstancer::~HdStrelkaInstancer() { } void HdStrelkaInstancer::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) { TF_UNUSED(renderParam); _UpdateInstancer(sceneDelegate, dirtyBits); const SdfPath& id = GetId(); if (!HdChangeTracker::IsAnyPrimvarDirty(*dirtyBits, id)) { return; } const HdPrimvarDescriptorVector& primvars = sceneDelegate->GetPrimvarDescriptors(id, HdInterpolation::HdInterpolationInstance); for (const HdPrimvarDescriptor& primvar : primvars) { TfToken primName = primvar.name; if (primName != HdInstancerTokens->translate && primName != HdInstancerTokens->rotate && primName != HdInstancerTokens->scale && primName != HdInstancerTokens->instanceTransform) { continue; } if (!HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, primName)) { continue; } VtValue value = sceneDelegate->Get(id, primName); m_primvarMap[primName] = value; } } VtMatrix4dArray HdStrelkaInstancer::ComputeInstanceTransforms(const SdfPath& prototypeId) { HdSceneDelegate* sceneDelegate = GetDelegate(); const SdfPath& id = GetId(); // Calculate instance transforms for this instancer. VtValue boxedTranslates = m_primvarMap[HdInstancerTokens->translate]; VtValue boxedRotates = m_primvarMap[HdInstancerTokens->rotate]; VtValue boxedScales = m_primvarMap[HdInstancerTokens->scale]; VtValue boxedInstanceTransforms = m_primvarMap[HdInstancerTokens->instanceTransform]; VtVec3fArray translates; if (boxedTranslates.IsHolding<VtVec3fArray>()) { translates = boxedTranslates.UncheckedGet<VtVec3fArray>(); } else if (!boxedTranslates.IsEmpty()) { TF_CODING_WARNING("Instancer translate values are not of type Vec3f!"); } VtVec4fArray rotates; if (boxedRotates.IsHolding<VtVec4fArray>()) { rotates = boxedRotates.Get<VtVec4fArray>(); } else if (!boxedRotates.IsEmpty()) { TF_CODING_WARNING("Instancer rotate values are not of type Vec3f!"); } VtVec3fArray scales; if (boxedScales.IsHolding<VtVec3fArray>()) { scales = boxedScales.Get<VtVec3fArray>(); } else if (!boxedScales.IsEmpty()) { TF_CODING_WARNING("Instancer scale values are not of type Vec3f!"); } VtMatrix4dArray instanceTransforms; if (boxedInstanceTransforms.IsHolding<VtMatrix4dArray>()) { instanceTransforms = boxedInstanceTransforms.Get<VtMatrix4dArray>(); } GfMatrix4d instancerTransform = sceneDelegate->GetInstancerTransform(id); const VtIntArray& instanceIndices = sceneDelegate->GetInstanceIndices(id, prototypeId); VtMatrix4dArray transforms; transforms.resize(instanceIndices.size()); for (size_t i = 0; i < instanceIndices.size(); i++) { int instanceIndex = instanceIndices[i]; GfMatrix4d mat = instancerTransform; GfMatrix4d temp; if (i < translates.size()) { auto trans = GfVec3d(translates[instanceIndex]); temp.SetTranslate(trans); mat = temp * mat; } if (i < rotates.size()) { GfVec4f rot = rotates[instanceIndex]; temp.SetRotate(GfQuatd(rot[0], rot[1], rot[2], rot[3])); mat = temp * mat; } if (i < scales.size()) { auto scale = GfVec3d(scales[instanceIndex]); temp.SetScale(scale); mat = temp * mat; } if (i < instanceTransforms.size()) { temp = instanceTransforms[instanceIndex]; mat = temp * mat; } transforms[i] = mat; } // Calculate instance transforms for all instancer instances. const SdfPath& parentId = GetParentId(); if (parentId.IsEmpty()) { return transforms; } const HdRenderIndex& renderIndex = sceneDelegate->GetRenderIndex(); HdInstancer* boxedParentInstancer = renderIndex.GetInstancer(parentId); HdStrelkaInstancer* parentInstancer = dynamic_cast<HdStrelkaInstancer*>(boxedParentInstancer); VtMatrix4dArray parentTransforms = parentInstancer->ComputeInstanceTransforms(id); VtMatrix4dArray transformProducts; transformProducts.resize(parentTransforms.size() * transforms.size()); for (size_t i = 0; i < parentTransforms.size(); i++) { for (size_t j = 0; j < transforms.size(); j++) { size_t index = i * transforms.size() + j; transformProducts[index] = transforms[j] * parentTransforms[i]; } } return transformProducts; } PXR_NAMESPACE_CLOSE_SCOPE
5,927
C++
29.556701
131
0.639615
arhix52/Strelka/src/HdStrelka/RenderDelegate.h
#pragma once #include <pxr/imaging/hd/renderDelegate.h> #include "MaterialNetworkTranslator.h" #include <render/common.h> #include <scene/scene.h> #include <render/render.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaRenderDelegate final : public HdRenderDelegate { public: HdStrelkaRenderDelegate(const HdRenderSettingsMap& settingsMap, const MaterialNetworkTranslator& translator); ~HdStrelkaRenderDelegate() override; void SetDrivers(HdDriverVector const& drivers) override; HdRenderSettingDescriptorList GetRenderSettingDescriptors() const override; HdRenderPassSharedPtr CreateRenderPass(HdRenderIndex* index, const HdRprimCollection& collection) override; HdResourceRegistrySharedPtr GetResourceRegistry() const override; void CommitResources(HdChangeTracker* tracker) override; HdInstancer* CreateInstancer(HdSceneDelegate* delegate, const SdfPath& id) override; void DestroyInstancer(HdInstancer* instancer) override; HdAovDescriptor GetDefaultAovDescriptor(const TfToken& name) const override; /* Rprim */ const TfTokenVector& GetSupportedRprimTypes() const override; HdRprim* CreateRprim(const TfToken& typeId, const SdfPath& rprimId) override; void DestroyRprim(HdRprim* rPrim) override; /* Sprim */ const TfTokenVector& GetSupportedSprimTypes() const override; HdSprim* CreateSprim(const TfToken& typeId, const SdfPath& sprimId) override; HdSprim* CreateFallbackSprim(const TfToken& typeId) override; void DestroySprim(HdSprim* sprim) override; /* Bprim */ const TfTokenVector& GetSupportedBprimTypes() const override; HdBprim* CreateBprim(const TfToken& typeId, const SdfPath& bprimId) override; HdBprim* CreateFallbackBprim(const TfToken& typeId) override; void DestroyBprim(HdBprim* bprim) override; TfToken GetMaterialBindingPurpose() const override; // In a USD file, there can be multiple networks associated with a material: // token outputs:mdl:surface.connect = </Root/Glass.outputs:out> // token outputs:surface.connect = </Root/GlassPreviewSurface.outputs:surface> // This function returns the order of preference used when selecting one for rendering. TfTokenVector GetMaterialRenderContexts() const override; TfTokenVector GetShaderSourceTypes() const override; oka::SharedContext& getSharedContext(); private: const MaterialNetworkTranslator& m_translator; HdRenderSettingDescriptorList m_settingDescriptors; HdResourceRegistrySharedPtr m_resourceRegistry; const TfTokenVector SUPPORTED_BPRIM_TYPES = { HdPrimTypeTokens->renderBuffer }; const TfTokenVector SUPPORTED_RPRIM_TYPES = { HdPrimTypeTokens->mesh, HdPrimTypeTokens->basisCurves }; const TfTokenVector SUPPORTED_SPRIM_TYPES = { HdPrimTypeTokens->camera, HdPrimTypeTokens->material, HdPrimTypeTokens->light, HdPrimTypeTokens->rectLight, HdPrimTypeTokens->diskLight, HdPrimTypeTokens->sphereLight, HdPrimTypeTokens->distantLight, }; oka::SharedContext* mSharedCtx; oka::Scene mScene; oka::Render* mRenderer; }; PXR_NAMESPACE_CLOSE_SCOPE
3,149
C
33.23913
113
0.768498
arhix52/Strelka/src/HdStrelka/RenderDelegate.cpp
#include "RenderDelegate.h" #include "Camera.h" #include "Instancer.h" #include "Light.h" #include "Material.h" #include "Mesh.h" #include "BasisCurves.h" #include "RenderBuffer.h" #include "RenderPass.h" #include "Tokens.h" #include <pxr/base/gf/vec4f.h> #include <pxr/imaging/hd/resourceRegistry.h> #include <log.h> #include <memory> PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS(_Tokens, (HdStrelkaDriver)); HdStrelkaRenderDelegate::HdStrelkaRenderDelegate(const HdRenderSettingsMap& settingsMap, const MaterialNetworkTranslator& translator) : m_translator(translator) { m_resourceRegistry = std::make_shared<HdResourceRegistry>(); m_settingDescriptors.push_back( HdRenderSettingDescriptor{ "Samples per pixel", HdStrelkaSettingsTokens->spp, VtValue{ 8 } }); m_settingDescriptors.push_back( HdRenderSettingDescriptor{ "Max bounces", HdStrelkaSettingsTokens->max_bounces, VtValue{ 4 } }); _PopulateDefaultSettings(m_settingDescriptors); for (const auto& setting : settingsMap) { const TfToken& key = setting.first; const VtValue& value = setting.second; _settingsMap[key] = value; } oka::RenderType type = oka::RenderType::eOptiX; #ifdef __APPLE__ type = oka::RenderType::eMetal; #endif mRenderer = oka::RenderFactory::createRender(type); mRenderer->setScene(&mScene); } HdStrelkaRenderDelegate::~HdStrelkaRenderDelegate() { } void HdStrelkaRenderDelegate::SetDrivers(HdDriverVector const& drivers) { for (HdDriver* hdDriver : drivers) { if (hdDriver->name == _Tokens->HdStrelkaDriver && hdDriver->driver.IsHolding<oka::SharedContext*>()) { assert(mRenderer); mSharedCtx = hdDriver->driver.UncheckedGet<oka::SharedContext*>(); mRenderer->setSharedContext(mSharedCtx); mRenderer->init(); mSharedCtx->mRender = mRenderer; break; } } } HdRenderSettingDescriptorList HdStrelkaRenderDelegate::GetRenderSettingDescriptors() const { return m_settingDescriptors; } HdRenderPassSharedPtr HdStrelkaRenderDelegate::CreateRenderPass(HdRenderIndex* index, const HdRprimCollection& collection) { return HdRenderPassSharedPtr(new HdStrelkaRenderPass(index, collection, _settingsMap, mRenderer, &mScene)); } HdResourceRegistrySharedPtr HdStrelkaRenderDelegate::GetResourceRegistry() const { return m_resourceRegistry; } void HdStrelkaRenderDelegate::CommitResources(HdChangeTracker* tracker) { TF_UNUSED(tracker); // We delay BVH building and GPU uploads to the next render call. } HdInstancer* HdStrelkaRenderDelegate::CreateInstancer(HdSceneDelegate* delegate, const SdfPath& id) { return new HdStrelkaInstancer(delegate, id); } void HdStrelkaRenderDelegate::DestroyInstancer(HdInstancer* instancer) { delete instancer; } HdAovDescriptor HdStrelkaRenderDelegate::GetDefaultAovDescriptor(const TfToken& name) const { TF_UNUSED(name); HdAovDescriptor aovDescriptor; aovDescriptor.format = HdFormatFloat32Vec4; aovDescriptor.multiSampled = false; aovDescriptor.clearValue = GfVec4f(0.0f, 0.0f, 0.0f, 0.0f); return aovDescriptor; } const TfTokenVector& HdStrelkaRenderDelegate::GetSupportedRprimTypes() const { return SUPPORTED_RPRIM_TYPES; } HdRprim* HdStrelkaRenderDelegate::CreateRprim(const TfToken& typeId, const SdfPath& rprimId) { if (typeId == HdPrimTypeTokens->mesh) { return new HdStrelkaMesh(rprimId, &mScene); } else if (typeId == HdPrimTypeTokens->basisCurves) { return new HdStrelkaBasisCurves(rprimId, &mScene); } STRELKA_ERROR("Unknown Rprim Type {}", typeId.GetText()); return nullptr; } void HdStrelkaRenderDelegate::DestroyRprim(HdRprim* rprim) { delete rprim; } const TfTokenVector& HdStrelkaRenderDelegate::GetSupportedSprimTypes() const { return SUPPORTED_SPRIM_TYPES; } HdSprim* HdStrelkaRenderDelegate::CreateSprim(const TfToken& typeId, const SdfPath& sprimId) { STRELKA_DEBUG("CreateSprim Type: {}", typeId.GetText()); if (sprimId.IsEmpty()) { STRELKA_DEBUG("skipping creation of empty sprim path"); return nullptr; } HdSprim* res = nullptr; if (typeId == HdPrimTypeTokens->camera) { res = new HdStrelkaCamera(sprimId, mScene); } else if (typeId == HdPrimTypeTokens->material) { res = new HdStrelkaMaterial(sprimId, m_translator); } else if (typeId == HdPrimTypeTokens->rectLight || typeId == HdPrimTypeTokens->diskLight || typeId == HdPrimTypeTokens->sphereLight || typeId == HdPrimTypeTokens->distantLight) { res = new HdStrelkaLight(sprimId, typeId); } else { STRELKA_ERROR("Unknown Sprim Type {}", typeId.GetText()); } return res; } HdSprim* HdStrelkaRenderDelegate::CreateFallbackSprim(const TfToken& typeId) { const SdfPath& sprimId = SdfPath::EmptyPath(); return CreateSprim(typeId, sprimId); } void HdStrelkaRenderDelegate::DestroySprim(HdSprim* sprim) { delete sprim; } const TfTokenVector& HdStrelkaRenderDelegate::GetSupportedBprimTypes() const { return SUPPORTED_BPRIM_TYPES; } HdBprim* HdStrelkaRenderDelegate::CreateBprim(const TfToken& typeId, const SdfPath& bprimId) { if (typeId == HdPrimTypeTokens->renderBuffer) { return new HdStrelkaRenderBuffer(bprimId, mSharedCtx); } return nullptr; } HdBprim* HdStrelkaRenderDelegate::CreateFallbackBprim(const TfToken& typeId) { const SdfPath& bprimId = SdfPath::EmptyPath(); return CreateBprim(typeId, bprimId); } void HdStrelkaRenderDelegate::DestroyBprim(HdBprim* bprim) { delete bprim; } TfToken HdStrelkaRenderDelegate::GetMaterialBindingPurpose() const { //return HdTokens->full; return HdTokens->preview; } TfTokenVector HdStrelkaRenderDelegate::GetMaterialRenderContexts() const { return TfTokenVector{ HdStrelkaRenderContexts->mtlx, HdStrelkaRenderContexts->mdl }; } TfTokenVector HdStrelkaRenderDelegate::GetShaderSourceTypes() const { return TfTokenVector{ HdStrelkaSourceTypes->mtlx, HdStrelkaSourceTypes->mdl }; } oka::SharedContext& HdStrelkaRenderDelegate::getSharedContext() { return mRenderer->getSharedContext(); } PXR_NAMESPACE_CLOSE_SCOPE
6,338
C++
25.634454
122
0.718523
arhix52/Strelka/src/HdStrelka/BasisCurves.cpp
#include "BasisCurves.h" #include <log.h> PXR_NAMESPACE_OPEN_SCOPE void HdStrelkaBasisCurves::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, const TfToken& reprToken) { TF_UNUSED(renderParam); TF_UNUSED(reprToken); HdRenderIndex& renderIndex = sceneDelegate->GetRenderIndex(); const SdfPath& id = GetId(); mName = id.GetText(); STRELKA_INFO("Curve Name: {}", mName.c_str()); if (*dirtyBits & HdChangeTracker::DirtyMaterialId) { const SdfPath& materialId = sceneDelegate->GetMaterialId(id); SetMaterialId(materialId); } if (*dirtyBits & HdChangeTracker::DirtyTopology) { mTopology = sceneDelegate->GetBasisCurvesTopology(id); } if (*dirtyBits & HdChangeTracker::DirtyTransform) { m_prototypeTransform = sceneDelegate->GetTransform(id); } bool updateGeometry = (*dirtyBits & HdChangeTracker::DirtyPoints) | (*dirtyBits & HdChangeTracker::DirtyNormals) | (*dirtyBits & HdChangeTracker::DirtyTopology); *dirtyBits = HdChangeTracker::Clean; if (!updateGeometry) { return; } // m_faces.clear(); mPoints.clear(); mNormals.clear(); _UpdateGeometry(sceneDelegate); } bool HdStrelkaBasisCurves::_FindPrimvar(HdSceneDelegate* sceneDelegate, const TfToken& primvarName, HdInterpolation& interpolation) const { HdInterpolation interpolations[] = { HdInterpolation::HdInterpolationVertex, HdInterpolation::HdInterpolationFaceVarying, HdInterpolation::HdInterpolationConstant, HdInterpolation::HdInterpolationUniform, HdInterpolation::HdInterpolationVarying, HdInterpolation::HdInterpolationInstance }; for (HdInterpolation i : interpolations) { const auto& primvarDescs = GetPrimvarDescriptors(sceneDelegate, i); for (const HdPrimvarDescriptor& primvar : primvarDescs) { if (primvar.name == primvarName) { interpolation = i; return true; } } } return false; } void HdStrelkaBasisCurves::_PullPrimvars(HdSceneDelegate* sceneDelegate, VtVec3fArray& points, VtVec3fArray& normals, VtFloatArray& widths, bool& indexedNormals, bool& indexedUVs, GfVec3f& color, bool& hasColor) const { const SdfPath& id = GetId(); // Handle points. HdInterpolation pointInterpolation; bool foundPoints = _FindPrimvar(sceneDelegate, HdTokens->points, pointInterpolation); if (!foundPoints) { STRELKA_ERROR("Points primvar not found!"); return; } else if (pointInterpolation != HdInterpolation::HdInterpolationVertex) { STRELKA_ERROR("Points primvar is not vertex-interpolated!"); return; } VtValue boxedPoints = sceneDelegate->Get(id, HdTokens->points); points = boxedPoints.Get<VtVec3fArray>(); // Handle color. HdInterpolation colorInterpolation; bool foundColor = _FindPrimvar(sceneDelegate, HdTokens->displayColor, colorInterpolation); if (foundColor && colorInterpolation == HdInterpolation::HdInterpolationConstant) { VtValue boxedColors = sceneDelegate->Get(id, HdTokens->displayColor); const VtVec3fArray& colors = boxedColors.Get<VtVec3fArray>(); color = colors[0]; hasColor = true; } HdBasisCurvesTopology topology = GetBasisCurvesTopology(sceneDelegate); VtIntArray curveVertexCounts = topology.GetCurveVertexCounts(); // Handle normals. HdInterpolation normalInterpolation; bool foundNormals = _FindPrimvar(sceneDelegate, HdTokens->normals, normalInterpolation); if (foundNormals && normalInterpolation == HdInterpolation::HdInterpolationVarying) { VtValue boxedNormals = sceneDelegate->Get(id, HdTokens->normals); normals = boxedNormals.Get<VtVec3fArray>(); indexedNormals = true; } // Handle width. HdInterpolation widthInterpolation; bool foundWidth = _FindPrimvar(sceneDelegate, HdTokens->widths, widthInterpolation); if (foundWidth) { VtValue boxedWidths = sceneDelegate->Get(id, HdTokens->widths); widths = boxedWidths.Get<VtFloatArray>(); } } void HdStrelkaBasisCurves::_UpdateGeometry(HdSceneDelegate* sceneDelegate) { const HdBasisCurvesTopology& topology = mTopology; const SdfPath& id = GetId(); // Get USD Curve Metadata mVertexCounts = topology.GetCurveVertexCounts(); TfToken curveType = topology.GetCurveType(); TfToken curveBasis = topology.GetCurveBasis(); TfToken curveWrap = topology.GetCurveWrap(); size_t num_curves = mVertexCounts.size(); size_t num_keys = 0; bool indexedNormals; bool indexedUVs; bool hasColor = true; _PullPrimvars(sceneDelegate, mPoints, mNormals, mWidths, indexedNormals, indexedUVs, mColor, hasColor); _ConvertCurve(); } HdStrelkaBasisCurves::HdStrelkaBasisCurves(const SdfPath& id, oka::Scene* scene) : HdBasisCurves(id), mScene(scene) { } HdStrelkaBasisCurves::~HdStrelkaBasisCurves() { } HdDirtyBits HdStrelkaBasisCurves::GetInitialDirtyBitsMask() const { return HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex | HdChangeTracker::DirtyTransform | HdChangeTracker::DirtyMaterialId | HdChangeTracker::DirtyPrimvar; } HdDirtyBits HdStrelkaBasisCurves::_PropagateDirtyBits(HdDirtyBits bits) const { return bits; } void HdStrelkaBasisCurves::_InitRepr(const TfToken& reprName, HdDirtyBits* dirtyBits) { TF_UNUSED(reprName); TF_UNUSED(dirtyBits); } void HdStrelkaBasisCurves::_ConvertCurve() { // calculate phantom points // https://raytracing-docs.nvidia.com/optix7/guide/index.html#curves#differences-between-curves-spheres-and-triangles glm::float3 p1 = glm::float3(mPoints[0][0], mPoints[0][1], mPoints[0][2]); glm::float3 p2 = glm::float3(mPoints[1][0], mPoints[1][1], mPoints[1][2]); glm::float3 p0 = p1 + (p1 - p2); mCurvePoints.push_back(p0); for (const GfVec3f& p : mPoints) { mCurvePoints.push_back(glm::float3(p[0], p[1], p[2])); } int n = mPoints.size() - 1; glm::float3 pn = glm::float3(mPoints[n][0], mPoints[n][1], mPoints[n][2]); glm::float3 pn1 = glm::float3(mPoints[n - 1][0], mPoints[n - 1][1], mPoints[n - 1][2]); glm::float3 pnn = pn + (pn - pn1); mCurvePoints.push_back(pnn); mCurveWidths.push_back(mWidths[0] * 0.5); assert((mWidths.size() == mPoints.size()) || (mWidths.size() == 1)); if (mWidths.size() == 1) { for (int i = 0; i < mPoints.size(); ++i) { mCurveWidths.push_back(mWidths[0] * 0.5); } } else { for (const float w : mWidths) { mCurveWidths.push_back(w * 0.5f); } } mCurveWidths.push_back(mCurveWidths.back()); for (const int i : mVertexCounts) { mCurveVertexCounts.push_back(i); } } const std::vector<glm::float3>& HdStrelkaBasisCurves::GetPoints() const { return mCurvePoints; } const std::vector<float>& HdStrelkaBasisCurves::GetWidths() const { return mCurveWidths; } const std::vector<uint32_t>& HdStrelkaBasisCurves::GetVertexCounts() const { return mCurveVertexCounts; } const GfMatrix4d& HdStrelkaBasisCurves::GetPrototypeTransform() const { return m_prototypeTransform; } const char* HdStrelkaBasisCurves::getName() const { return mName.c_str(); } PXR_NAMESPACE_CLOSE_SCOPE
8,047
C++
30.685039
121
0.644215
arhix52/Strelka/src/HdStrelka/RenderBuffer.cpp
#include "RenderBuffer.h" #include "render.h" #include <pxr/base/gf/vec3i.h> PXR_NAMESPACE_OPEN_SCOPE HdStrelkaRenderBuffer::HdStrelkaRenderBuffer(const SdfPath& id, oka::SharedContext* ctx) : HdRenderBuffer(id), mCtx(ctx) { m_isMapped = false; m_isConverged = false; m_bufferMem = nullptr; } HdStrelkaRenderBuffer::~HdStrelkaRenderBuffer() { _Deallocate(); } bool HdStrelkaRenderBuffer::Allocate(const GfVec3i& dimensions, HdFormat format, bool multiSampled) { if (dimensions[2] != 1) { return false; } m_width = dimensions[0]; m_height = dimensions[1]; m_format = format; m_isMultiSampled = multiSampled; size_t size = m_width * m_height * HdDataSizeOfFormat(m_format); m_bufferMem = realloc(m_bufferMem, size); if (!m_bufferMem) { return false; } if (mResult) { mResult->resize(m_width, m_height); } else { oka::BufferDesc desc{}; desc.format = oka::BufferFormat::FLOAT4; desc.width = m_width; desc.height = m_height; mResult = mCtx->mRender->createBuffer(desc); } if (!mResult) { return false; } return true; } unsigned int HdStrelkaRenderBuffer::GetWidth() const { return m_width; } unsigned int HdStrelkaRenderBuffer::GetHeight() const { return m_height; } unsigned int HdStrelkaRenderBuffer::GetDepth() const { return 1u; } HdFormat HdStrelkaRenderBuffer::GetFormat() const { return m_format; } bool HdStrelkaRenderBuffer::IsMultiSampled() const { return m_isMultiSampled; } VtValue HdStrelkaRenderBuffer::GetResource(bool multiSampled) const { return VtValue((uint8_t*)mResult); } bool HdStrelkaRenderBuffer::IsConverged() const { return m_isConverged; } void HdStrelkaRenderBuffer::SetConverged(bool converged) { m_isConverged = converged; } void* HdStrelkaRenderBuffer::Map() { m_isMapped = true; return m_bufferMem; } bool HdStrelkaRenderBuffer::IsMapped() const { return m_isMapped; } void HdStrelkaRenderBuffer::Unmap() { m_isMapped = false; } void HdStrelkaRenderBuffer::Resolve() { } void HdStrelkaRenderBuffer::_Deallocate() { free(m_bufferMem); delete mResult; } PXR_NAMESPACE_CLOSE_SCOPE
2,264
C++
16.558139
120
0.671378
arhix52/Strelka/src/HdStrelka/Tokens.h
#pragma once #include <pxr/base/tf/staticTokens.h> PXR_NAMESPACE_OPEN_SCOPE #define HD_STRELKA_SETTINGS_TOKENS \ ((spp, "spp"))((max_bounces, "max-bounces")) // mtlx node identifier is given by usdMtlx. #define HD_STRELKA_NODE_IDENTIFIER_TOKENS \ (mtlx)(mdl) #define HD_STRELKA_SOURCE_TYPE_TOKENS \ (mtlx)(mdl) #define HD_STRELKA_DISCOVERY_TYPE_TOKENS \ (mtlx)(mdl) #define HD_STRELKA_RENDER_CONTEXT_TOKENS \ (mtlx)(mdl) #define HD_STRELKA_NODE_CONTEXT_TOKENS \ (mtlx)(mdl) #define HD_STRELKA_NODE_METADATA_TOKENS \ (subIdentifier) TF_DECLARE_PUBLIC_TOKENS(HdStrelkaSettingsTokens, HD_STRELKA_SETTINGS_TOKENS); TF_DECLARE_PUBLIC_TOKENS(HdStrelkaNodeIdentifiers, HD_STRELKA_NODE_IDENTIFIER_TOKENS); TF_DECLARE_PUBLIC_TOKENS(HdStrelkaSourceTypes, HD_STRELKA_SOURCE_TYPE_TOKENS); TF_DECLARE_PUBLIC_TOKENS(HdStrelkaDiscoveryTypes, HD_STRELKA_DISCOVERY_TYPE_TOKENS); TF_DECLARE_PUBLIC_TOKENS(HdStrelkaRenderContexts, HD_STRELKA_RENDER_CONTEXT_TOKENS); TF_DECLARE_PUBLIC_TOKENS(HdStrelkaNodeContexts, HD_STRELKA_NODE_CONTEXT_TOKENS); TF_DECLARE_PUBLIC_TOKENS(HdStrelkaNodeMetadata, HD_STRELKA_NODE_METADATA_TOKENS); PXR_NAMESPACE_CLOSE_SCOPE
1,175
C
29.947368
86
0.771064
arhix52/Strelka/src/HdStrelka/Camera.h
#pragma once #include <pxr/imaging/hd/camera.h> #include <scene/scene.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaCamera final : public HdCamera { public: HdStrelkaCamera(const SdfPath& id, oka::Scene& scene); ~HdStrelkaCamera() override; public: float GetVFov() const; uint32_t GetCameraIndex() const; public: void Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) override; HdDirtyBits GetInitialDirtyBitsMask() const override; private: oka::Camera _ConstructStrelkaCamera(); float m_vfov; oka::Scene& mScene; uint32_t mCameraIndex = -1; }; PXR_NAMESPACE_CLOSE_SCOPE
687
C
17.594594
58
0.697234
arhix52/Strelka/src/HdStrelka/MdlDiscoveryPlugin.cpp
#include "MdlDiscoveryPlugin.h" #include <pxr/base/tf/staticTokens.h> //#include "Tokens.h" PXR_NAMESPACE_OPEN_SCOPE // clang-format off TF_DEFINE_PRIVATE_TOKENS(_tokens, (mdl) ); // clang-format on NDR_REGISTER_DISCOVERY_PLUGIN(HdStrelkaMdlDiscoveryPlugin); NdrNodeDiscoveryResultVec HdStrelkaMdlDiscoveryPlugin::DiscoverNodes(const Context& ctx) { NdrNodeDiscoveryResultVec result; NdrNodeDiscoveryResult mdlNode( /* identifier */ _tokens->mdl, /* version */ NdrVersion(1), /* name */ _tokens->mdl, /* family */ TfToken(), /* discoveryType */ _tokens->mdl, /* sourceType */ _tokens->mdl, /* uri */ std::string(), /* resolvedUri */ std::string()); result.push_back(mdlNode); return result; } const NdrStringVec& HdStrelkaMdlDiscoveryPlugin::GetSearchURIs() const { static const NdrStringVec s_searchURIs; return s_searchURIs; } PXR_NAMESPACE_CLOSE_SCOPE
996
C++
23.317073
88
0.646586
arhix52/Strelka/src/HdStrelka/Material.cpp
#include "Material.h" #include <pxr/base/gf/vec2f.h> #include <pxr/usd/sdr/registry.h> #include <pxr/usdImaging/usdImaging/tokens.h> #include <log.h> PXR_NAMESPACE_OPEN_SCOPE HdStrelkaMaterial::HdStrelkaMaterial(const SdfPath& id, const MaterialNetworkTranslator& translator) : HdMaterial(id), m_translator(translator) { } HdStrelkaMaterial::~HdStrelkaMaterial() = default; HdDirtyBits HdStrelkaMaterial::GetInitialDirtyBitsMask() const { // return DirtyBits::DirtyParams; return DirtyBits::AllDirty; } void HdStrelkaMaterial::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) { TF_UNUSED(renderParam); const bool pullMaterial = (*dirtyBits & DirtyBits::DirtyParams) != 0u; *dirtyBits = DirtyBits::Clean; if (!pullMaterial) { return; } const SdfPath& id = GetId(); const std::string& name = id.GetString(); STRELKA_INFO("Hydra Material: {}", name.c_str()); const VtValue& resource = sceneDelegate->GetMaterialResource(id); if (!resource.IsHolding<HdMaterialNetworkMap>()) { return; } auto networkMap = resource.GetWithDefault<HdMaterialNetworkMap>(); HdMaterialNetwork& surfaceNetwork = networkMap.map[HdMaterialTerminalTokens->surface]; bool isUsdPreviewSurface = false; HdMaterialNode* previewSurfaceNode = nullptr; // store material parameters uint32_t nodeIdx = 0; for (auto& node : surfaceNetwork.nodes) { STRELKA_DEBUG("Node #{}: {}", nodeIdx, node.path.GetText()); if (node.identifier == UsdImagingTokens->UsdPreviewSurface) { previewSurfaceNode = &node; isUsdPreviewSurface = true; } for (const auto& params : node.parameters) { const std::string& name = params.first.GetString(); const TfType type = params.second.GetType(); STRELKA_DEBUG("Node name: {}\tParam name: {}\t{}", node.path.GetName(), name.c_str(), params.second.GetTypeName().c_str()); if (type.IsA<GfVec3f>()) { oka::MaterialManager::Param param; param.name = params.first; param.type = oka::MaterialManager::Param::Type::eFloat3; GfVec3f val = params.second.Get<GfVec3f>(); param.value.resize(sizeof(val)); memcpy(param.value.data(), &val, sizeof(val)); mMaterialParams.push_back(param); } else if (type.IsA<GfVec4f>()) { oka::MaterialManager::Param param; param.name = params.first; param.type = oka::MaterialManager::Param::Type::eFloat4; GfVec4f val = params.second.Get<GfVec4f>(); param.value.resize(sizeof(val)); memcpy(param.value.data(), &val, sizeof(val)); mMaterialParams.push_back(param); } else if (type.IsA<float>()) { oka::MaterialManager::Param param; param.name = params.first; param.type = oka::MaterialManager::Param::Type::eFloat; float val = params.second.Get<float>(); param.value.resize(sizeof(val)); memcpy(param.value.data(), &val, sizeof(val)); mMaterialParams.push_back(param); } else if (type.IsA<int>()) { oka::MaterialManager::Param param; param.name = params.first; param.type = oka::MaterialManager::Param::Type::eInt; int val = params.second.Get<int>(); param.value.resize(sizeof(val)); memcpy(param.value.data(), &val, sizeof(val)); mMaterialParams.push_back(param); } else if (type.IsA<bool>()) { oka::MaterialManager::Param param; param.name = params.first; param.type = oka::MaterialManager::Param::Type::eBool; bool val = params.second.Get<bool>(); param.value.resize(sizeof(val)); memcpy(param.value.data(), &val, sizeof(val)); mMaterialParams.push_back(param); } else if (type.IsA<SdfAssetPath>()) { oka::MaterialManager::Param param; param.name = node.path.GetName() + "_" + std::string(params.first); param.type = oka::MaterialManager::Param::Type::eTexture; const SdfAssetPath val = params.second.Get<SdfAssetPath>(); // STRELKA_DEBUG("path: {}", val.GetAssetPath().c_str()); STRELKA_DEBUG("path: {}", val.GetResolvedPath().c_str()); // std::string texPath = val.GetAssetPath(); std::string texPath = val.GetResolvedPath(); if (!texPath.empty()) { param.value.resize(texPath.size()); memcpy(param.value.data(), texPath.data(), texPath.size()); mMaterialParams.push_back(param); } } else if (type.IsA<GfVec2f>()) { oka::MaterialManager::Param param; param.name = params.first; param.type = oka::MaterialManager::Param::Type::eFloat2; GfVec2f val = params.second.Get<GfVec2f>(); param.value.resize(sizeof(val)); memcpy(param.value.data(), &val, sizeof(val)); mMaterialParams.push_back(param); } else if (type.IsA<TfToken>()) { const TfToken val = params.second.Get<TfToken>(); STRELKA_DEBUG("TfToken: {}", val.GetText()); } else if (type.IsA<std::string>()) { const std::string val = params.second.Get<std::string>(); STRELKA_DEBUG("String: {}", val.c_str()); } else { STRELKA_ERROR("Unknown parameter type!\n"); } } nodeIdx++; } bool isVolume = false; const HdMaterialNetwork2 network = HdConvertToHdMaterialNetwork2(networkMap, &isVolume); if (isVolume) { STRELKA_ERROR("Volume %s unsupported", id.GetText()); return; } if (isUsdPreviewSurface) { mMaterialXCode = m_translator.ParseNetwork(id, network); // STRELKA_DEBUG("MaterialX code:\n {}\n", mMaterialXCode.c_str()); } else { // MDL const bool res = MaterialNetworkTranslator::ParseMdlNetwork(network, mMdlFileUri, mMdlSubIdentifier); if (!res) { STRELKA_ERROR("Failed to translate material, replace to default!"); mMdlFileUri = "default.mdl"; mMdlSubIdentifier = "default_material"; } mIsMdl = true; } } const std::string& HdStrelkaMaterial::GetStrelkaMaterial() const { return mMaterialXCode; } PXR_NAMESPACE_CLOSE_SCOPE
7,130
C++
35.015151
112
0.551192
arhix52/Strelka/src/HdStrelka/Camera.cpp
#include "Camera.h" #include <pxr/imaging/hd/sceneDelegate.h> #include <pxr/base/gf/vec4d.h> #include <pxr/base/gf/camera.h> #include <cmath> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/compatibility.hpp> #include <glm/gtx/matrix_decompose.hpp> PXR_NAMESPACE_OPEN_SCOPE HdStrelkaCamera::HdStrelkaCamera(const SdfPath& id, oka::Scene& scene) : HdCamera(id), mScene(scene), m_vfov(M_PI_2) { const std::string& name = id.GetString(); oka::Camera okaCamera; okaCamera.name = name; mCameraIndex = mScene.addCamera(okaCamera); } HdStrelkaCamera::~HdStrelkaCamera() { } float HdStrelkaCamera::GetVFov() const { return m_vfov; } uint32_t HdStrelkaCamera::GetCameraIndex() const { return mCameraIndex; } void HdStrelkaCamera::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) { HdDirtyBits dirtyBitsCopy = *dirtyBits; HdCamera::Sync(sceneDelegate, renderParam, &dirtyBitsCopy); if (*dirtyBits & DirtyBits::DirtyParams) { // See https://wiki.panotools.org/Field_of_View float aperture = _verticalAperture * GfCamera::APERTURE_UNIT; float focalLength = _focalLength * GfCamera::FOCAL_LENGTH_UNIT; float vfov = 2.0f * std::atan(aperture / (2.0f * focalLength)); m_vfov = vfov; oka::Camera cam = _ConstructStrelkaCamera(); mScene.updateCamera(cam, mCameraIndex); } *dirtyBits = DirtyBits::Clean; } HdDirtyBits HdStrelkaCamera::GetInitialDirtyBitsMask() const { return DirtyBits::DirtyParams | DirtyBits::DirtyTransform; } oka::Camera HdStrelkaCamera::_ConstructStrelkaCamera() { oka::Camera strelkaCamera; GfMatrix4d perspMatrix = ComputeProjectionMatrix(); GfMatrix4d absInvViewMatrix = GetTransform(); GfMatrix4d relViewMatrix = absInvViewMatrix; //*m_rootMatrix; glm::float4x4 xform; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { xform[i][j] = (float)relViewMatrix[i][j]; } } glm::float4x4 persp; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { persp[i][j] = (float)perspMatrix[i][j]; } } { glm::vec3 scale; glm::quat rotation; glm::vec3 translation; glm::vec3 skew; glm::vec4 perspective; glm::decompose(xform, scale, rotation, translation, skew, perspective); rotation = glm::conjugate(rotation); strelkaCamera.position = translation * scale; strelkaCamera.mOrientation = rotation; } strelkaCamera.matrices.perspective = persp; strelkaCamera.matrices.invPerspective = glm::inverse(persp); strelkaCamera.fov = glm::degrees(GetVFov()); const std::string& name = GetId().GetString(); strelkaCamera.name = name; return strelkaCamera; } PXR_NAMESPACE_CLOSE_SCOPE
2,967
C++
26.229358
116
0.658915
arhix52/Strelka/src/HdStrelka/RenderPass.cpp
#include "RenderPass.h" #include "Camera.h" #include "Instancer.h" #include "Material.h" #include "Mesh.h" #include "BasisCurves.h" #include "Light.h" #include "RenderBuffer.h" #include "Tokens.h" #include <pxr/base/gf/matrix3d.h> #include <pxr/base/gf/quatd.h> #include <pxr/imaging/hd/renderDelegate.h> #include <pxr/imaging/hd/renderPassState.h> #include <pxr/imaging/hd/rprim.h> #include <pxr/imaging/hd/basisCurves.h> #include <log.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/compatibility.hpp> PXR_NAMESPACE_OPEN_SCOPE HdStrelkaRenderPass::HdStrelkaRenderPass(HdRenderIndex* index, const HdRprimCollection& collection, const HdRenderSettingsMap& settings, oka::Render* renderer, oka::Scene* scene) : HdRenderPass(index, collection), m_settings(settings), m_isConverged(false), m_lastSceneStateVersion(UINT32_MAX), m_lastRenderSettingsVersion(UINT32_MAX), mRenderer(renderer), mScene(scene) { } HdStrelkaRenderPass::~HdStrelkaRenderPass() { } bool HdStrelkaRenderPass::IsConverged() const { return m_isConverged; } // valid range of coordinates [-1; 1] uint32_t packNormal(const glm::float3& normal) { uint32_t packed = (uint32_t)((normal.x + 1.0f) / 2.0f * 511.99999f); packed += (uint32_t)((normal.y + 1.0f) / 2.0f * 511.99999f) << 10; packed += (uint32_t)((normal.z + 1.0f) / 2.0f * 511.99999f) << 20; return packed; } // valid range of coordinates [-10; 10] uint32_t packUV(const glm::float2& uv) { int32_t packed = (uint32_t)((uv.x + 10.0f) / 20.0f * 16383.99999f); packed += (uint32_t)((uv.y + 10.0f) / 20.0f * 16383.99999f) << 16; return packed; } void HdStrelkaRenderPass::_BakeMeshInstance(const HdStrelkaMesh* mesh, GfMatrix4d transform, uint32_t materialIndex) { const GfMatrix4d normalMatrix = transform.GetInverse().GetTranspose(); const std::vector<GfVec3f>& meshPoints = mesh->GetPoints(); const std::vector<GfVec3f>& meshNormals = mesh->GetNormals(); const std::vector<GfVec3f>& meshTangents = mesh->GetTangents(); const std::vector<GfVec3i>& meshFaces = mesh->GetFaces(); const std::vector<GfVec2f>& meshUVs = mesh->GetUVs(); TF_VERIFY(meshPoints.size() == meshNormals.size()); const size_t vertexCount = meshPoints.size(); std::vector<oka::Scene::Vertex> vertices(vertexCount); std::vector<uint32_t> indices(meshFaces.size() * 3); for (size_t j = 0; j < meshFaces.size(); ++j) { const GfVec3i& vertexIndices = meshFaces[j]; indices[j * 3 + 0] = vertexIndices[0]; indices[j * 3 + 1] = vertexIndices[1]; indices[j * 3 + 2] = vertexIndices[2]; } for (size_t j = 0; j < vertexCount; ++j) { const GfVec3f& point = meshPoints[j]; const GfVec3f& normal = meshNormals[j]; const GfVec3f& tangent = meshTangents[j]; oka::Scene::Vertex& vertex = vertices[j]; vertex.pos[0] = point[0]; vertex.pos[1] = point[1]; vertex.pos[2] = point[2]; const glm::float3 glmNormal = glm::float3(normal[0], normal[1], normal[2]); vertex.normal = packNormal(glmNormal); const glm::float3 glmTangent = glm::float3(tangent[0], tangent[1], tangent[2]); vertex.tangent = packNormal(glmTangent); // Texture coord if (!meshUVs.empty()) { const GfVec2f& uv = meshUVs[j]; const glm::float2 glmUV = glm::float2(uv[0], 1.0f - uv[1]); // Flip v coordinate vertex.uv = packUV(glmUV); } } glm::float4x4 glmTransform; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { glmTransform[i][j] = (float)transform[i][j]; } } uint32_t meshId = mScene->createMesh(vertices, indices); assert(meshId != -1); uint32_t instId = mScene->createInstance(oka::Instance::Type::eMesh, meshId, materialIndex, glmTransform); assert(instId != -1); } void HdStrelkaRenderPass::_BakeMeshes(HdRenderIndex* renderIndex, GfMatrix4d rootTransform) { TfHashMap<SdfPath, uint32_t, SdfPath::Hash> materialMapping; materialMapping[SdfPath::EmptyPath()] = 0; auto getOrCreateMaterial = [&](const SdfPath& materialId) { uint32_t materialIndex = 0; if (materialMapping.find(materialId) != materialMapping.end()) { materialIndex = materialMapping[materialId]; } else { HdSprim* sprim = renderIndex->GetSprim(HdPrimTypeTokens->material, materialId); if (!sprim) { STRELKA_ERROR("Cannot retrive material!"); return 0u; } HdStrelkaMaterial* material = dynamic_cast<HdStrelkaMaterial*>(sprim); if (material->isMdl()) { const std::string& fileUri = material->getFileUri(); const std::string& name = material->getSubIdentifier(); oka::Scene::MaterialDescription materialDesc; materialDesc.file = fileUri; materialDesc.name = name; materialDesc.type = oka::Scene::MaterialDescription::Type::eMdl; materialDesc.params = material->getParams(); materialIndex = mScene->addMaterial(materialDesc); } else { const std::string& code = material->GetStrelkaMaterial(); const std::string& name = material->getSubIdentifier(); oka::Scene::MaterialDescription materialDesc; materialDesc.name = name; materialDesc.code = code; materialDesc.type = oka::Scene::MaterialDescription::Type::eMaterialX; materialDesc.params = material->getParams(); materialIndex = mScene->addMaterial(materialDesc); } materialMapping[materialId] = materialIndex; } return materialIndex; }; for (const auto& rprimId : renderIndex->GetRprimIds()) { const HdRprim* rprim = renderIndex->GetRprim(rprimId); if (dynamic_cast<const HdMesh*>(rprim)) { const HdStrelkaMesh* mesh = dynamic_cast<const HdStrelkaMesh*>(rprim); if (!mesh->IsVisible()) { // TODO: add UI/setting control here continue; } const TfToken renderTag = mesh->GetRenderTag(); if ((renderTag != "geometry") && (renderTag != "render")) { // skip all proxy meshes continue; } VtMatrix4dArray transforms; const SdfPath& instancerId = mesh->GetInstancerId(); if (instancerId.IsEmpty()) { transforms.resize(1); transforms[0] = GfMatrix4d(1.0); } else { HdInstancer* boxedInstancer = renderIndex->GetInstancer(instancerId); HdStrelkaInstancer* instancer = dynamic_cast<HdStrelkaInstancer*>(boxedInstancer); const SdfPath& meshId = mesh->GetId(); transforms = instancer->ComputeInstanceTransforms(meshId); } const SdfPath& materialId = mesh->GetMaterialId(); const std::string& materialName = materialId.GetString(); STRELKA_INFO("Hydra: Mesh: {0} \t Material: {1}", mesh->getName(), materialName.c_str()); uint32_t materialIndex = 0; if (materialId.IsEmpty()) { GfVec3f color(1.0f); if (mesh->HasColor()) { color = mesh->GetColor(); } // materialName += "_color"; const std::string& fileUri = "default.mdl"; const std::string& name = "default_material"; oka::Scene::MaterialDescription material; material.file = fileUri; material.name = name; material.type = oka::Scene::MaterialDescription::Type::eMdl; material.color = glm::float3(color[0], color[1], color[2]); material.hasColor = true; oka::MaterialManager::Param colorParam = {}; colorParam.name = "diffuse_color"; colorParam.type = oka::MaterialManager::Param::Type::eFloat3; colorParam.value.resize(sizeof(float) * 3); memcpy(colorParam.value.data(), glm::value_ptr(material.color), sizeof(float) * 3); material.params.push_back(colorParam); materialIndex = mScene->addMaterial(material); } else { materialIndex = getOrCreateMaterial(materialId); } const GfMatrix4d& prototypeTransform = mesh->GetPrototypeTransform(); for (size_t i = 0; i < transforms.size(); i++) { const GfMatrix4d transform = prototypeTransform * transforms[i]; // *rootTransform; // GfMatrix4d transform = GfMatrix4d(1.0); _BakeMeshInstance(mesh, transform, materialIndex); } } else if (dynamic_cast<const HdBasisCurves*>(rprim)) { const HdStrelkaBasisCurves* curve = dynamic_cast<const HdStrelkaBasisCurves*>(rprim); const std::vector<glm::float3>& points = curve->GetPoints(); const std::vector<float>& widths = curve->GetWidths(); const std::vector<uint32_t>& vertexCounts = curve->GetVertexCounts(); const SdfPath& materialId = curve->GetMaterialId(); const std::string& materialName = materialId.GetString(); STRELKA_INFO("Hydra: Curve: {0} \t Material: {1}", curve->getName(), materialName.c_str()); const uint32_t materialIndex = getOrCreateMaterial(materialId); const GfMatrix4d& prototypeTransform = curve->GetPrototypeTransform(); glm::float4x4 glmTransform; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { glmTransform[i][j] = (float)prototypeTransform[i][j]; } } uint32_t curveId = mScene->createCurve(oka::Curve::Type::eCubic, vertexCounts, points, widths); mScene->createInstance(oka::Instance::Type::eCurve, curveId, materialIndex, glmTransform, -1); } } STRELKA_INFO("Meshes: {}", mScene->getMeshes().size()); STRELKA_INFO("Instances: {}", mScene->getInstances().size()); STRELKA_INFO("Materials: {}", mScene->getMaterials().size()); STRELKA_INFO("Curves: {}", mScene->getCurves().size()); } void HdStrelkaRenderPass::_Execute(const HdRenderPassStateSharedPtr& renderPassState, const TfTokenVector& renderTags) { TF_UNUSED(renderTags); HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); m_isConverged = false; const auto* camera = dynamic_cast<const HdStrelkaCamera*>(renderPassState->GetCamera()); if (!camera) { return; } const HdRenderPassAovBindingVector& aovBindings = renderPassState->GetAovBindings(); if (aovBindings.empty()) { return; } const HdRenderPassAovBinding* colorAovBinding = nullptr; for (const HdRenderPassAovBinding& aovBinding : aovBindings) { if (aovBinding.aovName != HdAovTokens->color) { HdStrelkaRenderBuffer* renderBuffer = dynamic_cast<HdStrelkaRenderBuffer*>(aovBinding.renderBuffer); renderBuffer->SetConverged(true); continue; } colorAovBinding = &aovBinding; } if (!colorAovBinding) { return; } HdRenderIndex* renderIndex = GetRenderIndex(); HdChangeTracker& changeTracker = renderIndex->GetChangeTracker(); HdRenderDelegate* renderDelegate = renderIndex->GetRenderDelegate(); HdStrelkaRenderBuffer* renderBuffer = dynamic_cast<HdStrelkaRenderBuffer*>(colorAovBinding->renderBuffer); uint32_t sceneStateVersion = changeTracker.GetSceneStateVersion(); uint32_t renderSettingsStateVersion = renderDelegate->GetRenderSettingsVersion(); bool sceneChanged = (sceneStateVersion != m_lastSceneStateVersion); bool renderSettingsChanged = (renderSettingsStateVersion != m_lastRenderSettingsVersion); // if (!sceneChanged && !renderSettingsChanged) //{ // renderBuffer->SetConverged(true); // return; //} oka::Buffer* outputImage = renderBuffer->GetResource(false).UncheckedGet<oka::Buffer*>(); renderBuffer->SetConverged(false); m_lastSceneStateVersion = sceneStateVersion; m_lastRenderSettingsVersion = renderSettingsStateVersion; // Transform scene into camera space to increase floating point precision. GfMatrix4d viewMatrix = camera->GetTransform().GetInverse(); static int counter = 0; if (counter == 0) { ++counter; _BakeMeshes(renderIndex, viewMatrix); m_rootMatrix = viewMatrix; mRenderer->setScene(mScene); const uint32_t camIndex = camera->GetCameraIndex(); // mRenderer->setActiveCameraIndex(camIndex); oka::Scene::UniformLightDesc desc{}; desc.color = glm::float3(1.0f); desc.height = 0.4f; desc.width = 0.4f; desc.position = glm::float3(0, 1.1, 0.67); desc.orientation = glm::float3(179.68, 29.77, -89.97); desc.intensity = 160.0f; static const TfTokenVector lightTypes = { HdPrimTypeTokens->domeLight, HdPrimTypeTokens->simpleLight, HdPrimTypeTokens->sphereLight, HdPrimTypeTokens->rectLight, HdPrimTypeTokens->diskLight, HdPrimTypeTokens->cylinderLight, HdPrimTypeTokens->distantLight }; size_t count = 0; // TF_FOR_ALL(it, lightTypes) { // TODO: refactor this to more generic code, templates? if (renderIndex->IsSprimTypeSupported(HdPrimTypeTokens->rectLight)) { SdfPathVector sprimPaths = renderIndex->GetSprimSubtree(HdPrimTypeTokens->rectLight, SdfPath::AbsoluteRootPath()); for (int lightIdx = 0; lightIdx < sprimPaths.size(); ++lightIdx) { HdSprim* sprim = renderIndex->GetSprim(HdPrimTypeTokens->rectLight, sprimPaths[lightIdx]); HdStrelkaLight* light = dynamic_cast<HdStrelkaLight*>(sprim); mScene->createLight(light->getLightDesc()); } } if (renderIndex->IsSprimTypeSupported(HdPrimTypeTokens->diskLight)) { SdfPathVector sprimPaths = renderIndex->GetSprimSubtree(HdPrimTypeTokens->diskLight, SdfPath::AbsoluteRootPath()); for (int lightIdx = 0; lightIdx < sprimPaths.size(); ++lightIdx) { HdSprim* sprim = renderIndex->GetSprim(HdPrimTypeTokens->diskLight, sprimPaths[lightIdx]); HdStrelkaLight* light = dynamic_cast<HdStrelkaLight*>(sprim); mScene->createLight(light->getLightDesc()); } } if (renderIndex->IsSprimTypeSupported(HdPrimTypeTokens->sphereLight)) { SdfPathVector sprimPaths = renderIndex->GetSprimSubtree(HdPrimTypeTokens->sphereLight, SdfPath::AbsoluteRootPath()); for (int lightIdx = 0; lightIdx < sprimPaths.size(); ++lightIdx) { HdSprim* sprim = renderIndex->GetSprim(HdPrimTypeTokens->sphereLight, sprimPaths[lightIdx]); HdStrelkaLight* light = dynamic_cast<HdStrelkaLight*>(sprim); mScene->createLight(light->getLightDesc()); } } if (renderIndex->IsSprimTypeSupported(HdPrimTypeTokens->distantLight)) { SdfPathVector sprimPaths = renderIndex->GetSprimSubtree(HdPrimTypeTokens->distantLight, SdfPath::AbsoluteRootPath()); for (int lightIdx = 0; lightIdx < sprimPaths.size(); ++lightIdx) { HdSprim* sprim = renderIndex->GetSprim(HdPrimTypeTokens->distantLight, sprimPaths[lightIdx]); HdStrelkaLight* light = dynamic_cast<HdStrelkaLight*>(sprim); mScene->createLight(light->getLightDesc()); } } } } // mScene.createLight(desc); float* img_data = (float*)renderBuffer->Map(); mRenderer->render(outputImage); renderBuffer->Unmap(); // renderBuffer->SetConverged(true); m_isConverged = true; } PXR_NAMESPACE_CLOSE_SCOPE
17,099
C++
37
118
0.587578
arhix52/Strelka/src/HdStrelka/MaterialNetworkTranslator.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include <pxr/usd/sdf/path.h> #include <string> #include <MaterialXCore/Document.h> #include <memory> PXR_NAMESPACE_OPEN_SCOPE struct HdMaterialNetwork2; class MaterialNetworkTranslator { public: MaterialNetworkTranslator(const std::string& mtlxLibPath); std::string ParseNetwork(const SdfPath& id, const HdMaterialNetwork2& network) const; static bool ParseMdlNetwork(const HdMaterialNetwork2& network, std::string& fileUri, std::string& subIdentifier); private: MaterialX::DocumentPtr CreateMaterialXDocumentFromNetwork(const SdfPath& id, const HdMaterialNetwork2& network) const; void patchMaterialNetwork(HdMaterialNetwork2& network) const; private: MaterialX::DocumentPtr m_nodeLib; }; PXR_NAMESPACE_CLOSE_SCOPE
1,568
C
32.382978
122
0.714286
arhix52/Strelka/src/HdStrelka/Mesh.cpp
#include "Mesh.h" #include <pxr/imaging/hd/instancer.h> #include <pxr/imaging/hd/meshUtil.h> #include <pxr/imaging/hd/smoothNormals.h> #include <pxr/imaging/hd/vertexAdjacency.h> #include <log.h> PXR_NAMESPACE_OPEN_SCOPE // clang-format off TF_DEFINE_PRIVATE_TOKENS(_tokens, (st) ); // clang-format on HdStrelkaMesh::HdStrelkaMesh(const SdfPath& id, oka::Scene* scene) : HdMesh(id), mPrototypeTransform(1.0), mColor(0.0, 0.0, 0.0), mHasColor(false), mScene(scene) { } HdStrelkaMesh::~HdStrelkaMesh() = default; void HdStrelkaMesh::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, const TfToken& reprToken) { TF_UNUSED(renderParam); TF_UNUSED(reprToken); HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); HdRenderIndex& renderIndex = sceneDelegate->GetRenderIndex(); if ((*dirtyBits & HdChangeTracker::DirtyInstancer) | (*dirtyBits & HdChangeTracker::DirtyInstanceIndex)) { HdDirtyBits dirtyBitsCopy = *dirtyBits; _UpdateInstancer(sceneDelegate, &dirtyBitsCopy); const SdfPath& instancerId = GetInstancerId(); HdInstancer::_SyncInstancerAndParents(renderIndex, instancerId); } const SdfPath& id = GetId(); mName = id.GetText(); if (*dirtyBits & HdChangeTracker::DirtyMaterialId) { const SdfPath& materialId = sceneDelegate->GetMaterialId(id); SetMaterialId(materialId); } if (*dirtyBits & HdChangeTracker::DirtyTransform) { mPrototypeTransform = sceneDelegate->GetTransform(id); } const bool updateGeometry = (*dirtyBits & HdChangeTracker::DirtyPoints) | (*dirtyBits & HdChangeTracker::DirtyNormals) | (*dirtyBits & HdChangeTracker::DirtyTopology); *dirtyBits = HdChangeTracker::Clean; if (!updateGeometry) { return; } mFaces.clear(); mPoints.clear(); mNormals.clear(); _UpdateGeometry(sceneDelegate); } // valid range of coordinates [-1; 1] static uint32_t packNormal(const glm::float3& normal) { uint32_t packed = (uint32_t)((normal.x + 1.0f) / 2.0f * 511.99999f); packed += (uint32_t)((normal.y + 1.0f) / 2.0f * 511.99999f) << 10; packed += (uint32_t)((normal.z + 1.0f) / 2.0f * 511.99999f) << 20; return packed; } void HdStrelkaMesh::_ConvertMesh() { const std::vector<GfVec3f>& meshPoints = GetPoints(); const std::vector<GfVec3f>& meshNormals = GetNormals(); const std::vector<GfVec3i>& meshFaces = GetFaces(); TF_VERIFY(meshPoints.size() == meshNormals.size()); const size_t vertexCount = meshPoints.size(); std::vector<oka::Scene::Vertex> vertices(vertexCount); std::vector<uint32_t> indices(meshFaces.size() * 3); for (size_t j = 0; j < meshFaces.size(); ++j) { const GfVec3i& vertexIndices = meshFaces[j]; indices[j * 3 + 0] = vertexIndices[0]; indices[j * 3 + 1] = vertexIndices[1]; indices[j * 3 + 2] = vertexIndices[2]; } for (size_t j = 0; j < vertexCount; ++j) { const GfVec3f& point = meshPoints[j]; const GfVec3f& normal = meshNormals[j]; oka::Scene::Vertex& vertex = vertices[j]; vertex.pos[0] = point[0]; vertex.pos[1] = point[1]; vertex.pos[2] = point[2]; const glm::float3 glmNormal = glm::float3(normal[0], normal[1], normal[2]); vertex.normal = packNormal(glmNormal); } mStrelkaMeshId = mScene->createMesh(vertices, indices); assert(mStrelkaMeshId != -1); } void HdStrelkaMesh::_UpdateGeometry(HdSceneDelegate* sceneDelegate) { const HdMeshTopology& topology = GetMeshTopology(sceneDelegate); const SdfPath& id = GetId(); const HdMeshUtil meshUtil(&topology, id); VtVec3iArray indices; VtIntArray primitiveParams; meshUtil.ComputeTriangleIndices(&indices, &primitiveParams); VtVec3fArray points; VtVec3fArray normals; VtVec2fArray uvs; bool indexedNormals; bool indexedUVs; _PullPrimvars(sceneDelegate, points, normals, uvs, indexedNormals, indexedUVs, mColor, mHasColor); const bool hasUVs = !uvs.empty(); for (int i = 0; i < indices.size(); i++) { GfVec3i newFaceIndices(i * 3 + 0, i * 3 + 1, i * 3 + 2); mFaces.push_back(newFaceIndices); const GfVec3i& faceIndices = indices[i]; mPoints.push_back(points[faceIndices[0]]); mPoints.push_back(points[faceIndices[1]]); mPoints.push_back(points[faceIndices[2]]); auto computeTangent = [](const GfVec3f& normal) { GfVec3f c1 = GfCross(normal, GfVec3f(1.0f, 0.0f, 0.0f)); GfVec3f c2 = GfCross(normal, GfVec3f(0.0f, 1.0f, 0.0f)); GfVec3f tangent; if (c1.GetLengthSq() > c2.GetLengthSq()) { tangent = c1; } else { tangent = c2; } GfNormalize(&tangent); return tangent; }; mNormals.push_back(normals[indexedNormals ? faceIndices[0] : newFaceIndices[0]]); mTangents.push_back(computeTangent(normals[indexedNormals ? faceIndices[0] : newFaceIndices[0]])); mNormals.push_back(normals[indexedNormals ? faceIndices[1] : newFaceIndices[1]]); mTangents.push_back(computeTangent(normals[indexedNormals ? faceIndices[1] : newFaceIndices[1]])); mNormals.push_back(normals[indexedNormals ? faceIndices[2] : newFaceIndices[2]]); mTangents.push_back(computeTangent(normals[indexedNormals ? faceIndices[2] : newFaceIndices[2]])); if (hasUVs) { mUvs.push_back(uvs[indexedUVs ? faceIndices[0] : newFaceIndices[0]]); mUvs.push_back(uvs[indexedUVs ? faceIndices[1] : newFaceIndices[1]]); mUvs.push_back(uvs[indexedUVs ? faceIndices[2] : newFaceIndices[2]]); } } } bool HdStrelkaMesh::_FindPrimvar(HdSceneDelegate* sceneDelegate, const TfToken& primvarName, HdInterpolation& interpolation) const { const HdInterpolation interpolations[] = { HdInterpolation::HdInterpolationVertex, HdInterpolation::HdInterpolationFaceVarying, HdInterpolation::HdInterpolationConstant, HdInterpolation::HdInterpolationUniform, HdInterpolation::HdInterpolationVarying, HdInterpolation::HdInterpolationInstance }; for (const HdInterpolation& currInteroplation : interpolations) { const auto& primvarDescs = GetPrimvarDescriptors(sceneDelegate, currInteroplation); for (const HdPrimvarDescriptor& primvar : primvarDescs) { if (primvar.name == primvarName) { interpolation = currInteroplation; return true; } } } return false; } void HdStrelkaMesh::_PullPrimvars(HdSceneDelegate* sceneDelegate, VtVec3fArray& points, VtVec3fArray& normals, VtVec2fArray& uvs, bool& indexedNormals, bool& indexedUVs, GfVec3f& color, bool& hasColor) const { const SdfPath& id = GetId(); // Handle points. HdInterpolation pointInterpolation; const bool foundPoints = _FindPrimvar(sceneDelegate, HdTokens->points, pointInterpolation); if (!foundPoints) { TF_RUNTIME_ERROR("Points primvar not found!"); return; } else if (pointInterpolation != HdInterpolation::HdInterpolationVertex) { TF_RUNTIME_ERROR("Points primvar is not vertex-interpolated!"); return; } const VtValue boxedPoints = sceneDelegate->Get(id, HdTokens->points); points = boxedPoints.Get<VtVec3fArray>(); // Handle color. HdInterpolation colorInterpolation; const bool foundColor = _FindPrimvar(sceneDelegate, HdTokens->displayColor, colorInterpolation); if (foundColor && colorInterpolation == HdInterpolation::HdInterpolationConstant) { const VtValue boxedColors = sceneDelegate->Get(id, HdTokens->displayColor); const VtVec3fArray& colors = boxedColors.Get<VtVec3fArray>(); color = colors[0]; hasColor = true; } const HdMeshTopology topology = GetMeshTopology(sceneDelegate); // Handle normals. HdInterpolation normalInterpolation; const bool foundNormals = _FindPrimvar(sceneDelegate, HdTokens->normals, normalInterpolation); if (foundNormals && normalInterpolation == HdInterpolation::HdInterpolationVertex) { const VtValue boxedNormals = sceneDelegate->Get(id, HdTokens->normals); normals = boxedNormals.Get<VtVec3fArray>(); indexedNormals = true; } if (foundNormals && normalInterpolation == HdInterpolation::HdInterpolationFaceVarying) { const VtValue boxedFvNormals = sceneDelegate->Get(id, HdTokens->normals); const VtVec3fArray& fvNormals = boxedFvNormals.Get<VtVec3fArray>(); const HdMeshUtil meshUtil(&topology, id); VtValue boxedTriangulatedNormals; if (!meshUtil.ComputeTriangulatedFaceVaryingPrimvar( fvNormals.cdata(), fvNormals.size(), HdTypeFloatVec3, &boxedTriangulatedNormals)) { TF_CODING_ERROR("Unable to triangulate face-varying normals of %s", id.GetText()); } normals = boxedTriangulatedNormals.Get<VtVec3fArray>(); indexedNormals = false; } else { Hd_VertexAdjacency adjacency; adjacency.BuildAdjacencyTable(&topology); normals = Hd_SmoothNormals::ComputeSmoothNormals(&adjacency, points.size(), points.cdata()); indexedNormals = true; } // Handle texture coords HdInterpolation textureCoordInterpolation; const bool foundTextureCoord = _FindPrimvar(sceneDelegate, _tokens->st, textureCoordInterpolation); if (foundTextureCoord && textureCoordInterpolation == HdInterpolationVertex) { uvs = sceneDelegate->Get(id, _tokens->st).Get<VtVec2fArray>(); indexedUVs = true; } if (foundTextureCoord && textureCoordInterpolation == HdInterpolation::HdInterpolationFaceVarying) { const VtValue boxedUVs = sceneDelegate->Get(id, _tokens->st); const VtVec2fArray& fvUVs = boxedUVs.Get<VtVec2fArray>(); const HdMeshUtil meshUtil(&topology, id); VtValue boxedTriangulatedUVS; if (!meshUtil.ComputeTriangulatedFaceVaryingPrimvar( fvUVs.cdata(), fvUVs.size(), HdTypeFloatVec2, &boxedTriangulatedUVS)) { TF_CODING_ERROR("Unable to triangulate face-varying UVs of %s", id.GetText()); } uvs = boxedTriangulatedUVS.Get<VtVec2fArray>(); indexedUVs = false; } } const TfTokenVector& HdStrelkaMesh::GetBuiltinPrimvarNames() const { return BUILTIN_PRIMVAR_NAMES; } const std::vector<GfVec3f>& HdStrelkaMesh::GetPoints() const { return mPoints; } const std::vector<GfVec3f>& HdStrelkaMesh::GetNormals() const { return mNormals; } const std::vector<GfVec3f>& HdStrelkaMesh::GetTangents() const { return mTangents; } const std::vector<GfVec3i>& HdStrelkaMesh::GetFaces() const { return mFaces; } const std::vector<GfVec2f>& HdStrelkaMesh::GetUVs() const { return mUvs; } const GfMatrix4d& HdStrelkaMesh::GetPrototypeTransform() const { return mPrototypeTransform; } const GfVec3f& HdStrelkaMesh::GetColor() const { return mColor; } bool HdStrelkaMesh::HasColor() const { return mHasColor; } const char* HdStrelkaMesh::getName() const { return mName.c_str(); } HdDirtyBits HdStrelkaMesh::GetInitialDirtyBitsMask() const { return HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex | HdChangeTracker::DirtyTransform | HdChangeTracker::DirtyMaterialId | HdChangeTracker::DirtyPrimvar; } HdDirtyBits HdStrelkaMesh::_PropagateDirtyBits(HdDirtyBits bits) const { return bits; } void HdStrelkaMesh::_InitRepr(const TfToken& reprName, HdDirtyBits* dirtyBits) { TF_UNUSED(reprName); TF_UNUSED(dirtyBits); } PXR_NAMESPACE_CLOSE_SCOPE
12,415
C++
32.109333
116
0.648731
arhix52/Strelka/src/HdStrelka/Instancer.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include <pxr/imaging/hd/instancer.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaInstancer final : public HdInstancer { public: HdStrelkaInstancer(HdSceneDelegate* delegate, const SdfPath& id); ~HdStrelkaInstancer() override; public: VtMatrix4dArray ComputeInstanceTransforms(const SdfPath& prototypeId); void Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) override; private: TfHashMap<TfToken, VtValue, TfToken::HashFunctor> m_primvarMap; }; PXR_NAMESPACE_CLOSE_SCOPE
1,403
C
32.428571
106
0.676408
arhix52/Strelka/src/HdStrelka/Light.h
#pragma once #include "pxr/pxr.h" #include <pxr/imaging/hd/light.h> #include <pxr/imaging/hd/sceneDelegate.h> #include <scene/scene.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaLight final : public HdLight { public: HF_MALLOC_TAG_NEW("new HdStrelkaLight"); HdStrelkaLight(const SdfPath& id, TfToken const& lightType); ~HdStrelkaLight() override; public: void Sync(HdSceneDelegate* delegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits) override; HdDirtyBits GetInitialDirtyBitsMask() const override; oka::Scene::UniformLightDesc getLightDesc(); private: TfToken mLightType; oka::Scene::UniformLightDesc mLightDesc; }; PXR_NAMESPACE_CLOSE_SCOPE
720
C
19.599999
64
0.719444
arhix52/Strelka/src/HdStrelka/MdlParserPlugin.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include <pxr/usd/ndr/parserPlugin.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaMdlParserPlugin final : public NdrParserPlugin { public: NdrNodeUniquePtr Parse(const NdrNodeDiscoveryResult& discoveryResult) override; const NdrTokenVec& GetDiscoveryTypes() const override; const TfToken& GetSourceType() const override; }; PXR_NAMESPACE_CLOSE_SCOPE
1,174
C
34.60606
106
0.695911
arhix52/Strelka/src/HdStrelka/MaterialNetworkTranslator.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "MaterialNetworkTranslator.h" #include <pxr/imaging/hd/material.h> #include <pxr/usd/sdr/registry.h> #include <pxr/imaging/hdMtlx/hdMtlx.h> #include <pxr/imaging/hd/tokens.h> #include <MaterialXCore/Document.h> #include <MaterialXCore/Library.h> #include <MaterialXCore/Material.h> #include <MaterialXCore/Definition.h> #include <MaterialXFormat/File.h> #include <MaterialXFormat/Util.h> #include "Tokens.h" using std::string; namespace mx = MaterialX; PXR_NAMESPACE_OPEN_SCOPE // clang-format off TF_DEFINE_PRIVATE_TOKENS( _tokens, // USD node types (UsdPreviewSurface) (UsdUVTexture) (UsdTransform2d) (UsdPrimvarReader_float) (UsdPrimvarReader_float2) (UsdPrimvarReader_float3) (UsdPrimvarReader_float4) (UsdPrimvarReader_int) (UsdPrimvarReader_string) (UsdPrimvarReader_normal) (UsdPrimvarReader_point) (UsdPrimvarReader_vector) (UsdPrimvarReader_matrix) // MaterialX USD node type equivalents (ND_UsdPreviewSurface_surfaceshader) (ND_UsdUVTexture) (ND_UsdPrimvarReader_integer) (ND_UsdPrimvarReader_boolean) (ND_UsdPrimvarReader_string) (ND_UsdPrimvarReader_float) (ND_UsdPrimvarReader_vector2) (ND_UsdPrimvarReader_vector3) (ND_UsdPrimvarReader_vector4) (ND_UsdTransform2d) (ND_UsdPrimvarReader_matrix44) (mdl) (subIdentifier) (ND_convert_color3_vector3) (diffuse_color_constant) (normal) (rgb) (in) (out) ); // clang-format on bool _ConvertNodesToMaterialXNodes(const HdMaterialNetwork2& network, HdMaterialNetwork2& mtlxNetwork) { mtlxNetwork = network; for (auto& node : mtlxNetwork.nodes) { TfToken& nodeTypeId = node.second.nodeTypeId; SdrRegistry& sdrRegistry = SdrRegistry::GetInstance(); if (sdrRegistry.GetShaderNodeByIdentifierAndType(nodeTypeId, HdStrelkaDiscoveryTypes->mtlx)) { continue; } if (nodeTypeId == _tokens->UsdPreviewSurface) { nodeTypeId = _tokens->ND_UsdPreviewSurface_surfaceshader; } else if (nodeTypeId == _tokens->UsdUVTexture) { nodeTypeId = _tokens->ND_UsdUVTexture; } else if (nodeTypeId == _tokens->UsdTransform2d) { nodeTypeId = _tokens->ND_UsdTransform2d; } else if (nodeTypeId == _tokens->UsdPrimvarReader_float) { nodeTypeId = _tokens->ND_UsdPrimvarReader_float; } else if (nodeTypeId == _tokens->UsdPrimvarReader_float2) { nodeTypeId = _tokens->ND_UsdPrimvarReader_vector2; } else if (nodeTypeId == _tokens->UsdPrimvarReader_float3) { nodeTypeId = _tokens->ND_UsdPrimvarReader_vector3; } else if (nodeTypeId == _tokens->UsdPrimvarReader_float4) { nodeTypeId = _tokens->ND_UsdPrimvarReader_vector4; } else if (nodeTypeId == _tokens->UsdPrimvarReader_int) { nodeTypeId = _tokens->ND_UsdPrimvarReader_integer; } else if (nodeTypeId == _tokens->UsdPrimvarReader_string) { nodeTypeId = _tokens->ND_UsdPrimvarReader_string; } else if (nodeTypeId == _tokens->UsdPrimvarReader_normal) { nodeTypeId = _tokens->ND_UsdPrimvarReader_vector3; } else if (nodeTypeId == _tokens->UsdPrimvarReader_point) { nodeTypeId = _tokens->ND_UsdPrimvarReader_vector3; } else if (nodeTypeId == _tokens->UsdPrimvarReader_vector) { nodeTypeId = _tokens->ND_UsdPrimvarReader_vector3; } else if (nodeTypeId == _tokens->UsdPrimvarReader_matrix) { nodeTypeId = _tokens->ND_UsdPrimvarReader_matrix44; } else { TF_WARN("Unable to translate material node of type %s to MaterialX counterpart", nodeTypeId.GetText()); return false; } } return true; } bool GetMaterialNetworkSurfaceTerminal(const HdMaterialNetwork2& network2, HdMaterialNode2& surfaceTerminal, SdfPath& terminalPath) { const auto& connectionIt = network2.terminals.find(HdMaterialTerminalTokens->surface); if (connectionIt == network2.terminals.end()) { return false; } const HdMaterialConnection2& connection = connectionIt->second; terminalPath = connection.upstreamNode; const auto& nodeIt = network2.nodes.find(terminalPath); if (nodeIt == network2.nodes.end()) { return false; } surfaceTerminal = nodeIt->second; return true; } MaterialNetworkTranslator::MaterialNetworkTranslator(const std::string& mtlxLibPath) { m_nodeLib = mx::createDocument(); const mx::FilePathVec libFolders; // All directories if left empty. const mx::FileSearchPath folderSearchPath(mtlxLibPath); mx::loadLibraries(libFolders, folderSearchPath, m_nodeLib); } std::string MaterialNetworkTranslator::ParseNetwork(const SdfPath& id, const HdMaterialNetwork2& network) const { HdMaterialNetwork2 mtlxNetwork; if (!_ConvertNodesToMaterialXNodes(network, mtlxNetwork)) { return ""; } patchMaterialNetwork(mtlxNetwork); const mx::DocumentPtr doc = CreateMaterialXDocumentFromNetwork(id, mtlxNetwork); if (!doc) { return ""; } mx::string docStr = mx::writeToXmlString(doc); return docStr; } bool MaterialNetworkTranslator::ParseMdlNetwork(const HdMaterialNetwork2& network, std::string& fileUri, std::string& subIdentifier) { if (network.nodes.size() == 1) { const HdMaterialNode2& node = network.nodes.begin()->second; SdrRegistry& sdrRegistry = SdrRegistry::GetInstance(); SdrShaderNodeConstPtr sdrNode = sdrRegistry.GetShaderNodeByIdentifier(node.nodeTypeId); if ((sdrNode == nullptr) || sdrNode->GetContext() != _tokens->mdl) { return false; } const NdrTokenMap& metadata = sdrNode->GetMetadata(); const auto& subIdentifierIt = metadata.find(_tokens->subIdentifier); TF_DEV_AXIOM(subIdentifierIt != metadata.end()); subIdentifier = (*subIdentifierIt).second; fileUri = sdrNode->GetResolvedImplementationURI(); return true; } TF_RUNTIME_ERROR("Unsupported multi-node MDL material!"); return false; } mx::DocumentPtr MaterialNetworkTranslator::CreateMaterialXDocumentFromNetwork(const SdfPath& id, const HdMaterialNetwork2& network) const { HdMaterialNode2 surfaceTerminal; SdfPath terminalPath; if (!GetMaterialNetworkSurfaceTerminal(network, surfaceTerminal, terminalPath)) { TF_WARN("Unable to find surface terminal for material network"); return nullptr; } HdMtlxTexturePrimvarData mxHdData; return HdMtlxCreateMtlxDocumentFromHdNetwork(network, surfaceTerminal, terminalPath, id, m_nodeLib, &mxHdData); } void MaterialNetworkTranslator::patchMaterialNetwork(HdMaterialNetwork2& network) const { for (auto& pathNodePair : network.nodes) { HdMaterialNode2& node = pathNodePair.second; if (node.nodeTypeId != _tokens->ND_UsdPreviewSurface_surfaceshader) { continue; } auto& inputs = node.inputConnections; const auto patchColor3Vector3InputConnection = [&inputs, &network](const TfToken& inputName) { auto inputIt = inputs.find(inputName); if (inputIt == inputs.end()) { return; } auto& connections = inputIt->second; for (HdMaterialConnection2& connection : connections) { if (connection.upstreamOutputName != _tokens->rgb) { continue; } SdfPath upstreamNodePath = connection.upstreamNode; SdfPath convertNodePath = upstreamNodePath; for (int i = 0; network.nodes.count(convertNodePath) > 0; i++) { const std::string convertNodeName = "convert" + std::to_string(i); convertNodePath = upstreamNodePath.AppendElementString(convertNodeName); } HdMaterialNode2 convertNode; convertNode.nodeTypeId = _tokens->ND_convert_color3_vector3; convertNode.inputConnections[_tokens->in] = { { upstreamNodePath, _tokens->rgb } }; network.nodes[convertNodePath] = convertNode; connection.upstreamNode = convertNodePath; connection.upstreamOutputName = _tokens->out; } }; patchColor3Vector3InputConnection(_tokens->normal); } } PXR_NAMESPACE_CLOSE_SCOPE
9,749
C++
30.758958
118
0.634014
arhix52/Strelka/src/HdStrelka/Mesh.h
#pragma once #include <pxr/pxr.h> #include <pxr/imaging/hd/mesh.h> #include <scene/scene.h> #include <pxr/base/gf/vec2f.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaMesh final : public HdMesh { public: HF_MALLOC_TAG_NEW("new HdStrelkaMesh"); HdStrelkaMesh(const SdfPath& id, oka::Scene* scene); ~HdStrelkaMesh() override; void Sync(HdSceneDelegate* delegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, const TfToken& reprToken) override; HdDirtyBits GetInitialDirtyBitsMask() const override; const TfTokenVector& GetBuiltinPrimvarNames() const override; const std::vector<GfVec3f>& GetPoints() const; const std::vector<GfVec3f>& GetNormals() const; const std::vector<GfVec3f>& GetTangents() const; const std::vector<GfVec3i>& GetFaces() const; const std::vector<GfVec2f>& GetUVs() const; const GfMatrix4d& GetPrototypeTransform() const; const GfVec3f& GetColor() const; bool HasColor() const; const char* getName() const; protected: HdDirtyBits _PropagateDirtyBits(HdDirtyBits bits) const override; void _InitRepr(const TfToken& reprName, HdDirtyBits* dirtyBits) override; private: void _ConvertMesh(); void _UpdateGeometry(HdSceneDelegate* sceneDelegate); bool _FindPrimvar(HdSceneDelegate* sceneDelegate, const TfToken& primvarName, HdInterpolation& interpolation) const; void _PullPrimvars(HdSceneDelegate* sceneDelegate, VtVec3fArray& points, VtVec3fArray& normals, VtVec2fArray& uvs, bool& indexedNormals, bool& indexedUVs, GfVec3f& color, bool& hasColor) const; const TfTokenVector BUILTIN_PRIMVAR_NAMES = { HdTokens->points, HdTokens->normals }; GfMatrix4d mPrototypeTransform; std::vector<GfVec3f> mPoints; std::vector<GfVec3f> mNormals; std::vector<GfVec3f> mTangents; std::vector<GfVec2f> mUvs; std::vector<GfVec3i> mFaces; GfVec3f mColor; bool mHasColor; oka::Scene* mScene; std::string mName; uint32_t mStrelkaMeshId; }; PXR_NAMESPACE_CLOSE_SCOPE
2,224
C
26.8125
120
0.665018
arhix52/Strelka/src/HdStrelka/RenderBuffer.h
#pragma once #include <pxr/imaging/hd/renderBuffer.h> #include <pxr/pxr.h> #include <render/common.h> #include <render/buffer.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaRenderBuffer final : public HdRenderBuffer { public: HdStrelkaRenderBuffer(const SdfPath& id, oka::SharedContext* ctx); ~HdStrelkaRenderBuffer() override; public: bool Allocate(const GfVec3i& dimensions, HdFormat format, bool multiSamples) override; public: unsigned int GetWidth() const override; unsigned int GetHeight() const override; unsigned int GetDepth() const override; HdFormat GetFormat() const override; bool IsMultiSampled() const override; VtValue GetResource(bool multiSampled) const override; public: bool IsConverged() const override; void SetConverged(bool converged); public: void* Map() override; bool IsMapped() const override; void Unmap() override; void Resolve() override; protected: void _Deallocate() override; private: // oka::Image* mResult = nullptr; oka::SharedContext* mCtx = nullptr; oka::Buffer* mResult = nullptr; void* m_bufferMem = nullptr; uint32_t m_width; uint32_t m_height; HdFormat m_format; bool m_isMultiSampled; bool m_isMapped; bool m_isConverged; }; PXR_NAMESPACE_CLOSE_SCOPE
1,317
C
18.969697
90
0.709188
arhix52/Strelka/src/HdStrelka/RenderPass.h
#pragma once #include <pxr/imaging/hd/renderDelegate.h> #include <pxr/imaging/hd/renderPass.h> #include <pxr/pxr.h> #include <scene/camera.h> #include <scene/scene.h> #include <render/render.h> PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaCamera; class HdStrelkaMesh; class HdStrelkaRenderPass final : public HdRenderPass { public: HdStrelkaRenderPass(HdRenderIndex* index, const HdRprimCollection& collection, const HdRenderSettingsMap& settings, oka::Render* renderer, oka::Scene* scene); ~HdStrelkaRenderPass() override; bool IsConverged() const override; protected: void _Execute(const HdRenderPassStateSharedPtr& renderPassState, const TfTokenVector& renderTags) override; private: void _BakeMeshInstance(const HdStrelkaMesh* mesh, GfMatrix4d transform, uint32_t materialIndex); void _BakeMeshes(HdRenderIndex* renderIndex, GfMatrix4d rootTransform); const HdRenderSettingsMap& m_settings; bool m_isConverged; uint32_t m_lastSceneStateVersion; uint32_t m_lastRenderSettingsVersion; GfMatrix4d m_rootMatrix; oka::Scene* mScene; // ptr to global render oka::Render* mRenderer; }; PXR_NAMESPACE_CLOSE_SCOPE
1,350
C
24.490566
68
0.664444
arhix52/Strelka/src/HdStrelka/RendererPlugin.cpp
#include "RendererPlugin.h" #include "RenderDelegate.h" #include <pxr/imaging/hd/rendererPluginRegistry.h> #include <pxr/base/plug/plugin.h> #include "pxr/base/plug/thisPlugin.h" #include <log.h> PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfType) { HdRendererPluginRegistry::Define<HdStrelkaRendererPlugin>(); } HdStrelkaRendererPlugin::HdStrelkaRendererPlugin() { const PlugPluginPtr plugin = PLUG_THIS_PLUGIN; const std::string& resourcePath = plugin->GetResourcePath(); STRELKA_INFO("Resource path: {}", resourcePath.c_str()); const std::string shaderPath = resourcePath + "/shaders"; const std::string mtlxmdlPath = resourcePath + "/mtlxmdl"; const std::string mtlxlibPath = resourcePath + "/mtlxlib"; // m_translator = std::make_unique<MaterialNetworkTranslator>(mtlxlibPath); const char* envUSDPath = std::getenv("USD_DIR"); if (!envUSDPath) { STRELKA_FATAL("Please, set USD_DIR variable\n"); assert(0); m_isSupported = false; } else { const std::string USDPath(envUSDPath); m_translator = std::make_unique<MaterialNetworkTranslator>(USDPath + "/libraries"); m_isSupported = true; } } HdStrelkaRendererPlugin::~HdStrelkaRendererPlugin() { } HdRenderDelegate* HdStrelkaRendererPlugin::CreateRenderDelegate() { HdRenderSettingsMap settingsMap = {}; return new HdStrelkaRenderDelegate(settingsMap, *m_translator); } HdRenderDelegate* HdStrelkaRendererPlugin::CreateRenderDelegate(const HdRenderSettingsMap& settingsMap) { return new HdStrelkaRenderDelegate(settingsMap, *m_translator); } void HdStrelkaRendererPlugin::DeleteRenderDelegate(HdRenderDelegate* renderDelegate) { delete renderDelegate; } bool HdStrelkaRendererPlugin::IsSupported(bool gpuEnabled) const { return m_isSupported; } PXR_NAMESPACE_CLOSE_SCOPE
1,865
C++
25.657142
103
0.730831
arhix52/Strelka/src/materialmanager/mdlMaterialCompiler.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "mdlMaterialCompiler.h" #include <mi/mdl_sdk.h> #include <atomic> #include <cassert> #include <iostream> namespace oka { std::string _makeModuleName(const std::string& identifier) { return "::" + identifier; } MdlMaterialCompiler::MdlMaterialCompiler(MdlRuntime& runtime) { mLogger = mi::base::Handle<MdlLogger>(runtime.getLogger()); mDatabase = mi::base::Handle<mi::neuraylib::IDatabase>(runtime.getDatabase()); mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(runtime.getTransaction()); mFactory = mi::base::Handle<mi::neuraylib::IMdl_factory>(runtime.getFactory()); mImpExpApi = mi::base::Handle<mi::neuraylib::IMdl_impexp_api>(runtime.getImpExpApi()); } bool MdlMaterialCompiler::createModule(const std::string& identifier, std::string& moduleName) { mi::base::Handle<mi::neuraylib::IMdl_execution_context> context(mFactory->create_execution_context()); moduleName = _makeModuleName(identifier); mi::Sint32 result = mImpExpApi->load_module(mTransaction.get(), moduleName.c_str(), context.get()); mLogger->flushContextMessages(context.get()); return result == 0 || result == 1; } bool MdlMaterialCompiler::createMaterialInstace(const char* moduleName, const char* identifier, mi::base::Handle<mi::neuraylib::IFunction_call>& matInstance) { mi::base::Handle<mi::neuraylib::IMdl_execution_context> context(mFactory->create_execution_context()); mi::base::Handle<const mi::IString> moduleDbName(mFactory->get_db_module_name(moduleName)); mi::base::Handle<const mi::neuraylib::IModule> module(mTransaction->access<mi::neuraylib::IModule>(moduleDbName->get_c_str())); assert(module); std::string materialDbName = std::string(moduleDbName->get_c_str()) + "::" + identifier; mi::base::Handle<const mi::IArray> funcs(module->get_function_overloads(materialDbName.c_str(), (const mi::neuraylib::IExpression_list*)nullptr)); if (funcs->get_length() == 0) { std::string errorMsg = std::string("Material with identifier ") + identifier + " not found in MDL module\n"; mLogger->message(mi::base::MESSAGE_SEVERITY_ERROR, errorMsg.c_str()); return false; } if (funcs->get_length() > 1) { std::string errorMsg = std::string("Ambigious material identifier ") + identifier + " for MDL module\n"; mLogger->message(mi::base::MESSAGE_SEVERITY_ERROR, errorMsg.c_str()); return false; } mi::base::Handle<const mi::IString> exactMaterialDbName(funcs->get_element<mi::IString>(0)); // get material definition from database mi::base::Handle<const mi::neuraylib::IFunction_definition> matDefinition(mTransaction->access<mi::neuraylib::IFunction_definition>(exactMaterialDbName->get_c_str())); if (!matDefinition) { return false; } mi::Sint32 result; // instantiate material with default parameters and store in database matInstance = matDefinition->create_function_call(nullptr, &result); if (result != 0 || !matInstance) { return false; } return true; } bool MdlMaterialCompiler::compileMaterial(mi::base::Handle<mi::neuraylib::IFunction_call>& instance, mi::base::Handle<mi::neuraylib::ICompiled_material>& compiledMaterial) { if (!instance) { // TODO: log error return false; } mi::base::Handle<mi::neuraylib::IMdl_execution_context> context(mFactory->create_execution_context()); // performance optimizations available only in class compilation mode // (all parameters are folded in instance mode) context->set_option("fold_all_bool_parameters", true); // context->set_option("fold_all_enum_parameters", true); context->set_option("ignore_noinline", true); context->set_option("fold_ternary_on_df", true); auto flags = mi::neuraylib::IMaterial_instance::CLASS_COMPILATION; // auto flags = mi::neuraylib::IMaterial_instance::DEFAULT_OPTIONS; mi::base::Handle<mi::neuraylib::IMaterial_instance> material_instance2( instance->get_interface<mi::neuraylib::IMaterial_instance>()); compiledMaterial = mi::base::Handle<mi::neuraylib::ICompiled_material>(material_instance2->create_compiled_material(flags, context.get())); mLogger->flushContextMessages(context.get()); return true; } mi::base::Handle<mi::neuraylib::IMdl_factory>& MdlMaterialCompiler::getFactory() { return mFactory; } mi::base::Handle<mi::neuraylib::ITransaction>& MdlMaterialCompiler::getTransaction() { return mTransaction; } } // namespace oka
5,372
C++
40.976562
171
0.687826
arhix52/Strelka/src/materialmanager/mdlNeurayLoader.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "mdlNeurayLoader.h" #include <mi/mdl_sdk.h> #ifdef MI_PLATFORM_WINDOWS # include <mi/base/miwindows.h> #else # include <dlfcn.h> #endif #include "iostream" #include <string> namespace oka { MdlNeurayLoader::MdlNeurayLoader() : mDsoHandle(nullptr), mNeuray(nullptr) { } MdlNeurayLoader::~MdlNeurayLoader() { if (mNeuray) { mNeuray->shutdown(); mNeuray.reset(); } if (mDsoHandle) { unloadDso(); } } bool MdlNeurayLoader::init(const char* resourcePath, const char* imagePluginPath) { if (!loadDso(resourcePath)) { return false; } if (!loadNeuray()) { return false; } if (!loadPlugin(imagePluginPath)) { return false; } return mNeuray->start() == 0; } mi::base::Handle<mi::neuraylib::INeuray> MdlNeurayLoader::getNeuray() const { return mNeuray; } bool MdlNeurayLoader::loadPlugin(const char* imagePluginPath) { // init plugin for texture support mi::base::Handle<mi::neuraylib::INeuray> neuray(getNeuray()); mi::base::Handle<mi::neuraylib::IPlugin_configuration> configPl(neuray->get_api_component<mi::neuraylib::IPlugin_configuration>()); if (configPl->load_plugin_library(imagePluginPath)) // This function can only be called before the MDL SDK has been started. { std::cout << "Plugin file path not found, translation not possible" << std::endl; return false; } return true; } bool MdlNeurayLoader::loadDso(const char* resourcePath) { std::string dsoFilename = std::string(resourcePath) + std::string("/libmdl_sdk" MI_BASE_DLL_FILE_EXT); #ifdef MI_PLATFORM_WINDOWS HMODULE handle = LoadLibraryA(dsoFilename.c_str()); if (!handle) { LPTSTR buffer = NULL; LPCTSTR message = TEXT("unknown failure"); DWORD error_code = GetLastError(); if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, 0)) { message = buffer; } fprintf(stderr, "Failed to load library (%u): %s", error_code, message); if (buffer) { LocalFree(buffer); } return false; } #else void* handle = dlopen(dsoFilename.c_str(), RTLD_LAZY); if (!handle) { fprintf(stderr, "%s\n", dlerror()); return false; } #endif mDsoHandle = handle; return true; } bool MdlNeurayLoader::loadNeuray() { #ifdef MI_PLATFORM_WINDOWS void* symbol = GetProcAddress(reinterpret_cast<HMODULE>(mDsoHandle), "mi_factory"); if (!symbol) { LPTSTR buffer = NULL; LPCTSTR message = TEXT("unknown failure"); DWORD error_code = GetLastError(); if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, 0)) { message = buffer; } fprintf(stderr, "GetProcAddress error (%u): %s", error_code, message); if (buffer) { LocalFree(buffer); } return false; } #else void* symbol = dlsym(mDsoHandle, "mi_factory"); if (!symbol) { fprintf(stderr, "%s\n", dlerror()); return false; } #endif mNeuray = mi::base::Handle<mi::neuraylib::INeuray>(mi::neuraylib::mi_factory<mi::neuraylib::INeuray>(symbol)); if (mNeuray.is_valid_interface()) { return true; } mi::base::Handle<mi::neuraylib::IVersion> version(mi::neuraylib::mi_factory<mi::neuraylib::IVersion>(symbol)); if (!version) { fprintf(stderr, "Error: Incompatible library.\n"); } else { fprintf(stderr, "Error: Library version %s does not match header version %s.\n", version->get_product_version(), MI_NEURAYLIB_PRODUCT_VERSION_STRING); } return false; } void MdlNeurayLoader::unloadDso() { #ifdef MI_PLATFORM_WINDOWS if (FreeLibrary(reinterpret_cast<HMODULE>(mDsoHandle))) { return; } LPTSTR buffer = 0; LPCTSTR message = TEXT("unknown failure"); DWORD error_code = GetLastError(); if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, 0)) { message = buffer; } fprintf(stderr, "Failed to unload library (%u): %s", error_code, message); if (buffer) { LocalFree(buffer); } #else if (dlclose(mDsoHandle) != 0) { printf("%s\n", dlerror()); } #endif } } // namespace oka
5,771
C++
27.019417
158
0.601109
arhix52/Strelka/src/materialmanager/materialmanager.cpp
#include "materialmanager.h" #include "materials.h" #include <mi/mdl_sdk.h> #include "mdlPtxCodeGen.h" #include "mdlLogger.h" #include "mdlMaterialCompiler.h" #include "mdlNeurayLoader.h" #include "mdlRuntime.h" #include "mtlxMdlCodeGen.h" #include <filesystem> #include <fstream> #include <iostream> #include <unordered_map> #include <log.h> namespace fs = std::filesystem; namespace oka { struct MaterialManager::Module { std::string moduleName; std::string identifier; }; struct MaterialManager::MaterialInstance { mi::base::Handle<mi::neuraylib::IFunction_call> instance; }; struct MaterialManager::CompiledMaterial { mi::base::Handle<mi::neuraylib::ICompiled_material> compiledMaterial; std::string name; }; struct MaterialManager::TargetCode { struct InternalMaterial { mi::base::Handle<const mi::neuraylib::ITarget_code> targetCode; std::string codePtx; CompiledMaterial* compiledMaterial; mi::base::Uuid hash; uint32_t hash32; uint32_t functionNum; bool isUnique = false; mi::base::Handle<mi::neuraylib::ITarget_argument_block> arg_block; mi::Size argument_block_layout_index = -1; uint32_t arg_block_offset = -1; // offset for arg block in argBlockData uint32_t ro_offset = -1; }; std::vector<InternalMaterial> internalMaterials; std::unordered_map<uint32_t, uint32_t> uidToInternalIndex; std::unordered_map<CompiledMaterial*, uint32_t> ptrToInternalIndex; std::vector<Mdl_resource_info> resourceInfo; std::vector<oka::MdlPtxCodeGen::InternalMaterialInfo> internalsInfo; std::vector<const mi::neuraylib::ICompiled_material*> compiledMaterials; bool isInitialized = false; // MDL data for GPU buffers std::vector<MdlMaterial> mdlMaterials; std::vector<uint8_t> argBlockData; std::vector<uint8_t> roData; }; struct MaterialManager::TextureDescription { std::string dbName; mi::base::Handle<const mi::neuraylib::IType_texture> textureType; }; class Resource_callback : public mi::base::Interface_implement<mi::neuraylib::ITarget_resource_callback> { public: /// Constructor. Resource_callback(mi::base::Handle<mi::neuraylib::ITransaction>& transaction, const mi::base::Handle<const mi::neuraylib::ITarget_code>& target_code) : m_transaction(transaction), m_target_code(target_code) { } /// Destructor. virtual ~Resource_callback() = default; /// Returns a resource index for the given resource value usable by the target code /// resource handler for the corresponding resource type. /// /// \param resource the resource value /// /// \returns a resource index or 0 if no resource index can be returned mi::Uint32 get_resource_index(mi::neuraylib::IValue_resource const* resource) override { // check whether we already know the resource index auto it = m_resource_cache.find(resource); if (it != m_resource_cache.end()) return it->second; const char* filePath = resource->get_file_path(); // handle resources already known by the target code mi::Uint32 res_idx = m_target_code->get_known_resource_index(m_transaction.get(), resource); if (res_idx > 0) { // only accept body resources switch (resource->get_kind()) { case mi::neuraylib::IValue::VK_TEXTURE: if (res_idx < m_target_code->get_texture_count()) return res_idx; break; case mi::neuraylib::IValue::VK_LIGHT_PROFILE: if (res_idx < m_target_code->get_light_profile_count()) return res_idx; break; case mi::neuraylib::IValue::VK_BSDF_MEASUREMENT: if (res_idx < m_target_code->get_bsdf_measurement_count()) return res_idx; break; default: return 0u; // invalid kind } } // invalid (or empty) resource const char* name = resource->get_value(); if (!name) { return 0; } switch (resource->get_kind()) { case mi::neuraylib::IValue::VK_TEXTURE: { mi::base::Handle<mi::neuraylib::IValue_texture const> val_texture( resource->get_interface<mi::neuraylib::IValue_texture const>()); if (!val_texture) return 0u; // unknown resource mi::base::Handle<const mi::neuraylib::IType_texture> texture_type(val_texture->get_type()); mi::neuraylib::ITarget_code::Texture_shape shape = mi::neuraylib::ITarget_code::Texture_shape(texture_type->get_shape()); // m_compile_result.textures.emplace_back(resource->get_value(), shape); // res_idx = m_compile_result.textures.size() - 1; break; } case mi::neuraylib::IValue::VK_LIGHT_PROFILE: // m_compile_result.light_profiles.emplace_back(resource->get_value()); // res_idx = m_compile_result.light_profiles.size() - 1; break; case mi::neuraylib::IValue::VK_BSDF_MEASUREMENT: // m_compile_result.bsdf_measurements.emplace_back(resource->get_value()); // res_idx = m_compile_result.bsdf_measurements.size() - 1; break; default: return 0u; // invalid kind } m_resource_cache[resource] = res_idx; return res_idx; } /// Returns a string identifier for the given string value usable by the target code. /// /// The value 0 is always the "not known string". /// /// \param s the string value mi::Uint32 get_string_index(mi::neuraylib::IValue_string const* s) override { char const* str_val = s->get_value(); if (str_val == nullptr) return 0u; for (mi::Size i = 0, n = m_target_code->get_string_constant_count(); i < n; ++i) { if (strcmp(m_target_code->get_string_constant(i), str_val) == 0) return mi::Uint32(i); } // string not known by code return 0u; } private: mi::base::Handle<mi::neuraylib::ITransaction> m_transaction; mi::base::Handle<const mi::neuraylib::ITarget_code> m_target_code; std::unordered_map<mi::neuraylib::IValue_resource const*, mi::Uint32> m_resource_cache; }; class MaterialManager::Context { public: Context() { configurePaths(); }; ~Context(){}; // paths is array of resource pathes + mdl path bool addMdlSearchPath(const char* paths[], uint32_t numPaths) { mRuntime = std::make_unique<oka::MdlRuntime>(); if (!mRuntime->init(paths, numPaths, mPathso.c_str(), mImagePluginPath.c_str())) { return false; } mMtlxCodeGen = std::make_unique<oka::MtlxMdlCodeGen>(mtlxLibPath.generic_string().c_str(), mRuntime.get()); mMatCompiler = std::make_unique<oka::MdlMaterialCompiler>(*mRuntime); mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(mRuntime->getTransaction()); mNeuray = mRuntime->getNeuray(); mCodeGen = std::make_unique<MdlPtxCodeGen>(); mCodeGen->init(*mRuntime); std::vector<char> data; { const fs::path cwdPath = fs::current_path(); const fs::path precompiledPath = cwdPath / "optix/shaders/OptixRender_radiance_closest_hit.bc"; std::ifstream file(precompiledPath.c_str(), std::ios::in | std::ios::binary); if (!file.is_open()) { STRELKA_FATAL("Cannot open precompiled closest hit file.\n"); return false; } file.seekg(0, std::ios::end); data.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(data.data(), data.size()); } if (!mCodeGen->setOptionBinary("llvm_renderer_module", data.data(), data.size())) { STRELKA_ERROR("Unable to set binary options!"); return false; } return true; } Module* createMtlxModule(const char* mtlSrc) { assert(mMtlxCodeGen); std::unique_ptr<Module> module = std::make_unique<Module>(); bool res = mMtlxCodeGen->translate(mtlSrc, mMdlSrc, module->identifier); if (res) { std::string mtlxFile = "./data/materials/mtlx/" + module->identifier + ".mtlx"; std::string mdlFile = "./data/materials/mtlx/" + module->identifier + ".mdl"; auto dumpToFile = [](const std::string& fileName, const std::string& content) { std::ofstream material(fileName.c_str()); if (!material.is_open()) { STRELKA_ERROR("can not create file: {}", fileName.c_str()); return; } material << content; material.close(); return; }; dumpToFile(mtlxFile, mtlSrc); dumpToFile(mdlFile, mMdlSrc); if (!mMatCompiler->createModule(module->identifier, module->moduleName)) { STRELKA_ERROR("failed to create MDL module: {} identifier: {}", module->moduleName.c_str(), module->identifier.c_str()); return nullptr; } return module.release(); } else { STRELKA_ERROR("failed to translate MaterialX -> MDL"); return nullptr; } }; Module* createModule(const char* file) { std::unique_ptr<Module> module = std::make_unique<Module>(); const fs::path materialFile = file; module->identifier = materialFile.stem().string(); if (!mMatCompiler->createModule(module->identifier, module->moduleName)) { return nullptr; } return module.release(); }; void destroyModule(Module* module) { assert(module); delete module; }; MaterialInstance* createMaterialInstance(MaterialManager::Module* module, const char* materialName) { assert(module); assert(materialName); std::unique_ptr<MaterialInstance> material = std::make_unique<MaterialInstance>(); if (strcmp(materialName, "") == 0) // mtlx { materialName = module->identifier.c_str(); } if (!mMatCompiler->createMaterialInstace(module->moduleName.c_str(), materialName, material->instance)) { return nullptr; } return material.release(); } void destroyMaterialInstance(MaterialInstance* matInst) { assert(matInst); delete matInst; } void dumpParams(const TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material) { assert(targetCode); assert(targetCode->isInitialized); assert(material); const uint32_t internalIndex = materialIdx;// targetCode->ptrToInternalIndex.at(material); const mi::Size argLayoutIndex = targetCode->internalMaterials[internalIndex].argument_block_layout_index; mi::base::Handle<const mi::neuraylib::ITarget_value_layout> arg_layout( targetCode->internalMaterials[internalIndex].targetCode->get_argument_block_layout(argLayoutIndex)); if (targetCode->internalMaterials[internalIndex].arg_block == nullptr) { STRELKA_ERROR("Material : {} has no arg block!\n", material->name.c_str()); return; } char* baseArgBlockData = targetCode->internalMaterials[internalIndex].arg_block->get_data(); const mi::Size argBlockOffset = targetCode->internalMaterials[internalIndex].arg_block_offset; const mi::Size paramCount = material->compiledMaterial->get_parameter_count(); STRELKA_DEBUG("Material name: {0}\t param count: {1}", material->name.c_str(), paramCount); for (int pi = 0; pi < paramCount; ++pi) { const char* name = material->compiledMaterial->get_parameter_name(pi); STRELKA_DEBUG("# {0}: Param name: {1}", pi, name); mi::neuraylib::Target_value_layout_state valLayoutState = arg_layout->get_nested_state(pi); mi::neuraylib::IValue::Kind kind; mi::Size arg_size; const mi::Size offsetInArgBlock = arg_layout->get_layout(kind, arg_size, valLayoutState); STRELKA_DEBUG("\t offset = {0} \t size = {1}", offsetInArgBlock, arg_size); // char* data = baseArgBlockData + offsetInArgBlock; const uint8_t* data = targetCode->argBlockData.data() + argBlockOffset + offsetInArgBlock; switch (kind) { case mi::neuraylib::IValue::Kind::VK_FLOAT: { float val = *((float*)data); STRELKA_DEBUG("\t type float"); STRELKA_DEBUG("\t val = {}", val); break; } case mi::neuraylib::IValue::Kind::VK_INT: { int val = *((int*)data); STRELKA_DEBUG("\t type int"); STRELKA_DEBUG("\t val = {}", val); break; } case mi::neuraylib::IValue::Kind::VK_BOOL: { bool val = *((bool*)data); STRELKA_DEBUG("\t type bool"); STRELKA_DEBUG("\t val = {}", val); break; } case mi::neuraylib::IValue::Kind::VK_COLOR: { float* val = (float*)data; STRELKA_DEBUG("\t type color"); STRELKA_DEBUG("\t val = ({}, {}, {})", val[0], val[1], val[2]); break; } case mi::neuraylib::IValue::Kind::VK_TEXTURE: { STRELKA_DEBUG("\t type texture"); int val = *((int*)data); STRELKA_DEBUG("\t val = {}", val); break; } default: break; } // uint8_t* dst = targetCode->argBlockData.data() + argBlockOffset + offsetInArgBlock; // memcpy(dst, param.value.data(), param.value.size()); // isParamFound = true; } } bool setParam(TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material, const Param& param) { assert(targetCode); assert(targetCode->isInitialized); assert(material); bool isParamFound = false; for (int pi = 0; pi < material->compiledMaterial->get_parameter_count(); ++pi) { if (!strcmp(material->compiledMaterial->get_parameter_name(pi), param.name.c_str())) { const uint32_t internalIndex = materialIdx; //targetCode->ptrToInternalIndex[material]; const mi::Size argLayoutIndex = targetCode->internalMaterials[internalIndex].argument_block_layout_index; mi::base::Handle<const mi::neuraylib::ITarget_value_layout> arg_layout( targetCode->internalMaterials[internalIndex].targetCode->get_argument_block_layout(argLayoutIndex)); mi::neuraylib::Target_value_layout_state valLayoutState = arg_layout->get_nested_state(pi); mi::neuraylib::IValue::Kind kind; mi::Size arg_size; const mi::Size offsetInArgBlock = arg_layout->get_layout(kind, arg_size, valLayoutState); assert(arg_size == param.value.size()); // TODO: should match, otherwise error const mi::Size argBlockOffset = targetCode->internalMaterials[internalIndex].arg_block_offset; uint8_t* dst = targetCode->argBlockData.data() + argBlockOffset + offsetInArgBlock; memcpy(dst, param.value.data(), param.value.size()); isParamFound = true; break; } } return isParamFound; } TextureDescription* createTextureDescription(const char* name, const char* gammaMode) { assert(name); float gamma = 1.0; const char* texGamma = ""; if (strcmp(gammaMode, "srgb") == 0) { gamma = 2.2f; texGamma = "_srgb"; } else if (strcmp(gammaMode, "linear") == 0) { gamma = 1.0f; texGamma = "_linear"; } std::string textureDbName = std::string(name) + std::string(texGamma); mi::base::Handle<const mi::neuraylib::ITexture> texAccess = mi::base::Handle<const mi::neuraylib::ITexture>( mMatCompiler->getTransaction()->access<mi::neuraylib::ITexture>(textureDbName.c_str())); // check if it is in DB if (!texAccess.is_valid_interface()) { // Load it mi::base::Handle<mi::neuraylib::ITexture> tex( mMatCompiler->getTransaction()->create<mi::neuraylib::ITexture>("Texture")); mi::base::Handle<mi::neuraylib::IImage> image( mMatCompiler->getTransaction()->create<mi::neuraylib::IImage>("Image")); if (image->reset_file(name) != 0) { // TODO: report error could not find texture! return nullptr; } std::string imageName = textureDbName + std::string("_image"); mMatCompiler->getTransaction()->store(image.get(), imageName.c_str()); tex->set_image(imageName.c_str()); tex->set_gamma(gamma); mMatCompiler->getTransaction()->store(tex.get(), textureDbName.c_str()); } mi::base::Handle<mi::neuraylib::IType_factory> typeFactory( mMatCompiler->getFactory()->create_type_factory(mMatCompiler->getTransaction().get())); // TODO: texture could be 1D, 3D mi::base::Handle<const mi::neuraylib::IType_texture> textureType( typeFactory->create_texture(mi::neuraylib::IType_texture::TS_2D)); TextureDescription* texDesc = new TextureDescription; texDesc->dbName = textureDbName; texDesc->textureType = textureType; return texDesc; } const char* getTextureDbName(TextureDescription* texDesc) { return texDesc->dbName.c_str(); } CompiledMaterial* compileMaterial(MaterialInstance* matInstance) { assert(matInstance); std::unique_ptr<CompiledMaterial> material = std::make_unique<CompiledMaterial>(); if (!mMatCompiler->compileMaterial(matInstance->instance, material->compiledMaterial)) { return nullptr; } material->name = matInstance->instance->get_function_definition(); return material.release(); }; void destroyCompiledMaterial(CompiledMaterial* materials) { assert(materials); delete materials; } const char* getName(CompiledMaterial* compMaterial) { return compMaterial->name.c_str(); } TargetCode* generateTargetCode(CompiledMaterial** materials, const uint32_t numMaterials) { TargetCode* targetCode = new TargetCode; std::unordered_map<uint32_t, uint32_t> uidToFunctionNum; std::vector<TargetCode::InternalMaterial>& internalMaterials = targetCode->internalMaterials; internalMaterials.resize(numMaterials); std::vector<const mi::neuraylib::ICompiled_material*> materialsToCompile; for (int i = 0; i < numMaterials; ++i) { internalMaterials[i].compiledMaterial = materials[i]; internalMaterials[i].hash = materials[i]->compiledMaterial->get_hash(); internalMaterials[i].hash32 = uuid_hash32(internalMaterials[i].hash); uint32_t functionNum = -1; bool isUnique = false; if (uidToFunctionNum.find(internalMaterials[i].hash32) != uidToFunctionNum.end()) { functionNum = uidToFunctionNum[internalMaterials[i].hash32]; } else { functionNum = uidToFunctionNum.size(); uidToFunctionNum[internalMaterials[i].hash32] = functionNum; isUnique = true; materialsToCompile.push_back(internalMaterials[i].compiledMaterial->compiledMaterial.get()); // log output STRELKA_DEBUG("Material to compile: {}", getName(internalMaterials[i].compiledMaterial)); } internalMaterials[i].isUnique = isUnique; internalMaterials[i].functionNum = functionNum; targetCode->uidToInternalIndex[internalMaterials[i].hash32] = i; targetCode->ptrToInternalIndex[materials[i]] = i; } const uint32_t numMaterialsToCompile = materialsToCompile.size(); STRELKA_INFO("Num Materials to compile: {}", numMaterialsToCompile); std::vector<oka::MaterialManager::TargetCode::InternalMaterial> compiledInternalMaterials(numMaterialsToCompile); for (int i = 0; i < numMaterialsToCompile; ++i) { oka::MdlPtxCodeGen::InternalMaterialInfo internalsInfo; compiledInternalMaterials[i].targetCode = mCodeGen->translate(materialsToCompile[i], compiledInternalMaterials[i].codePtx, internalsInfo); compiledInternalMaterials[i].argument_block_layout_index = internalsInfo.argument_block_index; } targetCode->mdlMaterials.resize(numMaterials); for (uint32_t i = 0; i < numMaterials; ++i) { const uint32_t compiledOrder = internalMaterials[i].functionNum; assert(compiledOrder < numMaterialsToCompile); internalMaterials[i].argument_block_layout_index = compiledInternalMaterials[compiledOrder].argument_block_layout_index; internalMaterials[i].targetCode = compiledInternalMaterials[compiledOrder].targetCode; internalMaterials[i].codePtx = compiledInternalMaterials[compiledOrder].codePtx; targetCode->mdlMaterials[i].functionId = compiledOrder; } targetCode->argBlockData = loadArgBlocks(targetCode); targetCode->roData = loadROData(targetCode); // uint32_t texCount = targetCode->targetCode->get_texture_count(); // if (texCount > 0) // { // targetCode->resourceInfo.resize(texCount); // for (uint32_t i = 0; i < texCount; ++i) // { // targetCode->resourceInfo[i].gpu_resource_array_start = i; // const char* texUrl = targetCode->targetCode->get_texture_url(i); // const int texBody = targetCode->targetCode->get_body_texture_count(); // const char* texName = getTextureName(targetCode, i); // // const float* data = getTextureData(targetCode, i); // // uint32_t width = getTextureWidth(targetCode, i); // // uint32_t height = getTextureHeight(targetCode, i); // // const char* type = getTextureType(targetCode, i); // printf("Material texture name: %s\n", texName); // } // } // else //{ // targetCode->resourceInfo.resize(1); // } targetCode->isInitialized = true; return targetCode; }; int registerResource(TargetCode* targetCode, int index) { Mdl_resource_info ri{ 0 }; ri.gpu_resource_array_start = index; targetCode->resourceInfo.push_back(ri); return (int)targetCode->resourceInfo.size(); // resource id 0 is reserved for invalid, but we store resources // from 0 internally } const char* getShaderCode(const TargetCode* targetCode, uint32_t materialIdx) { const uint32_t compiledOrder = targetCode->internalMaterials[materialIdx].functionNum; return targetCode->internalMaterials[compiledOrder].codePtx.c_str(); } uint32_t getArgBlockOffset(const TargetCode* targetCode, uint32_t materialId) { return targetCode->internalMaterials[materialId].arg_block_offset; } uint32_t getReadOnlyBlockOffset(const TargetCode* targetCode, uint32_t materialId) { return targetCode->internalMaterials[materialId].ro_offset; } uint32_t getReadOnlyBlockSize(const TargetCode* shaderCode) { return shaderCode->roData.size(); } const uint8_t* getReadOnlyBlockData(const TargetCode* targetCode) { return targetCode->roData.data(); } uint32_t getArgBufferSize(const TargetCode* shaderCode) { return shaderCode->argBlockData.size(); } const uint8_t* getArgBufferData(const TargetCode* targetCode) { return targetCode->argBlockData.data(); } uint32_t getResourceInfoSize(const TargetCode* targetCode) { return targetCode->resourceInfo.size() * sizeof(Mdl_resource_info); } const uint8_t* getResourceInfoData(const TargetCode* targetCode) { return reinterpret_cast<const uint8_t*>(targetCode->resourceInfo.data()); } uint32_t getMdlMaterialSize(const TargetCode* targetCode) { return targetCode->mdlMaterials.size() * sizeof(MdlMaterial); } const uint8_t* getMdlMaterialData(const TargetCode* targetCode) { return reinterpret_cast<const uint8_t*>(targetCode->mdlMaterials.data()); } uint32_t getTextureCount(const TargetCode* targetCode, uint32_t materialId) { return targetCode->internalMaterials[materialId].targetCode->get_texture_count(); } const char* getTextureName(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { assert(index); // index == 0 is invalid return targetCode->internalMaterials[materialId].targetCode->get_texture(index); } const float* getTextureData(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { // assert(index); // index == 0 is invalid assert(mTransaction); auto cachedCanvas = m_indexToCanvas.find(index); if (cachedCanvas == m_indexToCanvas.end()) { mi::base::Handle<mi::neuraylib::IImage_api> image_api(mNeuray->get_api_component<mi::neuraylib::IImage_api>()); mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>( targetCode->internalMaterials[materialId].targetCode->get_texture(index))); mi::base::Handle<const mi::neuraylib::IImage> image( mTransaction->access<mi::neuraylib::IImage>(texture->get_image())); mi::base::Handle<const mi::neuraylib::ICanvas> canvas(image->get_canvas(0, 0, 0)); char const* image_type = image->get_type(0, 0); // if (canvas->get_tiles_size_x() != 1 || canvas->get_tiles_size_y() != 1) // { // mLogger->message(mi::base::MESSAGE_SEVERITY_ERROR, "The example does not support tiled images!"); // return nullptr; // } if (texture->get_effective_gamma(0, 0) != 1.0f) { // Copy/convert to float4 canvas and adjust gamma from "effective gamma" to 1. mi::base::Handle<mi::neuraylib::ICanvas> gamma_canvas(image_api->convert(canvas.get(), "Color")); gamma_canvas->set_gamma(texture->get_effective_gamma(0, 0)); image_api->adjust_gamma(gamma_canvas.get(), 1.0f); canvas = gamma_canvas; } else if (strcmp(image_type, "Color") != 0 && strcmp(image_type, "Float32<4>") != 0) { // Convert to expected format canvas = image_api->convert(canvas.get(), "Color"); } m_indexToCanvas[index] = canvas; cachedCanvas = m_indexToCanvas.find(index); } mi::Float32 const* data = nullptr; mi::neuraylib::ITarget_code::Texture_shape texture_shape = targetCode->internalMaterials[materialId].targetCode->get_texture_shape(index); if (texture_shape == mi::neuraylib::ITarget_code::Texture_shape_2d) { mi::base::Handle<const mi::neuraylib::ITile> tile(cachedCanvas->second->get_tile()); data = static_cast<mi::Float32 const*>(tile->get_data()); } return data; } const char* getTextureType(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { // assert(index); // index == 0 is invalid mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>( targetCode->internalMaterials[materialId].targetCode->get_texture(index))); mi::base::Handle<const mi::neuraylib::IImage> image( mTransaction->access<mi::neuraylib::IImage>(texture->get_image())); char const* imageType = image->get_type(0, 0); return imageType; } uint32_t getTextureWidth(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { // assert(index); // index == 0 is invalid mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>( targetCode->internalMaterials[materialId].targetCode->get_texture(index))); mi::base::Handle<const mi::neuraylib::IImage> image( mTransaction->access<mi::neuraylib::IImage>(texture->get_image())); mi::base::Handle<const mi::neuraylib::ICanvas> canvas(image->get_canvas(0, 0, 0)); mi::Uint32 texWidth = canvas->get_resolution_x(); return texWidth; } uint32_t getTextureHeight(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { // assert(index); // index == 0 is invalid mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>( targetCode->internalMaterials[materialId].targetCode->get_texture(index))); mi::base::Handle<const mi::neuraylib::IImage> image( mTransaction->access<mi::neuraylib::IImage>(texture->get_image())); mi::base::Handle<const mi::neuraylib::ICanvas> canvas(image->get_canvas(0, 0, 0)); mi::Uint32 texHeight = canvas->get_resolution_y(); return texHeight; } uint32_t getTextureBytesPerTexel(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { // assert(index); // index == 0 is invalid mi::base::Handle<mi::neuraylib::IImage_api> image_api(mNeuray->get_api_component<mi::neuraylib::IImage_api>()); mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>( targetCode->internalMaterials[materialId].targetCode->get_texture(index))); mi::base::Handle<const mi::neuraylib::IImage> image( mTransaction->access<mi::neuraylib::IImage>(texture->get_image())); char const* imageType = image->get_type(0, 0); int cpp = image_api->get_components_per_pixel(imageType); int bpc = image_api->get_bytes_per_component(imageType); int bpp = cpp * bpc; return bpp; } private: std::string mImagePluginPath; std::string mPathso; std::string mMdlSrc; fs::path mtlxLibPath; std::unordered_map<uint32_t, mi::base::Handle<const mi::neuraylib::ICanvas>> m_indexToCanvas; void configurePaths() { using namespace std; const fs::path cwd = fs::current_path(); #ifdef MI_PLATFORM_WINDOWS mPathso = cwd.string(); mImagePluginPath = cwd.string() + "/nv_openimageio.dll"; #else mPathso = cwd.string(); mImagePluginPath = cwd.string() + "/nv_openimageio.so"; #endif } std::unique_ptr<oka::MdlPtxCodeGen> mCodeGen = nullptr; std::unique_ptr<oka::MdlMaterialCompiler> mMatCompiler = nullptr; std::unique_ptr<oka::MdlRuntime> mRuntime = nullptr; std::unique_ptr<oka::MtlxMdlCodeGen> mMtlxCodeGen = nullptr; mi::base::Handle<mi::neuraylib::ITransaction> mTransaction; mi::base::Handle<oka::MdlLogger> mLogger; mi::base::Handle<mi::neuraylib::INeuray> mNeuray; std::vector<uint8_t> loadArgBlocks(TargetCode* targetCode); std::vector<uint8_t> loadROData(TargetCode* targetCode); }; MaterialManager::MaterialManager() { mContext = std::make_unique<Context>(); } MaterialManager::~MaterialManager() { mContext.reset(nullptr); }; bool MaterialManager::addMdlSearchPath(const char* paths[], uint32_t numPaths) { return mContext->addMdlSearchPath(paths, numPaths); } MaterialManager::Module* MaterialManager::createModule(const char* file) { return mContext->createModule(file); } MaterialManager::Module* MaterialManager::createMtlxModule(const char* file) { return mContext->createMtlxModule(file); } void MaterialManager::destroyModule(MaterialManager::Module* module) { return mContext->destroyModule(module); } MaterialManager::MaterialInstance* MaterialManager::createMaterialInstance(MaterialManager::Module* module, const char* materialName) { return mContext->createMaterialInstance(module, materialName); } void MaterialManager::destroyMaterialInstance(MaterialManager::MaterialInstance* matInst) { return mContext->destroyMaterialInstance(matInst); } MaterialManager::TextureDescription* MaterialManager::createTextureDescription(const char* name, const char* gamma) { return mContext->createTextureDescription(name, gamma); } const char* MaterialManager::getTextureDbName(TextureDescription* texDesc) { return mContext->getTextureDbName(texDesc); } void MaterialManager::dumpParams(const TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material) { return mContext->dumpParams(targetCode, materialIdx, material); } bool MaterialManager::setParam(TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material, const Param& param) { return mContext->setParam(targetCode, materialIdx, material, param); } MaterialManager::CompiledMaterial* MaterialManager::compileMaterial(MaterialManager::MaterialInstance* matInstance) { return mContext->compileMaterial(matInstance); } void MaterialManager::destroyCompiledMaterial(MaterialManager::CompiledMaterial* material) { return mContext->destroyCompiledMaterial(material); } const char* MaterialManager::getName(CompiledMaterial* compMaterial) { return mContext->getName(compMaterial); } MaterialManager::TargetCode* MaterialManager::generateTargetCode(CompiledMaterial** materials, uint32_t numMaterials) { return mContext->generateTargetCode(materials, numMaterials); } const char* MaterialManager::getShaderCode(const TargetCode* targetCode, uint32_t materialId) // get shader code { return mContext->getShaderCode(targetCode, materialId); } uint32_t MaterialManager::getReadOnlyBlockSize(const TargetCode* targetCode) { return mContext->getReadOnlyBlockSize(targetCode); } const uint8_t* MaterialManager::getReadOnlyBlockData(const TargetCode* targetCode) { return mContext->getReadOnlyBlockData(targetCode); } uint32_t MaterialManager::getArgBufferSize(const TargetCode* targetCode) { return mContext->getArgBufferSize(targetCode); } const uint8_t* MaterialManager::getArgBufferData(const TargetCode* targetCode) { return mContext->getArgBufferData(targetCode); } uint32_t MaterialManager::getArgBlockOffset(const TargetCode* targetCode, uint32_t materialId) { return mContext->getArgBlockOffset(targetCode, materialId); } uint32_t MaterialManager::getReadOnlyOffset(const TargetCode* targetCode, uint32_t materialId) { return mContext->getArgBlockOffset(targetCode, materialId); } uint32_t MaterialManager::getResourceInfoSize(const TargetCode* targetCode) { return mContext->getResourceInfoSize(targetCode); } const uint8_t* MaterialManager::getResourceInfoData(const TargetCode* targetCode) { return mContext->getResourceInfoData(targetCode); } int MaterialManager::registerResource(TargetCode* targetCode, int index) { return mContext->registerResource(targetCode, index); } uint32_t MaterialManager::getMdlMaterialSize(const TargetCode* targetCode) { return mContext->getMdlMaterialSize(targetCode); } const uint8_t* MaterialManager::getMdlMaterialData(const TargetCode* targetCode) { return mContext->getMdlMaterialData(targetCode); } uint32_t MaterialManager::getTextureCount(const TargetCode* targetCode, uint32_t materialId) { return mContext->getTextureCount(targetCode, materialId); } const char* MaterialManager::getTextureName(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { return mContext->getTextureName(targetCode, materialId, index); } const float* MaterialManager::getTextureData(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { return mContext->getTextureData(targetCode, materialId, index); } const char* MaterialManager::getTextureType(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { return mContext->getTextureType(targetCode, materialId, index); } uint32_t MaterialManager::getTextureWidth(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { return mContext->getTextureWidth(targetCode, materialId, index); } uint32_t MaterialManager::getTextureHeight(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { return mContext->getTextureHeight(targetCode, materialId, index); } uint32_t MaterialManager::getTextureBytesPerTexel(const TargetCode* targetCode, uint32_t materialId, uint32_t index) { return mContext->getTextureBytesPerTexel(targetCode, materialId, index); } inline size_t round_to_power_of_two(size_t value, size_t power_of_two_factor) { return (value + (power_of_two_factor - 1)) & ~(power_of_two_factor - 1); } std::vector<uint8_t> MaterialManager::Context::loadArgBlocks(TargetCode* targetCode) { std::vector<uint8_t> res; for (int i = 0; i < targetCode->internalMaterials.size(); ++i) { mi::base::Handle<const mi::neuraylib::ITarget_code>& mdlTargetCode = targetCode->internalMaterials[i].targetCode; mi::base::Handle<Resource_callback> callback(new Resource_callback(mTransaction, mdlTargetCode)); // const uint32_t compiledIndex = targetCode->internalMaterials[i].functionNum; const mi::Size argLayoutIndex = targetCode->internalMaterials[i].argument_block_layout_index; const mi::Size layoutCount = mdlTargetCode->get_argument_layout_count(); if (argLayoutIndex != static_cast<mi::Size>(-1) && argLayoutIndex < layoutCount) { mi::neuraylib::ICompiled_material* compiledMaterial = targetCode->internalMaterials[i].compiledMaterial->compiledMaterial.get(); targetCode->internalMaterials[i].arg_block = mdlTargetCode->create_argument_block(argLayoutIndex, compiledMaterial, callback.get()); if (!targetCode->internalMaterials[i].arg_block) { std::cerr << ("Failed to create material argument block: ") << std::endl; res.resize(4); return res; } // create a buffer to provide those parameters to the shader // align to 4 bytes and pow of two const size_t buffer_size = round_to_power_of_two(targetCode->internalMaterials[i].arg_block->get_size(), 4); std::vector<uint8_t> argBlockData = std::vector<uint8_t>(buffer_size, 0); memcpy(argBlockData.data(), targetCode->internalMaterials[i].arg_block->get_data(), targetCode->internalMaterials[i].arg_block->get_size()); // set offset in common arg block buffer targetCode->internalMaterials[i].arg_block_offset = (uint32_t)res.size(); targetCode->mdlMaterials[i].arg_block_offset = (int)res.size(); res.insert(res.end(), argBlockData.begin(), argBlockData.end()); } } if (res.empty()) { res.resize(4); } return res; } std::vector<uint8_t> MaterialManager::Context::loadROData(TargetCode* targetCode) { std::vector<uint8_t> roData; for (int i = 0; i < targetCode->internalMaterials.size(); ++i) { const size_t segCount = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_count(); targetCode->internalMaterials[i].ro_offset = roData.size(); for (size_t s = 0; s < segCount; ++s) { const char* data = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_data(s); size_t dataSize = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_size(s); const char* name = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_name(s); std::cerr << "MDL segment [" << s << "] name : " << name << std::endl; if (dataSize != 0) { roData.insert(roData.end(), data, data + dataSize); } } } if (roData.empty()) { roData.resize(4); } return roData; } } // namespace oka
41,296
C++
37.096863
132
0.627809
arhix52/Strelka/src/materialmanager/mdlPtxCodeGen.cpp
#include "mdlPtxCodeGen.h" #include "materials.h" #include <mi/mdl_sdk.h> #include <cassert> #include <sstream> #include <log.h> namespace oka { const char* SCATTERING_FUNC_NAME = "mdl_bsdf_scattering"; const char* EMISSION_FUNC_NAME = "mdl_edf_emission"; const char* EMISSION_INTENSITY_FUNC_NAME = "mdl_edf_emission_intensity"; const char* MATERIAL_STATE_NAME = "Shading_state_material"; bool MdlPtxCodeGen::init(MdlRuntime& runtime) { mi::base::Handle<mi::neuraylib::IMdl_backend_api> backendApi(runtime.getBackendApi()); mBackend = mi::base::Handle<mi::neuraylib::IMdl_backend>( backendApi->get_backend(mi::neuraylib::IMdl_backend_api::MB_CUDA_PTX)); if (!mBackend.is_valid_interface()) { mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "CUDA backend not supported by MDL runtime"); return false; } // 75 - Turing // 86 - Ampere // 89 - Ada if (mBackend->set_option("sm_version", "75") != 0) { mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option sm_version failed"); return false; } if (mBackend->set_option("num_texture_spaces", "2") != 0) { mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option num_texture_spaces failed"); return false; } if (mBackend->set_option("num_texture_results", "16") != 0) { mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option num_texture_results failed"); return false; } if (mBackend->set_option("tex_lookup_call_mode", "direct_call") != 0) { mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option tex_lookup_call_mode failed"); return false; } mLogger = mi::base::Handle<MdlLogger>(runtime.getLogger()); mLoader = std::move(runtime.mLoader); mi::base::Handle<mi::neuraylib::IMdl_factory> factory(runtime.getFactory()); mContext = mi::base::Handle<mi::neuraylib::IMdl_execution_context>(factory->create_execution_context()); mDatabase = mi::base::Handle<mi::neuraylib::IDatabase>(runtime.getDatabase()); mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(runtime.getTransaction()); return true; } mi::base::Handle<const mi::neuraylib::ITarget_code> MdlPtxCodeGen::translate( const mi::neuraylib::ICompiled_material* material, std::string& ptxSrc, InternalMaterialInfo& internalsInfo) { assert(material); mi::base::Handle<mi::neuraylib::ILink_unit> linkUnit(mBackend->create_link_unit(mTransaction.get(), mContext.get())); mLogger->flushContextMessages(mContext.get()); if (!linkUnit) { throw "Failed to create link unit"; } mi::Size argBlockIndex; if (!appendMaterialToLinkUnit(0, material, linkUnit.get(), argBlockIndex)) { throw "Failed to append material to the link unit"; } internalsInfo.argument_block_index = argBlockIndex; mi::base::Handle<const mi::neuraylib::ITarget_code> targetCode( mBackend->translate_link_unit(linkUnit.get(), mContext.get())); mLogger->flushContextMessages(mContext.get()); if (!targetCode) { throw "No target code"; } ptxSrc = targetCode->get_code(); return targetCode; } mi::base::Handle<const mi::neuraylib::ITarget_code> MdlPtxCodeGen::translate( const std::vector<const mi::neuraylib::ICompiled_material*>& materials, std::string& ptxSrc, std::vector<InternalMaterialInfo>& internalsInfo) { mi::base::Handle<mi::neuraylib::ILink_unit> linkUnit(mBackend->create_link_unit(mTransaction.get(), mContext.get())); mLogger->flushContextMessages(mContext.get()); if (!linkUnit) { throw "Failed to create link unit"; } uint32_t materialCount = materials.size(); internalsInfo.resize(materialCount); mi::Size argBlockIndex; for (uint32_t i = 0; i < materialCount; i++) { const mi::neuraylib::ICompiled_material* material = materials.at(i); assert(material); if (!appendMaterialToLinkUnit(i, material, linkUnit.get(), argBlockIndex)) { throw "Failed to append material to the link unit"; } internalsInfo[i].argument_block_index = argBlockIndex; } mi::base::Handle<const mi::neuraylib::ITarget_code> targetCode( mBackend->translate_link_unit(linkUnit.get(), mContext.get())); mLogger->flushContextMessages(mContext.get()); if (!targetCode) { throw "No target code"; } ptxSrc = targetCode->get_code(); return targetCode; } bool MdlPtxCodeGen::appendMaterialToLinkUnit(uint32_t idx, const mi::neuraylib::ICompiled_material* compiledMaterial, mi::neuraylib::ILink_unit* linkUnit, mi::Size& argBlockIndex) { std::string idxStr = std::to_string(idx); auto scatteringFuncName = std::string("mdlcode"); auto emissionFuncName = std::string(EMISSION_FUNC_NAME) + "_" + idxStr; auto emissionIntensityFuncName = std::string(EMISSION_INTENSITY_FUNC_NAME) + "_" + idxStr; // Here we need to detect if current material for hair, if so, replace name in function description mi::base::Handle<mi::neuraylib::IExpression const> hairExpr(compiledMaterial->lookup_sub_expression("hair")); bool isHair = false; if (hairExpr != nullptr) { if (hairExpr->get_kind() != mi::neuraylib::IExpression::EK_CONSTANT) { isHair = true; } } std::vector<mi::neuraylib::Target_function_description> genFunctions; genFunctions.push_back(mi::neuraylib::Target_function_description( isHair ? "hair" : "surface.scattering", scatteringFuncName.c_str())); genFunctions.push_back( mi::neuraylib::Target_function_description("surface.emission.emission", emissionFuncName.c_str())); genFunctions.push_back( mi::neuraylib::Target_function_description("surface.emission.intensity", emissionIntensityFuncName.c_str())); mi::Sint32 result = linkUnit->add_material(compiledMaterial, genFunctions.data(), genFunctions.size(), mContext.get()); mLogger->flushContextMessages(mContext.get()); if (result == 0) { argBlockIndex = genFunctions[0].argument_block_index; } return result == 0; } bool MdlPtxCodeGen::setOptionBinary(const char* name, const char* data, size_t size) { if (mBackend->set_option_binary(name, data, size) != 0) { return false; } // limit functions for which PTX code is generated to the entry functions if (mBackend->set_option("visible_functions", "__closesthit__radiance") != 0) { STRELKA_ERROR("Setting PTX option visible_functions failed"); return false; } return true; } } // namespace oka
6,873
C++
35.178947
140
0.657064
arhix52/Strelka/src/materialmanager/mtlxMdlCodeGen.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "mtlxMdlCodeGen.h" #include <MaterialXCore/Definition.h> #include <MaterialXCore/Document.h> #include <MaterialXCore/Library.h> #include <MaterialXCore/Material.h> #include <MaterialXFormat/File.h> #include <MaterialXFormat/Util.h> #include <MaterialXGenMdl/MdlShaderGenerator.h> #include <MaterialXGenShader/DefaultColorManagementSystem.h> #include <MaterialXGenShader/GenContext.h> #include <MaterialXGenShader/GenOptions.h> #include <MaterialXGenShader/Library.h> #include <MaterialXGenShader/Shader.h> #include <MaterialXGenShader/Util.h> #include <unordered_set> #include <log.h> namespace mx = MaterialX; namespace oka { class MdlStringResolver; using MdlStringResolverPtr = std::shared_ptr<MdlStringResolver>; // Original source from https://github.com/NVIDIA/MDL-SDK/blob/190249748ddfe75b133b9da9028cc6272928c1b5/examples/mdl_sdk/dxr/mdl_d3d12/materialx/mdl_generator.cpp#L53 class MdlStringResolver : public mx::StringResolver { public: /// Create a new string resolver. static MdlStringResolverPtr create() { return MdlStringResolverPtr(new MdlStringResolver()); } ~MdlStringResolver() = default; void initialize(mx::DocumentPtr document, mi::neuraylib::IMdl_configuration* config) { // remove duplicates and keep order by using a set auto less = [](const mx::FilePath& lhs, const mx::FilePath& rhs) { return lhs.asString() < rhs.asString(); }; std::set<mx::FilePath, decltype(less)> mtlx_paths(less); m_mtlx_document_paths.clear(); m_mdl_search_paths.clear(); // use the source search paths as base mx::FilePath p = mx::FilePath(document->getSourceUri()).getParentPath().getNormalized(); mtlx_paths.insert(p); m_mtlx_document_paths.append(p); for (auto sp : mx::getSourceSearchPath(document)) { sp = sp.getNormalized(); if(sp.exists() && mtlx_paths.insert(sp).second) m_mtlx_document_paths.append(sp); } // add all search paths known to MDL for (size_t i = 0, n = config->get_mdl_paths_length(); i < n; i++) { mi::base::Handle<const mi::IString> sp_istring(config->get_mdl_path(i)); p = mx::FilePath(sp_istring->get_c_str()).getNormalized(); if (p.exists() && mtlx_paths.insert(p).second) m_mtlx_document_paths.append(p); // keep a list of MDL search paths for resource resolution m_mdl_search_paths.append(p); } } std::string resolve(const std::string& str, const std::string& type) const override { mx::FilePath normalizedPath = mx::FilePath(str).getNormalized(); // in case the path is absolute we need to find a proper search path to put the file in if (normalizedPath.isAbsolute()) { // find the highest priority search path that is a prefix of the resource path for (const auto& sp : m_mdl_search_paths) { if (sp.size() > normalizedPath.size()) continue; bool isParent = true; for (size_t i = 0; i < sp.size(); ++i) { if (sp[i] != normalizedPath[i]) { isParent = false; break; } } if (!isParent) continue; // found a search path that is a prefix of the resource std::string resource_path = normalizedPath.asString(mx::FilePath::FormatPosix).substr( sp.asString(mx::FilePath::FormatPosix).size()); if (resource_path[0] != '/') resource_path = "/" + resource_path; return resource_path; } } STRELKA_ERROR("MaterialX resource can not be accessed through an MDL search path. \n Dropping the resource from the Material. Resource Path: {} ", normalizedPath.asString()); // drop the resource by returning the empty string. // alternatively, the resource could be copied into an MDL search path, // maybe even only temporary. return ""; } // Get the MaterialX paths used to load the current document as well the current MDL search // paths in order to resolve resources by the MaterialX SDK. const mx::FileSearchPath& get_search_paths() const { return m_mtlx_document_paths; } private: // List of paths from which MaterialX can locate resources. // This includes the document folder and the search paths used to load the document. mx::FileSearchPath m_mtlx_document_paths; // List of MDL search paths from which we can locate resources. // This is only a subset of the MaterialX document paths and needs to be extended by using the // `--mdl_path` option when starting the application if needed. mx::FileSearchPath m_mdl_search_paths; }; MtlxMdlCodeGen::MtlxMdlCodeGen(const char* mtlxlibPath, MdlRuntime* mdlRuntime) : mMtlxlibPath(mtlxlibPath), mMdlRuntime(mdlRuntime) { // Init shadergen. mShaderGen = mx::MdlShaderGenerator::create(); std::string target = mShaderGen->getTarget(); // MaterialX libs. mStdLib = mx::createDocument(); mx::FilePathVec libFolders; mx::loadLibraries(libFolders, mMtlxlibPath, mStdLib); // Color management. mx::DefaultColorManagementSystemPtr colorSystem = mx::DefaultColorManagementSystem::create(target); colorSystem->loadLibrary(mStdLib); mShaderGen->setColorManagementSystem(colorSystem); // Unit management. mx::UnitSystemPtr unitSystem = mx::UnitSystem::create(target); unitSystem->loadLibrary(mStdLib); mx::UnitConverterRegistryPtr unitRegistry = mx::UnitConverterRegistry::create(); mx::UnitTypeDefPtr distanceTypeDef = mStdLib->getUnitTypeDef("distance"); unitRegistry->addUnitConverter(distanceTypeDef, mx::LinearUnitConverter::create(distanceTypeDef)); mx::UnitTypeDefPtr angleTypeDef = mStdLib->getUnitTypeDef("angle"); unitRegistry->addUnitConverter(angleTypeDef, mx::LinearUnitConverter::create(angleTypeDef)); unitSystem->setUnitConverterRegistry(unitRegistry); mShaderGen->setUnitSystem(unitSystem); } mx::TypedElementPtr _FindSurfaceShaderElement(mx::DocumentPtr doc) { // Find renderable element. std::vector<mx::TypedElementPtr> renderableElements; mx::findRenderableElements(doc, renderableElements); if (renderableElements.size() != 1) { return nullptr; } // Extract surface shader node. mx::TypedElementPtr renderableElement = renderableElements.at(0); mx::NodePtr node = renderableElement->asA<mx::Node>(); if (node && node->getType() == mx::MATERIAL_TYPE_STRING) { auto shaderNodes = mx::getShaderNodes(node, mx::SURFACE_SHADER_TYPE_STRING); if (!shaderNodes.empty()) { renderableElement = *shaderNodes.begin(); } } mx::ElementPtr surfaceElement = doc->getDescendant(renderableElement->getNamePath()); if (!surfaceElement) { return nullptr; } return surfaceElement->asA<mx::TypedElement>(); } bool MtlxMdlCodeGen::translate(const char* mtlxSrc, std::string& mdlSrc, std::string& subIdentifier) { // Don't cache the context because it is thread-local. mx::GenContext context(mShaderGen); context.registerSourceCodeSearchPath(mMtlxlibPath); mx::GenOptions& contextOptions = context.getOptions(); contextOptions.targetDistanceUnit = "meter"; mx::ShaderPtr shader = nullptr; try { mx::DocumentPtr doc = mx::createDocument(); doc->importLibrary(mStdLib); mx::readFromXmlString(doc, mtlxSrc); // originally from string auto custom_resolver = MdlStringResolver::create(); custom_resolver->initialize(doc, mMdlRuntime->getConfig().get()); mx::flattenFilenames(doc, custom_resolver->get_search_paths(), custom_resolver); mx::TypedElementPtr element = _FindSurfaceShaderElement(doc); if (!element) { return false; } subIdentifier = element->getName(); shader = mShaderGen->generate(subIdentifier, element, context); } catch (const std::exception& ex) { STRELKA_ERROR("Exception generating MDL code: {}", ex.what()); } if (!shader) { return false; } mx::ShaderStage pixelStage = shader->getStage(mx::Stage::PIXEL); mdlSrc = pixelStage.getSourceCode(); return true; } } // namespace oka
9,457
C++
35.517374
182
0.64936
arhix52/Strelka/src/materialmanager/mdlRuntime.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "mdlRuntime.h" #include <mi/mdl_sdk.h> #include <vector> namespace oka { MdlRuntime::MdlRuntime() { } MdlRuntime::~MdlRuntime() { if (mTransaction) { mTransaction->commit(); } } bool MdlRuntime::init(const char* paths[], uint32_t numPaths, const char* neurayPath, const char* imagePluginPath) { mLoader = std::make_unique<MdlNeurayLoader>(); if (!mLoader->init(neurayPath, imagePluginPath)) { return false; } mi::base::Handle<mi::neuraylib::INeuray> neuray(mLoader->getNeuray()); mConfig = neuray->get_api_component<mi::neuraylib::IMdl_configuration>(); mi::base::Handle<mi::neuraylib::ILogging_configuration> logging_conf( neuray->get_api_component<mi::neuraylib::ILogging_configuration>()); mLogger = mi::base::Handle<MdlLogger>(new MdlLogger()); logging_conf->set_receiving_logger(mLogger.get()); for (uint32_t i = 0; i < numPaths; i++) { if (mConfig->add_mdl_path(paths[i]) != 0 || mConfig->add_resource_path(paths[i]) != 0) { mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "MDL file path not found, translation not possible"); return false; } } mDatabase = mi::base::Handle<mi::neuraylib::IDatabase>(neuray->get_api_component<mi::neuraylib::IDatabase>()); mi::base::Handle<mi::neuraylib::IScope> scope(mDatabase->get_global_scope()); mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(scope->create_transaction()); mFactory = mi::base::Handle<mi::neuraylib::IMdl_factory>(neuray->get_api_component<mi::neuraylib::IMdl_factory>()); mImpExpApi = mi::base::Handle<mi::neuraylib::IMdl_impexp_api>(neuray->get_api_component<mi::neuraylib::IMdl_impexp_api>()); mBackendApi = mi::base::Handle<mi::neuraylib::IMdl_backend_api>(neuray->get_api_component<mi::neuraylib::IMdl_backend_api>()); return true; } mi::base::Handle<mi::neuraylib::IMdl_configuration> MdlRuntime::getConfig() { return mConfig; } mi::base::Handle<mi::neuraylib::INeuray> MdlRuntime::getNeuray() { return mLoader->getNeuray(); } mi::base::Handle<MdlLogger> MdlRuntime::getLogger() { return mLogger; } mi::base::Handle<mi::neuraylib::IDatabase> MdlRuntime::getDatabase() { return mDatabase; } mi::base::Handle<mi::neuraylib::ITransaction> MdlRuntime::getTransaction() { return mTransaction; } mi::base::Handle<mi::neuraylib::IMdl_factory> MdlRuntime::getFactory() { return mFactory; } mi::base::Handle<mi::neuraylib::IMdl_impexp_api> MdlRuntime::getImpExpApi() { return mImpExpApi; } mi::base::Handle<mi::neuraylib::IMdl_backend_api> MdlRuntime::getBackendApi() { return mBackendApi; } } // namespace oka
3,511
C++
30.639639
130
0.668755
arhix52/Strelka/src/materialmanager/mdlLogger.cpp
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #include "mdlLogger.h" #include <log.h> namespace oka { const char* _miMessageSeverityToCStr(mi::base::Message_severity severity) { switch (severity) { case mi::base::MESSAGE_SEVERITY_FATAL: return "fatal"; case mi::base::MESSAGE_SEVERITY_ERROR: return "error"; case mi::base::MESSAGE_SEVERITY_WARNING: return "warning"; case mi::base::MESSAGE_SEVERITY_INFO: return "info"; case mi::base::MESSAGE_SEVERITY_VERBOSE: return "verbose"; case mi::base::MESSAGE_SEVERITY_DEBUG: return "debug"; default: break; } return ""; } const char* _miMessageKindToCStr(mi::neuraylib::IMessage::Kind kind) { switch (kind) { case mi::neuraylib::IMessage::MSG_INTEGRATION: return "MDL SDK"; case mi::neuraylib::IMessage::MSG_IMP_EXP: return "Importer/Exporter"; case mi::neuraylib::IMessage::MSG_COMILER_BACKEND: return "Compiler Backend"; case mi::neuraylib::IMessage::MSG_COMILER_CORE: return "Compiler Core"; case mi::neuraylib::IMessage::MSG_COMPILER_ARCHIVE_TOOL: return "Compiler Archive Tool"; case mi::neuraylib::IMessage::MSG_COMPILER_DAG: return "Compiler DAG generator"; default: break; } return ""; } void MdlLogger::message(mi::base::Message_severity level, const char* moduleCategory, const mi::base::Message_details& details, const char* message) { #ifdef NDEBUG const mi::base::Message_severity minLogLevel = mi::base::MESSAGE_SEVERITY_WARNING; #else const mi::base::Message_severity minLogLevel = mi::base::MESSAGE_SEVERITY_VERBOSE; #endif if (level <= minLogLevel) { // const char* s_severity = _miMessageSeverityToCStr(level); // FILE* os = (level <= mi::base::MESSAGE_SEVERITY_ERROR) ? stderr : stdout; // fprintf(os, "[%s] (%s) %s\n", s_severity, moduleCategory, message); switch (level) { case mi::base::MESSAGE_SEVERITY_FATAL: STRELKA_FATAL("MDL: ({0}) {1}", moduleCategory, message); break; case mi::base::MESSAGE_SEVERITY_ERROR: STRELKA_ERROR("MDL: ({0}) {1}", moduleCategory, message); break; case mi::base::MESSAGE_SEVERITY_WARNING: STRELKA_WARNING("MDL: ({0}) {1}", moduleCategory, message); break; case mi::base::MESSAGE_SEVERITY_INFO: STRELKA_INFO("MDL: ({0}) {1}", moduleCategory, message); break; case mi::base::MESSAGE_SEVERITY_VERBOSE: STRELKA_TRACE("MDL: ({0}) {1}", moduleCategory, message); break; case mi::base::MESSAGE_SEVERITY_DEBUG: STRELKA_DEBUG("MDL: ({0}) {1}", moduleCategory, message); break; default: break; } } } void MdlLogger::message(mi::base::Message_severity level, const char* moduleCategory, const char* message) { this->message(level, moduleCategory, mi::base::Message_details{}, message); } void MdlLogger::message(mi::base::Message_severity level, const char* message) { const char* MODULE_CATEGORY = "shadergen"; this->message(level, MODULE_CATEGORY, message); } void MdlLogger::flushContextMessages(mi::neuraylib::IMdl_execution_context* context) { for (mi::Size i = 0, n = context->get_messages_count(); i < n; ++i) { mi::base::Handle<const mi::neuraylib::IMessage> message(context->get_message(i)); const char* s_msg = message->get_string(); const char* s_kind = _miMessageKindToCStr(message->get_kind()); this->message(message->get_severity(), s_kind, s_msg); } context->clear_messages(); } } // namespace oka
4,575
C++
34.2
106
0.615519
arhix52/Strelka/src/render/render.cpp
#include "render.h" #ifdef __APPLE__ # include "metal/MetalRender.h" #else # include "optix/OptixRender.h" #endif using namespace oka; Render* RenderFactory::createRender(const RenderType type) { #ifdef __APPLE__ if (type == RenderType::eMetal) { return new MetalRender(); } // unsupported return nullptr; #else if (type == RenderType::eOptiX) { return new OptiXRender(); } return nullptr; #endif }
459
C++
16.037036
58
0.627451
arhix52/Strelka/src/render/optix/RandomSampler.h
#pragma once #include <stdint.h> // source: // https://github.com/mmp/pbrt-v4/blob/5acc5e46cf4b5c3382babd6a3b93b87f54d79b0a/src/pbrt/util/float.h#L46C1-L47C1 static constexpr float FloatOneMinusEpsilon = 0x1.fffffep-1; __device__ const unsigned int primeNumbers[32] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, }; enum struct SampleDimension : uint32_t { ePixelX, ePixelY, eLightId, eLightPointX, eLightPointY, eBSDF0, eBSDF1, eBSDF2, eBSDF3, eRussianRoulette, eNUM_DIMENSIONS }; struct SamplerState { uint32_t seed; uint32_t sampleIdx; uint32_t depth; }; #define MAX_BOUNCES 128 // Based on: https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/ __device__ inline unsigned int pcg_hash(unsigned int seed) { unsigned int state = seed * 747796405u + 2891336453u; unsigned int word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u; return (word >> 22u) ^ word; } // __device__ inline unsigned hash_combine(unsigned a, unsigned b) // { // return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2)); // } __device__ __inline__ uint32_t hash_combine(uint32_t seed, uint32_t v) { return seed ^ (v + (seed << 6) + (seed >> 2)); } __device__ inline unsigned int hash_with(unsigned int seed, unsigned int hash) { // Wang hash seed = (seed ^ 61u) ^ hash; seed += seed << 3; seed ^= seed >> 4; seed *= 0x27d4eb2du; return seed; } // Generate random unsigned int in [0, 2^24) static __host__ __device__ __inline__ unsigned int lcg(unsigned int& prev) { const unsigned int LCG_A = 1664525u; const unsigned int LCG_C = 1013904223u; prev = (LCG_A * prev + LCG_C); return prev & 0x00FFFFFF; } // jenkins hash static __device__ unsigned int jenkins_hash(unsigned int a) { a = (a + 0x7ED55D16) + (a << 12); a = (a ^ 0xC761C23C) ^ (a >> 19); a = (a + 0x165667B1) + (a << 5); a = (a + 0xD3A2646C) ^ (a << 9); a = (a + 0xFD7046C5) + (a << 3); a = (a ^ 0xB55A4F09) ^ (a >> 16); return a; } __device__ __inline__ uint32_t hash(uint32_t x) { // finalizer from murmurhash3 x ^= x >> 16; x *= 0x85ebca6bu; x ^= x >> 13; x *= 0xc2b2ae35u; x ^= x >> 16; return x; } static __device__ float halton(uint32_t index, uint32_t base) { const float s = 1.0f / float(base); unsigned int i = index; float result = 0.0f; float f = s; while (i) { const unsigned int digit = i % base; result += f * float(digit); i = (i - digit) / base; f *= s; } return clamp(result, 0.0f, FloatOneMinusEpsilon); } // source https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/ // "Insert" a 0 bit after each of the 16 low bits of x __device__ __inline__ uint32_t Part1By1(uint32_t x) { x &= 0x0000ffff; // x = ---- ---- ---- ---- fedc ba98 7654 3210 x = (x ^ (x << 8)) & 0x00ff00ff; // x = ---- ---- fedc ba98 ---- ---- 7654 3210 x = (x ^ (x << 4)) & 0x0f0f0f0f; // x = ---- fedc ---- ba98 ---- 7654 ---- 3210 x = (x ^ (x << 2)) & 0x33333333; // x = --fe --dc --ba --98 --76 --54 --32 --10 x = (x ^ (x << 1)) & 0x55555555; // x = -f-e -d-c -b-a -9-8 -7-6 -5-4 -3-2 -1-0 return x; } __device__ __inline__ uint32_t EncodeMorton2(uint32_t x, uint32_t y) { return (Part1By1(y) << 1) + Part1By1(x); } static __device__ SamplerState initSampler(uint32_t pixelX, uint32_t pixelY, uint32_t linearPixelIndex, uint32_t pixelSampleIndex, uint32_t maxSampleCount, uint32_t seed) { SamplerState sampler{}; sampler.seed = seed; // sampler.sampleIdx = pixelSampleIndex + linearPixelIndex * maxSampleCount; sampler.sampleIdx = EncodeMorton2(pixelX, pixelY) * maxSampleCount + pixelSampleIndex; return sampler; } __device__ const uint32_t sb_matrix[5][32] = { 0x80000000, 0x40000000, 0x20000000, 0x10000000, 0x08000000, 0x04000000, 0x02000000, 0x01000000, 0x00800000, 0x00400000, 0x00200000, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001, 0x80000000, 0xc0000000, 0xa0000000, 0xf0000000, 0x88000000, 0xcc000000, 0xaa000000, 0xff000000, 0x80800000, 0xc0c00000, 0xa0a00000, 0xf0f00000, 0x88880000, 0xcccc0000, 0xaaaa0000, 0xffff0000, 0x80008000, 0xc000c000, 0xa000a000, 0xf000f000, 0x88008800, 0xcc00cc00, 0xaa00aa00, 0xff00ff00, 0x80808080, 0xc0c0c0c0, 0xa0a0a0a0, 0xf0f0f0f0, 0x88888888, 0xcccccccc, 0xaaaaaaaa, 0xffffffff, 0x80000000, 0xc0000000, 0x60000000, 0x90000000, 0xe8000000, 0x5c000000, 0x8e000000, 0xc5000000, 0x68800000, 0x9cc00000, 0xee600000, 0x55900000, 0x80680000, 0xc09c0000, 0x60ee0000, 0x90550000, 0xe8808000, 0x5cc0c000, 0x8e606000, 0xc5909000, 0x6868e800, 0x9c9c5c00, 0xeeee8e00, 0x5555c500, 0x8000e880, 0xc0005cc0, 0x60008e60, 0x9000c590, 0xe8006868, 0x5c009c9c, 0x8e00eeee, 0xc5005555, 0x80000000, 0xc0000000, 0x20000000, 0x50000000, 0xf8000000, 0x74000000, 0xa2000000, 0x93000000, 0xd8800000, 0x25400000, 0x59e00000, 0xe6d00000, 0x78080000, 0xb40c0000, 0x82020000, 0xc3050000, 0x208f8000, 0x51474000, 0xfbea2000, 0x75d93000, 0xa0858800, 0x914e5400, 0xdbe79e00, 0x25db6d00, 0x58800080, 0xe54000c0, 0x79e00020, 0xb6d00050, 0x800800f8, 0xc00c0074, 0x200200a2, 0x50050093, 0x80000000, 0x40000000, 0x20000000, 0xb0000000, 0xf8000000, 0xdc000000, 0x7a000000, 0x9d000000, 0x5a800000, 0x2fc00000, 0xa1600000, 0xf0b00000, 0xda880000, 0x6fc40000, 0x81620000, 0x40bb0000, 0x22878000, 0xb3c9c000, 0xfb65a000, 0xddb2d000, 0x78022800, 0x9c0b3c00, 0x5a0fb600, 0x2d0ddb00, 0xa2878080, 0xf3c9c040, 0xdb65a020, 0x6db2d0b0, 0x800228f8, 0x400b3cdc, 0x200fb67a, 0xb00ddb9d, }; __device__ __inline__ uint32_t sobol_uint(uint32_t index, uint32_t dim) { uint32_t X = 0; for (int bit = 0; bit < 32; bit++) { int mask = (index >> bit) & 1; X ^= mask * sb_matrix[dim][bit]; } return X; } __device__ __inline__ float sobol(uint32_t index, uint32_t dim) { return min(sobol_uint(index, dim) * 0x1p-32f, FloatOneMinusEpsilon); } __device__ __inline__ uint32_t laine_karras_permutation(uint32_t value, uint32_t seed) { value += seed; value ^= value * 0x6c50b47cu; value ^= value * 0xb82f1e52u; value ^= value * 0xc7afe638u; value ^= value * 0x8d22f6e6u; return value; } __device__ __inline__ uint32_t ReverseBits(uint32_t value) { #ifdef __CUDACC__ return __brev(value); #else value = (((value & 0xaaaaaaaa) >> 1) | ((value & 0x55555555) << 1)); value = (((value & 0xcccccccc) >> 2) | ((value & 0x33333333) << 2)); value = (((value & 0xf0f0f0f0) >> 4) | ((value & 0x0f0f0f0f) << 4)); value = (((value & 0xff00ff00) >> 8) | ((value & 0x00ff00ff) << 8)); return ((value >> 16) | (value << 16)); #endif } __device__ __inline__ uint32_t nested_uniform_scramble(uint32_t value, uint32_t seed) { value = ReverseBits(value); value = laine_karras_permutation(value, seed); value = ReverseBits(value); return value; } __device__ __inline__ float sobol_scramble(uint32_t index, uint32_t dim, uint32_t seed) { seed = hash(seed); index = nested_uniform_scramble(index, seed); uint32_t result = nested_uniform_scramble(sobol_uint(index, dim), hash_combine(seed, dim)); return min(result * 0x1p-32f, FloatOneMinusEpsilon); } template <SampleDimension Dim> __device__ __inline__ float random(SamplerState& state) { const uint32_t dimension = (uint32_t(Dim) + state.depth * uint32_t(SampleDimension::eNUM_DIMENSIONS)) % 5; return sobol_scramble(state.sampleIdx, dimension, state.seed + state.depth); }
7,854
C
33.603524
170
0.650751
arhix52/Strelka/src/render/optix/OptixBuffer.h
#pragma once #include "buffer.h" #include <stdint.h> #include <vector> namespace oka { class OptixBuffer : public Buffer { public: OptixBuffer(void* devicePtr, BufferFormat format, uint32_t width, uint32_t height); virtual ~OptixBuffer(); void resize(uint32_t width, uint32_t height) override; void* map() override; void unmap() override; void* getNativePtr() { return mDeviceData; } protected: void* mDeviceData = nullptr; uint32_t mDeviceIndex = 0; }; } // namespace oka
529
C
15.5625
87
0.667297
arhix52/Strelka/src/render/optix/OptixRenderParams.h
#pragma once #include <optix_types.h> #include <vector_types.h> #include <sutil/Matrix.h> #include "RandomSampler.h" #include "Lights.h" #define GEOMETRY_MASK_TRIANGLE 1 #define GEOMETRY_MASK_CURVE 2 #define GEOMETRY_MASK_LIGHT 4 #define GEOMETRY_MASK_GEOMETRY (GEOMETRY_MASK_TRIANGLE | GEOMETRY_MASK_CURVE) #define RAY_MASK_PRIMARY (GEOMETRY_MASK_GEOMETRY | GEOMETRY_MASK_LIGHT) #define RAY_MASK_SHADOW GEOMETRY_MASK_GEOMETRY #define RAY_MASK_SECONDARY GEOMETRY_MASK_GEOMETRY struct Vertex { float3 position; uint32_t tangent; uint32_t normal; uint32_t uv; float pad0; float pad1; }; struct SceneData { Vertex* vb; uint32_t* ib; UniformLight* lights; uint32_t numLights; }; struct Params { uint32_t subframe_index; uint32_t samples_per_launch; uint32_t maxSampleCount; float4* image; float4* accum; float4* diffuse; uint16_t* diffuseCounter; float4* specular; uint16_t* specularCounter; uint32_t image_width; uint32_t image_height; uint32_t max_depth; uint32_t rectLightSamplingMethod; float3 exposure; float clipToView[16]; float viewToWorld[16]; OptixTraversableHandle handle; SceneData scene; bool enableAccumulation; // developers settings: uint32_t debug; float shadowRayTmin; float materialRayTmin; }; enum class EventType: uint8_t { eUndef, eAbsorb, eDiffuse, eSpecular, eLast, }; struct PerRayData { SamplerState sampler; uint32_t linearPixelIndex; uint32_t sampleIndex; uint32_t depth; // bounce float3 radiance; float3 throughput; float3 origin; float3 dir; bool inside; bool specularBounce; float lastBsdfPdf; EventType firstEventType; }; enum RayType { RAY_TYPE_RADIANCE = 0, RAY_TYPE_OCCLUSION = 1, RAY_TYPE_COUNT }; struct RayGenData { // No data needed }; struct MissData { float3 bg_color; }; struct HitGroupData { int32_t indexOffset; int32_t indexCount; int32_t vertexOffset; int32_t lightId; // only for lights. -1 for others CUdeviceptr argData; CUdeviceptr roData; CUdeviceptr resHandler; float4 world_to_object[4] = {}; float4 object_to_world[4] = {}; };
2,254
C
17.185484
77
0.681012
arhix52/Strelka/src/render/optix/texture_support_cuda.h
/****************************************************************************** * Copyright 2022 NVIDIA Corporation. All rights reserved. *****************************************************************************/ // examples/mdl_sdk/shared/texture_support_cuda.h // // This file contains the implementations and the vtables of the texture access functions. #ifndef TEXTURE_SUPPORT_CUDA_H #define TEXTURE_SUPPORT_CUDA_H #include <cuda.h> #include <cuda_runtime.h> #include <math.h> #include <mi/neuraylib/target_code_types.h> #define USE_SMOOTHERSTEP_FILTER #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #define M_ONE_OVER_PI 0.318309886183790671538 typedef mi::neuraylib::tct_deriv_float tct_deriv_float; typedef mi::neuraylib::tct_deriv_float2 tct_deriv_float2; typedef mi::neuraylib::tct_deriv_arr_float_2 tct_deriv_arr_float_2; typedef mi::neuraylib::tct_deriv_arr_float_3 tct_deriv_arr_float_3; typedef mi::neuraylib::tct_deriv_arr_float_4 tct_deriv_arr_float_4; typedef mi::neuraylib::Shading_state_material_with_derivs Shading_state_material_with_derivs; typedef mi::neuraylib::Shading_state_material Shading_state_material; typedef mi::neuraylib::Texture_handler_base Texture_handler_base; typedef mi::neuraylib::Tex_wrap_mode Tex_wrap_mode; typedef mi::neuraylib::Mbsdf_part Mbsdf_part; // Custom structure representing an MDL texture, containing filtered and unfiltered CUDA texture // objects and the size of the texture. struct Texture { explicit Texture() : filtered_object(0) , unfiltered_object(0) , size(make_uint3(0, 0, 0)) , inv_size(make_float3(0.0f, 0.0f, 0.0f)) {} explicit Texture( cudaTextureObject_t filtered_object, cudaTextureObject_t unfiltered_object, uint3 size) : filtered_object(filtered_object) , unfiltered_object(unfiltered_object) , size(size) , inv_size(make_float3(1.0f / size.x, 1.0f / size.y, 1.0f / size.z)) {} cudaTextureObject_t filtered_object; // uses filter mode cudaFilterModeLinear cudaTextureObject_t unfiltered_object; // uses filter mode cudaFilterModePoint uint3 size; // size of the texture, needed for texel access float3 inv_size; // the inverse values of the size of the texture }; // Custom structure representing an MDL BSDF measurement. struct Mbsdf { unsigned has_data[2]; // true if there is a measurement for this part cudaTextureObject_t eval_data[2]; // uses filter mode cudaFilterModeLinear float max_albedo[2]; // max albedo used to limit the multiplier float* sample_data[2]; // CDFs for sampling a BSDF measurement float* albedo_data[2]; // max albedo for each theta (isotropic) uint2 angular_resolution[2]; // size of the dataset, needed for texel access float2 inv_angular_resolution[2]; // the inverse values of the size of the dataset unsigned num_channels[2]; // number of color channels (1 or 3) }; // Structure representing a Light Profile struct Lightprofile { explicit Lightprofile() : angular_resolution(make_uint2(0, 0)) , inv_angular_resolution(make_float2(0.0f, 0.0f)) , theta_phi_start(make_float2(0.0f, 0.0f)) , theta_phi_delta(make_float2(0.0f, 0.0f)) , theta_phi_inv_delta(make_float2(0.0f, 0.0f)) , candela_multiplier(0.0f) , total_power(0.0f) , eval_data(0) { } uint2 angular_resolution; // angular resolution of the grid float2 inv_angular_resolution; // inverse angular resolution of the grid float2 theta_phi_start; // start of the grid float2 theta_phi_delta; // angular step size float2 theta_phi_inv_delta; // inverse step size float candela_multiplier; // factor to rescale the normalized data float total_power; cudaTextureObject_t eval_data; // normalized data sampled on grid float* cdf_data; // CDFs for sampling a light profile }; // The texture handler structure required by the MDL SDK with custom additional fields. struct Texture_handler : Texture_handler_base { // additional data for the texture access functions can be provided here size_t num_textures; // the number of textures used by the material // (without the invalid texture) Texture const *textures; // the textures used by the material // (without the invalid texture) size_t num_mbsdfs; // the number of mbsdfs used by the material // (without the invalid mbsdf) Mbsdf const *mbsdfs; // the mbsdfs used by the material // (without the invalid mbsdf) size_t num_lightprofiles; // number of elements in the lightprofiles field // (without the invalid light profile) Lightprofile const *lightprofiles; // a device pointer to a list of mbsdfs objects, if used // (without the invalid light profile) }; // The texture handler structure required by the MDL SDK with custom additional fields. struct Texture_handler_deriv : mi::neuraylib::Texture_handler_deriv_base { // additional data for the texture access functions can be provided here size_t num_textures; // the number of textures used by the material // (without the invalid texture) Texture const *textures; // the textures used by the material // (without the invalid texture) size_t num_mbsdfs; // the number of mbsdfs used by the material // (without the invalid texture) Mbsdf const *mbsdfs; // the mbsdfs used by the material // (without the invalid texture) size_t num_lightprofiles; // number of elements in the lightprofiles field // (without the invalid light profile) Lightprofile const *lightprofiles; // a device pointer to a list of mbsdfs objects, if used // (without the invalid light profile) }; #if defined(__CUDACC__) // Stores a float4 in a float[4] array. __device__ inline void store_result4(float res[4], const float4 &v) { res[0] = v.x; res[1] = v.y; res[2] = v.z; res[3] = v.w; } // Stores a float in all elements of a float[4] array. __device__ inline void store_result4(float res[4], float s) { res[0] = res[1] = res[2] = res[3] = s; } // Stores the given float values in a float[4] array. __device__ inline void store_result4( float res[4], float v0, float v1, float v2, float v3) { res[0] = v0; res[1] = v1; res[2] = v2; res[3] = v3; } // Stores a float3 in a float[3] array. __device__ inline void store_result3(float res[3], float3 const&v) { res[0] = v.x; res[1] = v.y; res[2] = v.z; } // Stores a float4 in a float[3] array, ignoring v.w. __device__ inline void store_result3(float res[3], const float4 &v) { res[0] = v.x; res[1] = v.y; res[2] = v.z; } // Stores a float in all elements of a float[3] array. __device__ inline void store_result3(float res[3], float s) { res[0] = res[1] = res[2] = s; } // Stores the given float values in a float[3] array. __device__ inline void store_result3(float res[3], float v0, float v1, float v2) { res[0] = v0; res[1] = v1; res[2] = v2; } // Stores the luminance if a given float[3] in a float. __device__ inline void store_result1(float* res, float3 const& v) { // store luminance *res = 0.212671 * v.x + 0.715160 * v.y + 0.072169 * v.z; } // Stores the luminance if a given float[3] in a float. __device__ inline void store_result1(float* res, float v0, float v1, float v2) { // store luminance *res = 0.212671 * v0 + 0.715160 * v1 + 0.072169 * v2; } // Stores a given float in a float __device__ inline void store_result1(float* res, float s) { *res = s; } // ------------------------------------------------------------------------------------------------ // Textures // ------------------------------------------------------------------------------------------------ // Applies wrapping and cropping to the given coordinate. // Note: This macro returns if wrap mode is clip and the coordinate is out of range. #define WRAP_AND_CROP_OR_RETURN_BLACK(val, inv_dim, wrap_mode, crop_vals, store_res_func) \ do { \ if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_REPEAT && \ (crop_vals)[0] == 0.0f && (crop_vals)[1] == 1.0f ) { \ /* Do nothing, use texture sampler default behavior */ \ } \ else \ { \ if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_REPEAT ) \ val = val - floorf(val); \ else { \ if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_CLIP && (val < 0.0f || val >= 1.0f) ) { \ store_res_func(result, 0.0f); \ return; \ } \ else if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_MIRRORED_REPEAT ) { \ float floored_val = floorf(val); \ if ( (int(floored_val) & 1) != 0 ) \ val = 1.0f - (val - floored_val); \ else \ val = val - floored_val; \ } \ float inv_hdim = 0.5f * (inv_dim); \ val = fminf(fmaxf(val, inv_hdim), 1.f - inv_hdim); \ } \ val = val * ((crop_vals)[1] - (crop_vals)[0]) + (crop_vals)[0]; \ } \ } while ( 0 ) #ifdef USE_SMOOTHERSTEP_FILTER // Modify texture coordinates to get better texture filtering, // see http://www.iquilezles.org/www/articles/texture/texture.htm #define APPLY_SMOOTHERSTEP_FILTER() \ do { \ u = u * tex.size.x + 0.5f; \ v = v * tex.size.y + 0.5f; \ \ float u_i = floorf(u), v_i = floorf(v); \ float u_f = u - u_i; \ float v_f = v - v_i; \ u_f = u_f * u_f * u_f * (u_f * (u_f * 6.f - 15.f) + 10.f); \ v_f = v_f * v_f * v_f * (v_f * (v_f * 6.f - 15.f) + 10.f); \ u = u_i + u_f; \ v = v_i + v_f; \ \ u = (u - 0.5f) * tex.inv_size.x; \ v = (v - 0.5f) * tex.inv_size.y; \ } while ( 0 ) #else #define APPLY_SMOOTHERSTEP_FILTER() #endif // Implementation of tex::lookup_float4() for a texture_2d texture. extern "C" __device__ void tex_lookup_float4_2d( float result[4], Texture_handler_base const *self_base, unsigned texture_idx, float const coord[2], Tex_wrap_mode const wrap_u, Tex_wrap_mode const wrap_v, float const crop_u[2], float const crop_v[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result4(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; float u = coord[0], v = coord[1]; WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result4); WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result4); APPLY_SMOOTHERSTEP_FILTER(); store_result4(result, tex2D<float4>(tex.filtered_object, u, v)); } // Implementation of tex::lookup_float4() for a texture_2d texture. extern "C" __device__ void tex_lookup_deriv_float4_2d( float result[4], Texture_handler_base const *self_base, unsigned texture_idx, tct_deriv_float2 const *coord, Tex_wrap_mode const wrap_u, Tex_wrap_mode const wrap_v, float const crop_u[2], float const crop_v[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result4(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; float u = coord->val.x, v = coord->val.y; WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result4); WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result4); APPLY_SMOOTHERSTEP_FILTER(); store_result4(result, tex2DGrad<float4>(tex.filtered_object, u, v, coord->dx, coord->dy)); } // Implementation of tex::lookup_float3() for a texture_2d texture. extern "C" __device__ void tex_lookup_float3_2d( float result[3], Texture_handler_base const *self_base, unsigned texture_idx, float const coord[2], Tex_wrap_mode const wrap_u, Tex_wrap_mode const wrap_v, float const crop_u[2], float const crop_v[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result3(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; float u = coord[0], v = coord[1]; WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result3); WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result3); APPLY_SMOOTHERSTEP_FILTER(); store_result3(result, tex2D<float4>(tex.filtered_object, u, v)); } // Implementation of tex::lookup_float3() for a texture_2d texture. extern "C" __device__ void tex_lookup_deriv_float3_2d( float result[3], Texture_handler_base const *self_base, unsigned texture_idx, tct_deriv_float2 const *coord, Tex_wrap_mode const wrap_u, Tex_wrap_mode const wrap_v, float const crop_u[2], float const crop_v[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result3(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; float u = coord->val.x, v = coord->val.y; WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result3); WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result3); APPLY_SMOOTHERSTEP_FILTER(); store_result3(result, tex2DGrad<float4>(tex.filtered_object, u, v, coord->dx, coord->dy)); } // Implementation of tex::texel_float4() for a texture_2d texture. // Note: uvtile and/or animated textures are not supported extern "C" __device__ void tex_texel_float4_2d( float result[4], Texture_handler_base const *self_base, unsigned texture_idx, int const coord[2], int const /*uv_tile*/[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result4(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; store_result4(result, tex2D<float4>( tex.unfiltered_object, float(coord[0]) * tex.inv_size.x, float(coord[1]) * tex.inv_size.y)); } // Implementation of tex::lookup_float4() for a texture_3d texture. extern "C" __device__ void tex_lookup_float4_3d( float result[4], Texture_handler_base const *self_base, unsigned texture_idx, float const coord[3], Tex_wrap_mode wrap_u, Tex_wrap_mode wrap_v, Tex_wrap_mode wrap_w, float const crop_u[2], float const crop_v[2], float const crop_w[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result4(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; float u = coord[0], v = coord[1], w = coord[2]; WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result4); WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result4); WRAP_AND_CROP_OR_RETURN_BLACK(w, tex.inv_size.z, wrap_w, crop_w, store_result4); store_result4(result, tex3D<float4>(tex.filtered_object, u, v, w)); } // Implementation of tex::lookup_float3() for a texture_3d texture. extern "C" __device__ void tex_lookup_float3_3d( float result[3], Texture_handler_base const *self_base, unsigned texture_idx, float const coord[3], Tex_wrap_mode wrap_u, Tex_wrap_mode wrap_v, Tex_wrap_mode wrap_w, float const crop_u[2], float const crop_v[2], float const crop_w[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result3(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; float u = coord[0], v = coord[1], w = coord[2]; WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result3); WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result3); WRAP_AND_CROP_OR_RETURN_BLACK(w, tex.inv_size.z, wrap_w, crop_w, store_result3); store_result3(result, tex3D<float4>(tex.filtered_object, u, v, w)); } // Implementation of tex::texel_float4() for a texture_3d texture. extern "C" __device__ void tex_texel_float4_3d( float result[4], Texture_handler_base const *self_base, unsigned texture_idx, const int coord[3], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result4(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; store_result4(result, tex3D<float4>( tex.unfiltered_object, float(coord[0]) * tex.inv_size.x, float(coord[1]) * tex.inv_size.y, float(coord[2]) * tex.inv_size.z)); } // Implementation of tex::lookup_float4() for a texture_cube texture. extern "C" __device__ void tex_lookup_float4_cube( float result[4], Texture_handler_base const *self_base, unsigned texture_idx, float const coord[3]) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result4(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; store_result4(result, texCubemap<float4>(tex.filtered_object, coord[0], coord[1], coord[2])); } // Implementation of tex::lookup_float3() for a texture_cube texture. extern "C" __device__ void tex_lookup_float3_cube( float result[3], Texture_handler_base const *self_base, unsigned texture_idx, float const coord[3]) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero store_result3(result, 0.0f); return; } Texture const &tex = self->textures[texture_idx - 1]; store_result3(result, texCubemap<float4>(tex.filtered_object, coord[0], coord[1], coord[2])); } // Implementation of resolution_2d function needed by generated code. // Note: uvtile and/or animated textures are not supported extern "C" __device__ void tex_resolution_2d( int result[2], Texture_handler_base const *self_base, unsigned texture_idx, int const /*uv_tile*/[2], float /*frame*/) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) { // invalid texture returns zero result[0] = 0; result[1] = 0; return; } Texture const &tex = self->textures[texture_idx - 1]; result[0] = tex.size.x; result[1] = tex.size.y; } // Implementation of resolution_3d function needed by generated code. extern "C" __device__ void tex_resolution_3d( int result[3], Texture_handler_base const *self_base, unsigned texture_idx, float /*frame*/) { Texture_handler const* self = static_cast<Texture_handler const*>(self_base); if (texture_idx == 0 || texture_idx - 1 >= self->num_textures) { // invalid texture returns zero result[0] = 0; result[1] = 0; result[2] = 0; } Texture const& tex = self->textures[texture_idx - 1]; result[0] = tex.size.x; result[1] = tex.size.y; result[2] = tex.size.z; } // Implementation of texture_isvalid(). extern "C" __device__ bool tex_texture_isvalid( Texture_handler_base const *self_base, unsigned texture_idx) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); return texture_idx != 0 && texture_idx - 1 < self->num_textures; } // Implementation of frame function needed by generated code. extern "C" __device__ void tex_frame( int result[2], Texture_handler_base const *self_base, unsigned texture_idx) { Texture_handler const* self = static_cast<Texture_handler const*>(self_base); if (texture_idx == 0 || texture_idx - 1 >= self->num_textures) { // invalid texture returns zero result[0] = 0; result[1] = 0; } // Texture const& tex = self->textures[texture_idx - 1]; result[0] = 0; result[1] = 0; } // ------------------------------------------------------------------------------------------------ // Light Profiles // ------------------------------------------------------------------------------------------------ // Implementation of light_profile_power() for a light profile. extern "C" __device__ float df_light_profile_power( Texture_handler_base const *self_base, unsigned light_profile_idx) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles) return 0.0f; // invalid light profile returns zero const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1]; return lp.total_power; } // Implementation of light_profile_maximum() for a light profile. extern "C" __device__ float df_light_profile_maximum( Texture_handler_base const *self_base, unsigned light_profile_idx) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles) return 0.0f; // invalid light profile returns zero const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1]; return lp.candela_multiplier; } // Implementation of light_profile_isvalid() for a light profile. extern "C" __device__ bool df_light_profile_isvalid( Texture_handler_base const *self_base, unsigned light_profile_idx) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); return light_profile_idx != 0 && light_profile_idx - 1 < self->num_lightprofiles; } // binary search through CDF __device__ inline unsigned sample_cdf( const float* cdf, unsigned cdf_size, float xi) { unsigned li = 0; unsigned ri = cdf_size - 1; unsigned m = (li + ri) / 2; while (ri > li) { if (xi < cdf[m]) ri = m; else li = m + 1; m = (li + ri) / 2; } return m; } // Implementation of df::light_profile_evaluate() for a light profile. extern "C" __device__ float df_light_profile_evaluate( Texture_handler_base const *self_base, unsigned light_profile_idx, float const theta_phi[2]) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles) return 0.0f; // invalid light profile returns zero const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1]; // map theta to 0..1 range float u = (theta_phi[0] - lp.theta_phi_start.x) * lp.theta_phi_inv_delta.x * lp.inv_angular_resolution.x; // converting input phi from -pi..pi to 0..2pi float phi = (theta_phi[1] > 0.0f) ? theta_phi[1] : (float(2.0 * M_PI) + theta_phi[1]); // floorf wraps phi range into 0..2pi phi = phi - lp.theta_phi_start.y - floorf((phi - lp.theta_phi_start.y) * float(0.5 / M_PI)) * float(2.0 * M_PI); // (phi < 0.0f) is no problem, this is handle by the (black) border // since it implies lp.theta_phi_start.y > 0 (and we really have "no data" below that) float v = phi * lp.theta_phi_inv_delta.y * lp.inv_angular_resolution.y; // half pixel offset // see https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#linear-filtering u += 0.5f * lp.inv_angular_resolution.x; v += 0.5f * lp.inv_angular_resolution.y; // wrap_mode: border black would be an alternative (but it produces artifacts at low res) if (u < 0.0f || u > 1.0f || v < 0.0f || v > 1.0f) return 0.0f; return tex2D<float>(lp.eval_data, u, v) * lp.candela_multiplier; } // Implementation of df::light_profile_sample() for a light profile. extern "C" __device__ void df_light_profile_sample( float result[3], // output: theta, phi, pdf Texture_handler_base const *self_base, unsigned light_profile_idx, float const xi[3]) // uniform random values { result[0] = -1.0f; // negative theta means no emission result[1] = -1.0f; result[2] = 0.0f; Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles) return; // invalid light profile returns zero const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1]; uint2 res = lp.angular_resolution; // sample theta_out //------------------------------------------- float xi0 = xi[0]; const float* cdf_data_theta = lp.cdf_data; // CDF theta unsigned idx_theta = sample_cdf(cdf_data_theta, res.x - 1, xi0); // binary search float prob_theta = cdf_data_theta[idx_theta]; if (idx_theta > 0) { const float tmp = cdf_data_theta[idx_theta - 1]; prob_theta -= tmp; xi0 -= tmp; } xi0 /= prob_theta; // rescale for re-usage // sample phi_out //------------------------------------------- float xi1 = xi[1]; const float* cdf_data_phi = cdf_data_theta + (res.x - 1) // CDF theta block + (idx_theta * (res.y - 1)); // selected CDF for phi const unsigned idx_phi = sample_cdf(cdf_data_phi, res.y - 1, xi1); // binary search float prob_phi = cdf_data_phi[idx_phi]; if (idx_phi > 0) { const float tmp = cdf_data_phi[idx_phi - 1]; prob_phi -= tmp; xi1 -= tmp; } xi1 /= prob_phi; // rescale for re-usage // compute theta and phi //------------------------------------------- // sample uniformly within the patch (grid cell) const float2 start = lp.theta_phi_start; const float2 delta = lp.theta_phi_delta; const float cos_theta_0 = cosf(start.x + float(idx_theta) * delta.x); const float cos_theta_1 = cosf(start.x + float(idx_theta + 1u) * delta.x); // n = \int_{\theta_0}^{\theta_1} \sin{\theta} \delta \theta // = 1 / (\cos{\theta_0} - \cos{\theta_1}) // // \xi = n * \int_{\theta_0}^{\theta_1} \sin{\theta} \delta \theta // => \cos{\theta} = (1 - \xi) \cos{\theta_0} + \xi \cos{\theta_1} const float cos_theta = (1.0f - xi1) * cos_theta_0 + xi1 * cos_theta_1; result[0] = acosf(cos_theta); result[1] = start.y + (float(idx_phi) + xi0) * delta.y; // align phi if (result[1] > float(2.0 * M_PI)) result[1] -= float(2.0 * M_PI); // wrap if (result[1] > float(1.0 * M_PI)) result[1] = float(-2.0 * M_PI) + result[1]; // to [-pi, pi] // compute pdf //------------------------------------------- result[2] = prob_theta * prob_phi / (delta.y * (cos_theta_0 - cos_theta_1)); } // Implementation of df::light_profile_pdf() for a light profile. extern "C" __device__ float df_light_profile_pdf( Texture_handler_base const *self_base, unsigned light_profile_idx, float const theta_phi[2]) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles) return 0.0f; // invalid light profile returns zero const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1]; // CDF data const uint2 res = lp.angular_resolution; const float* cdf_data_theta = lp.cdf_data; // map theta to 0..1 range const float theta = theta_phi[0] - lp.theta_phi_start.x; const int idx_theta = int(theta * lp.theta_phi_inv_delta.x); // converting input phi from -pi..pi to 0..2pi float phi = (theta_phi[1] > 0.0f) ? theta_phi[1] : (float(2.0 * M_PI) + theta_phi[1]); // floorf wraps phi range into 0..2pi phi = phi - lp.theta_phi_start.y - floorf((phi - lp.theta_phi_start.y) * float(0.5 / M_PI)) * float(2.0 * M_PI); // (phi < 0.0f) is no problem, this is handle by the (black) border // since it implies lp.theta_phi_start.y > 0 (and we really have "no data" below that) const int idx_phi = int(phi * lp.theta_phi_inv_delta.y); // wrap_mode: border black would be an alternative (but it produces artifacts at low res) if (idx_theta < 0 || idx_theta > (res.x - 2) || idx_phi < 0 || idx_phi >(res.x - 2)) return 0.0f; // get probability for theta //------------------------------------------- float prob_theta = cdf_data_theta[idx_theta]; if (idx_theta > 0) { const float tmp = cdf_data_theta[idx_theta - 1]; prob_theta -= tmp; } // get probability for phi //------------------------------------------- const float* cdf_data_phi = cdf_data_theta + (res.x - 1) // CDF theta block + (idx_theta * (res.y - 1)); // selected CDF for phi float prob_phi = cdf_data_phi[idx_phi]; if (idx_phi > 0) { const float tmp = cdf_data_phi[idx_phi - 1]; prob_phi -= tmp; } // compute probability to select a position in the sphere patch const float2 start = lp.theta_phi_start; const float2 delta = lp.theta_phi_delta; const float cos_theta_0 = cos(start.x + float(idx_theta) * delta.x); const float cos_theta_1 = cos(start.x + float(idx_theta + 1u) * delta.x); return prob_theta * prob_phi / (delta.y * (cos_theta_0 - cos_theta_1)); } // ------------------------------------------------------------------------------------------------ // BSDF Measurements // ------------------------------------------------------------------------------------------------ // Implementation of bsdf_measurement_isvalid() for an MBSDF. extern "C" __device__ bool df_bsdf_measurement_isvalid( Texture_handler_base const *self_base, unsigned bsdf_measurement_index) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); return bsdf_measurement_index != 0 && bsdf_measurement_index - 1 < self->num_mbsdfs; } // Implementation of df::bsdf_measurement_resolution() function needed by generated code, // which retrieves the angular and chromatic resolution of the given MBSDF. // The returned triple consists of: number of equi-spaced steps of theta_i and theta_o, // number of equi-spaced steps of phi, and number of color channels (1 or 3). extern "C" __device__ void df_bsdf_measurement_resolution( unsigned result[3], Texture_handler_base const *self_base, unsigned bsdf_measurement_index, Mbsdf_part part) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs) { // invalid MBSDF returns zero result[0] = 0; result[1] = 0; result[2] = 0; return; } Mbsdf const &bm = self->mbsdfs[bsdf_measurement_index - 1]; const unsigned part_index = static_cast<unsigned>(part); // check for the part if (bm.has_data[part_index] == 0) { result[0] = 0; result[1] = 0; result[2] = 0; return; } // pass out the information result[0] = bm.angular_resolution[part_index].x; result[1] = bm.angular_resolution[part_index].y; result[2] = bm.num_channels[part_index]; } __device__ inline float3 bsdf_compute_uvw(const float theta_phi_in[2], const float theta_phi_out[2]) { // assuming each phi is between -pi and pi float u = theta_phi_out[1] - theta_phi_in[1]; if (u < 0.0) u += float(2.0 * M_PI); if (u > float(1.0 * M_PI)) u = float(2.0 * M_PI) - u; u *= M_ONE_OVER_PI; const float v = theta_phi_out[0] * float(2.0 / M_PI); const float w = theta_phi_in[0] * float(2.0 / M_PI); return make_float3(u, v, w); } template<typename T> __device__ inline T bsdf_measurement_lookup(const cudaTextureObject_t& eval_volume, const float theta_phi_in[2], const float theta_phi_out[2]) { // 3D volume on the GPU (phi_delta x theta_out x theta_in) const float3 uvw = bsdf_compute_uvw(theta_phi_in, theta_phi_out); return tex3D<T>(eval_volume, uvw.x, uvw.y, uvw.z); } // Implementation of df::bsdf_measurement_evaluate() for an MBSDF. extern "C" __device__ void df_bsdf_measurement_evaluate( float result[3], Texture_handler_base const *self_base, unsigned bsdf_measurement_index, float const theta_phi_in[2], float const theta_phi_out[2], Mbsdf_part part) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs) { // invalid MBSDF returns zero store_result3(result, 0.0f); return; } const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1]; const unsigned part_index = static_cast<unsigned>(part); // check for the parta if (bm.has_data[part_index] == 0) { store_result3(result, 0.0f); return; } // handle channels if (bm.num_channels[part_index] == 3) { const float4 sample = bsdf_measurement_lookup<float4>( bm.eval_data[part_index], theta_phi_in, theta_phi_out); store_result3(result, sample.x, sample.y, sample.z); } else { const float sample = bsdf_measurement_lookup<float>( bm.eval_data[part_index], theta_phi_in, theta_phi_out); store_result3(result, sample); } } // Implementation of df::bsdf_measurement_sample() for an MBSDF. extern "C" __device__ void df_bsdf_measurement_sample( float result[3], // output: theta, phi, pdf Texture_handler_base const *self_base, unsigned bsdf_measurement_index, float const theta_phi_out[2], float const xi[3], // uniform random values Mbsdf_part part) { result[0] = -1.0f; // negative theta means absorption result[1] = -1.0f; result[2] = 0.0f; Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs) return; // invalid MBSDFs returns zero const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1]; unsigned part_index = static_cast<unsigned>(part); if (bm.has_data[part_index] == 0) return; // check for the part // CDF data uint2 res = bm.angular_resolution[part_index]; const float* sample_data = bm.sample_data[part_index]; // compute the theta_in index (flipping input and output, BSDFs are symmetric) unsigned idx_theta_in = unsigned(theta_phi_out[0] * M_ONE_OVER_PI * 2.0f * float(res.x)); idx_theta_in = min(idx_theta_in, res.x - 1); // sample theta_out //------------------------------------------- float xi0 = xi[0]; const float* cdf_theta = sample_data + idx_theta_in * res.x; unsigned idx_theta_out = sample_cdf(cdf_theta, res.x, xi0); // binary search float prob_theta = cdf_theta[idx_theta_out]; if (idx_theta_out > 0) { const float tmp = cdf_theta[idx_theta_out - 1]; prob_theta -= tmp; xi0 -= tmp; } xi0 /= prob_theta; // rescale for re-usage // sample phi_out //------------------------------------------- float xi1 = xi[1]; const float* cdf_phi = sample_data + (res.x * res.x) + // CDF theta block (idx_theta_in * res.x + idx_theta_out) * res.y; // selected CDF phi // select which half-circle to choose with probability 0.5 const bool flip = (xi1 > 0.5f); if (flip) xi1 = 1.0f - xi1; xi1 *= 2.0f; unsigned idx_phi_out = sample_cdf(cdf_phi, res.y, xi1); // binary search float prob_phi = cdf_phi[idx_phi_out]; if (idx_phi_out > 0) { const float tmp = cdf_phi[idx_phi_out - 1]; prob_phi -= tmp; xi1 -= tmp; } xi1 /= prob_phi; // rescale for re-usage // compute theta and phi out //------------------------------------------- const float2 inv_res = bm.inv_angular_resolution[part_index]; const float s_theta = float(0.5 * M_PI) * inv_res.x; const float s_phi = float(1.0 * M_PI) * inv_res.y; const float cos_theta_0 = cosf(float(idx_theta_out) * s_theta); const float cos_theta_1 = cosf(float(idx_theta_out + 1u) * s_theta); const float cos_theta = cos_theta_0 * (1.0f - xi1) + cos_theta_1 * xi1; result[0] = acosf(cos_theta); result[1] = (float(idx_phi_out) + xi0) * s_phi; if (flip) result[1] = float(2.0 * M_PI) - result[1]; // phi \in [0, 2pi] // align phi result[1] += (theta_phi_out[1] > 0) ? theta_phi_out[1] : (float(2.0 * M_PI) + theta_phi_out[1]); if (result[1] > float(2.0 * M_PI)) result[1] -= float(2.0 * M_PI); if (result[1] > float(1.0 * M_PI)) result[1] = float(-2.0 * M_PI) + result[1]; // to [-pi, pi] // compute pdf //------------------------------------------- result[2] = prob_theta * prob_phi * 0.5f / (s_phi * (cos_theta_0 - cos_theta_1)); } // Implementation of df::bsdf_measurement_pdf() for an MBSDF. extern "C" __device__ float df_bsdf_measurement_pdf( Texture_handler_base const *self_base, unsigned bsdf_measurement_index, float const theta_phi_in[2], float const theta_phi_out[2], Mbsdf_part part) { Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs) return 0.0f; // invalid MBSDF returns zero const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1]; unsigned part_index = static_cast<unsigned>(part); // check for the part if (bm.has_data[part_index] == 0) return 0.0f; // CDF data and resolution const float* sample_data = bm.sample_data[part_index]; uint2 res = bm.angular_resolution[part_index]; // compute indices in the CDF data float3 uvw = bsdf_compute_uvw(theta_phi_in, theta_phi_out); // phi_delta, theta_out, theta_in unsigned idx_theta_in = unsigned(theta_phi_in[0] * M_ONE_OVER_PI * 2.0f * float(res.x)); unsigned idx_theta_out = unsigned(theta_phi_out[0] * M_ONE_OVER_PI * 2.0f * float(res.x)); unsigned idx_phi_out = unsigned(uvw.x * float(res.y)); idx_theta_in = min(idx_theta_in, res.x - 1); idx_theta_out = min(idx_theta_out, res.x - 1); idx_phi_out = min(idx_phi_out, res.y - 1); // get probability to select theta_out const float* cdf_theta = sample_data + idx_theta_in * res.x; float prob_theta = cdf_theta[idx_theta_out]; if (idx_theta_out > 0) { const float tmp = cdf_theta[idx_theta_out - 1]; prob_theta -= tmp; } // get probability to select phi_out const float* cdf_phi = sample_data + (res.x * res.x) + // CDF theta block (idx_theta_in * res.x + idx_theta_out) * res.y; // selected CDF phi float prob_phi = cdf_phi[idx_phi_out]; if (idx_phi_out > 0) { const float tmp = cdf_phi[idx_phi_out - 1]; prob_phi -= tmp; } // compute probability to select a position in the sphere patch float2 inv_res = bm.inv_angular_resolution[part_index]; const float s_theta = float(0.5 * M_PI) * inv_res.x; const float s_phi = float(1.0 * M_PI) * inv_res.y; const float cos_theta_0 = cosf(float(idx_theta_out) * s_theta); const float cos_theta_1 = cosf(float(idx_theta_out + 1u) * s_theta); return prob_theta * prob_phi * 0.5f / (s_phi * (cos_theta_0 - cos_theta_1)); } __device__ inline void df_bsdf_measurement_albedo( float result[2], // output: max (in case of color) albedo // for the selected direction ([0]) and // global ([1]) Texture_handler const *self, unsigned bsdf_measurement_index, float const theta_phi[2], Mbsdf_part part) { const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1]; const unsigned part_index = static_cast<unsigned>(part); // check for the part if (bm.has_data[part_index] == 0) return; const uint2 res = bm.angular_resolution[part_index]; unsigned idx_theta = unsigned(theta_phi[0] * float(2.0 / M_PI) * float(res.x)); idx_theta = min(idx_theta, res.x - 1u); result[0] = bm.albedo_data[part_index][idx_theta]; result[1] = bm.max_albedo[part_index]; } // Implementation of df::bsdf_measurement_albedos() for an MBSDF. extern "C" __device__ void df_bsdf_measurement_albedos( float result[4], // output: [0] albedo refl. for theta_phi // [1] max albedo refl. global // [2] albedo trans. for theta_phi // [3] max albedo trans. global Texture_handler_base const *self_base, unsigned bsdf_measurement_index, float const theta_phi[2]) { result[0] = 0.0f; result[1] = 0.0f; result[2] = 0.0f; result[3] = 0.0f; Texture_handler const *self = static_cast<Texture_handler const *>(self_base); if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs) return; // invalid MBSDF returns zero df_bsdf_measurement_albedo( &result[0], self, bsdf_measurement_index, theta_phi, mi::neuraylib::MBSDF_DATA_REFLECTION); df_bsdf_measurement_albedo( &result[2], self, bsdf_measurement_index, theta_phi, mi::neuraylib::MBSDF_DATA_TRANSMISSION); } // ------------------------------------------------------------------------------------------------ // Normal adaption (dummy functions) // // Can be enabled via backend option "use_renderer_adapt_normal". // ------------------------------------------------------------------------------------------------ #ifndef TEX_SUPPORT_NO_DUMMY_ADAPTNORMAL // Implementation of adapt_normal(). extern "C" __device__ void adapt_normal( float result[3], Texture_handler_base const *self_base, Shading_state_material *state, float const normal[3]) { // just return original normal result[0] = normal[0]; result[1] = normal[1]; result[2] = normal[2]; } #endif // TEX_SUPPORT_NO_DUMMY_ADAPTNORMAL // ------------------------------------------------------------------------------------------------ // Scene data (dummy functions) // ------------------------------------------------------------------------------------------------ #ifndef TEX_SUPPORT_NO_DUMMY_SCENEDATA // Implementation of scene_data_isvalid(). extern "C" __device__ bool scene_data_isvalid( Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id) { return false; } // Implementation of scene_data_lookup_float4(). extern "C" __device__ void scene_data_lookup_float4( float result[4], Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, float const default_value[4], bool uniform_lookup) { // just return default value result[0] = default_value[0]; result[1] = default_value[1]; result[2] = default_value[2]; result[3] = default_value[3]; } // Implementation of scene_data_lookup_float3(). extern "C" __device__ void scene_data_lookup_float3( float result[3], Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, float const default_value[3], bool uniform_lookup) { // just return default value result[0] = default_value[0]; result[1] = default_value[1]; result[2] = default_value[2]; } // Implementation of scene_data_lookup_color(). extern "C" __device__ void scene_data_lookup_color( float result[3], Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, float const default_value[3], bool uniform_lookup) { // just return default value result[0] = default_value[0]; result[1] = default_value[1]; result[2] = default_value[2]; } // Implementation of scene_data_lookup_float2(). extern "C" __device__ void scene_data_lookup_float2( float result[2], Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, float const default_value[2], bool uniform_lookup) { // just return default value result[0] = default_value[0]; result[1] = default_value[1]; } // Implementation of scene_data_lookup_float(). extern "C" __device__ float scene_data_lookup_float( Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, float const default_value, bool uniform_lookup) { // just return default value return default_value; } // Implementation of scene_data_lookup_int4(). extern "C" __device__ void scene_data_lookup_int4( int result[4], Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, int const default_value[4], bool uniform_lookup) { // just return default value result[0] = default_value[0]; result[1] = default_value[1]; result[2] = default_value[2]; result[3] = default_value[3]; } // Implementation of scene_data_lookup_int3(). extern "C" __device__ void scene_data_lookup_int3( int result[3], Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, int const default_value[3], bool uniform_lookup) { // just return default value result[0] = default_value[0]; result[1] = default_value[1]; result[2] = default_value[2]; } // Implementation of scene_data_lookup_int2(). extern "C" __device__ void scene_data_lookup_int2( int result[2], Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, int const default_value[2], bool uniform_lookup) { // just return default value result[0] = default_value[0]; result[1] = default_value[1]; } // Implementation of scene_data_lookup_int(). extern "C" __device__ int scene_data_lookup_int( Texture_handler_base const *self_base, Shading_state_material *state, unsigned scene_data_id, int default_value, bool uniform_lookup) { // just return default value return default_value; } // Implementation of scene_data_lookup_float4() with derivatives. extern "C" __device__ void scene_data_lookup_deriv_float4( tct_deriv_arr_float_4 *result, Texture_handler_base const *self_base, Shading_state_material_with_derivs *state, unsigned scene_data_id, tct_deriv_arr_float_4 const *default_value, bool uniform_lookup) { // just return default value *result = *default_value; } // Implementation of scene_data_lookup_float3() with derivatives. extern "C" __device__ void scene_data_lookup_deriv_float3( tct_deriv_arr_float_3 *result, Texture_handler_base const *self_base, Shading_state_material_with_derivs *state, unsigned scene_data_id, tct_deriv_arr_float_3 const *default_value, bool uniform_lookup) { // just return default value *result = *default_value; } // Implementation of scene_data_lookup_color() with derivatives. extern "C" __device__ void scene_data_lookup_deriv_color( tct_deriv_arr_float_3 *result, Texture_handler_base const *self_base, Shading_state_material_with_derivs *state, unsigned scene_data_id, tct_deriv_arr_float_3 const *default_value, bool uniform_lookup) { // just return default value *result = *default_value; } // Implementation of scene_data_lookup_float2() with derivatives. extern "C" __device__ void scene_data_lookup_deriv_float2( tct_deriv_arr_float_2 *result, Texture_handler_base const *self_base, Shading_state_material_with_derivs *state, unsigned scene_data_id, tct_deriv_arr_float_2 const *default_value, bool uniform_lookup) { // just return default value *result = *default_value; } // Implementation of scene_data_lookup_float() with derivatives. extern "C" __device__ void scene_data_lookup_deriv_float( tct_deriv_float *result, Texture_handler_base const *self_base, Shading_state_material_with_derivs *state, unsigned scene_data_id, tct_deriv_float const *default_value, bool uniform_lookup) { // just return default value *result = *default_value; } #endif // TEX_SUPPORT_NO_DUMMY_SCENEDATA // ------------------------------------------------------------------------------------------------ // Vtables // ------------------------------------------------------------------------------------------------ #ifndef TEX_SUPPORT_NO_VTABLES // The vtable containing all texture access handlers required by the generated code // in "vtable" mode. __device__ mi::neuraylib::Texture_handler_vtable tex_vtable = { tex_lookup_float4_2d, tex_lookup_float3_2d, tex_texel_float4_2d, tex_lookup_float4_3d, tex_lookup_float3_3d, tex_texel_float4_3d, tex_lookup_float4_cube, tex_lookup_float3_cube, tex_resolution_2d, tex_resolution_3d, tex_texture_isvalid, tex_frame, df_light_profile_power, df_light_profile_maximum, df_light_profile_isvalid, df_light_profile_evaluate, df_light_profile_sample, df_light_profile_pdf, df_bsdf_measurement_isvalid, df_bsdf_measurement_resolution, df_bsdf_measurement_evaluate, df_bsdf_measurement_sample, df_bsdf_measurement_pdf, df_bsdf_measurement_albedos, adapt_normal, scene_data_isvalid, scene_data_lookup_float, scene_data_lookup_float2, scene_data_lookup_float3, scene_data_lookup_float4, scene_data_lookup_int, scene_data_lookup_int2, scene_data_lookup_int3, scene_data_lookup_int4, scene_data_lookup_color, }; // The vtable containing all texture access handlers required by the generated code // in "vtable" mode with derivatives. __device__ mi::neuraylib::Texture_handler_deriv_vtable tex_deriv_vtable = { tex_lookup_deriv_float4_2d, tex_lookup_deriv_float3_2d, tex_texel_float4_2d, tex_lookup_float4_3d, tex_lookup_float3_3d, tex_texel_float4_3d, tex_lookup_float4_cube, tex_lookup_float3_cube, tex_resolution_2d, tex_resolution_3d, tex_texture_isvalid, tex_frame, df_light_profile_power, df_light_profile_maximum, df_light_profile_isvalid, df_light_profile_evaluate, df_light_profile_sample, df_light_profile_pdf, df_bsdf_measurement_isvalid, df_bsdf_measurement_resolution, df_bsdf_measurement_evaluate, df_bsdf_measurement_sample, df_bsdf_measurement_pdf, df_bsdf_measurement_albedos, adapt_normal, scene_data_isvalid, scene_data_lookup_float, scene_data_lookup_float2, scene_data_lookup_float3, scene_data_lookup_float4, scene_data_lookup_int, scene_data_lookup_int2, scene_data_lookup_int3, scene_data_lookup_int4, scene_data_lookup_color, scene_data_lookup_deriv_float, scene_data_lookup_deriv_float2, scene_data_lookup_deriv_float3, scene_data_lookup_deriv_float4, scene_data_lookup_deriv_color, }; #endif // TEX_SUPPORT_NO_VTABLES #endif // __CUDACC__ #endif // TEXTURE_SUPPORT_CUDA_H
60,296
C
37.602433
100
0.532191
arhix52/Strelka/src/render/optix/OptixRender.h
#pragma once #include "render.h" #include <optix.h> #include "OptixRenderParams.h" #include <iostream> #include <iomanip> #include <scene/scene.h> #include "common.h" #include "buffer.h" #include <materialmanager.h> struct Texture; namespace oka { enum RayType { RAY_TYPE_RADIANCE = 0, RAY_TYPE_OCCLUSION = 1, RAY_TYPE_COUNT }; struct PathTracerState { OptixDeviceContext context = 0; OptixTraversableHandle ias_handle; CUdeviceptr d_instances = 0; OptixTraversableHandle gas_handle = 0; // Traversable handle for triangle AS CUdeviceptr d_gas_output_buffer = 0; // Triangle AS memory CUdeviceptr d_vertices = 0; OptixModuleCompileOptions module_compile_options = {}; OptixModule ptx_module = 0; OptixPipelineCompileOptions pipeline_compile_options = {}; OptixPipeline pipeline = 0; OptixModule m_catromCurveModule = 0; OptixProgramGroup raygen_prog_group = 0; OptixProgramGroup radiance_miss_group = 0; OptixProgramGroup occlusion_miss_group = 0; OptixProgramGroup radiance_default_hit_group = 0; std::vector<OptixProgramGroup> radiance_hit_groups; OptixProgramGroup occlusion_hit_group = 0; OptixProgramGroup light_hit_group = 0; CUstream stream = 0; Params params = {}; Params prevParams = {}; CUdeviceptr d_params = 0; OptixShaderBindingTable sbt = {}; }; class OptiXRender : public Render { private: struct Mesh { OptixTraversableHandle gas_handle = 0; CUdeviceptr d_gas_output_buffer = 0; }; struct Curve { OptixTraversableHandle gas_handle = 0; CUdeviceptr d_gas_output_buffer = 0; }; struct Instance { OptixInstance instance; }; // optix material struct Material { OptixProgramGroup programGroup; CUdeviceptr d_argData = 0; size_t d_argDataSize = 0; CUdeviceptr d_roData = 0; size_t d_roSize = 0; CUdeviceptr d_textureHandler; }; struct View { oka::Camera::Matrices mCamMatrices; }; View mPrevView; PathTracerState mState; bool mEnableValidation; Mesh* createMesh(const oka::Mesh& mesh); Curve* createCurve(const oka::Curve& curve); bool compactAccel(CUdeviceptr& buffer, OptixTraversableHandle& handle, CUdeviceptr result, size_t outputSizeInBytes); std::vector<Mesh*> mOptixMeshes; std::vector<Curve*> mOptixCurves; CUdeviceptr d_vb = 0; CUdeviceptr d_ib = 0; CUdeviceptr d_lights = 0; CUdeviceptr d_points = 0; CUdeviceptr d_widths = 0; CUdeviceptr d_materialRoData = 0; CUdeviceptr d_materialArgData = 0; CUdeviceptr d_texturesHandler = 0; CUdeviceptr d_texturesData = 0; CUdeviceptr d_param = 0; void createVertexBuffer(); void createIndexBuffer(); // curve utils void createPointsBuffer(); void createWidthsBuffer(); void createLightBuffer(); Texture loadTextureFromFile(const std::string& fileName); bool createOptixMaterials(); Material& getMaterial(int id); MaterialManager mMaterialManager; std::vector<Material> mMaterials; void updatePathtracerParams(const uint32_t width, const uint32_t height); public: OptiXRender(/* args */); ~OptiXRender(); void init() override; void render(Buffer* output_buffer) override; Buffer* createBuffer(const BufferDesc& desc) override; void createContext(); void createAccelerationStructure(); void createModule(); void createProgramGroups(); void createPipeline(); void createSbt(); OptixProgramGroup createRadianceClosestHitProgramGroup(PathTracerState& state, char const* module_code, size_t module_size); }; } // namespace oka
3,873
C
22.621951
121
0.661245
arhix52/Strelka/src/render/optix/OptixBuffer.cpp
#include "OptixBuffer.h" #include <cuda.h> #include <cuda_runtime_api.h> using namespace oka; oka::OptixBuffer::OptixBuffer(void* devicePtr, BufferFormat format, uint32_t width, uint32_t height) { mDeviceData = devicePtr; mFormat = format; mWidth = width; mHeight = height; } oka::OptixBuffer::~OptixBuffer() { // TODO: if (mDeviceData) { cudaFree(mDeviceData); } } void oka::OptixBuffer::resize(uint32_t width, uint32_t height) { if (mDeviceData) { cudaFree(mDeviceData); } mWidth = width; mHeight = height; const size_t bufferSize = mWidth * mHeight * getElementSize(); cudaMalloc(reinterpret_cast<void**>(&mDeviceData), bufferSize); } void* oka::OptixBuffer::map() { const size_t bufferSize = mWidth * mHeight * getElementSize(); mHostData.resize(bufferSize); cudaMemcpy(static_cast<void*>(mHostData.data()), mDeviceData, bufferSize, cudaMemcpyDeviceToHost); return nullptr; } void oka::OptixBuffer::unmap() { }
1,014
C++
20.145833
102
0.670611
arhix52/Strelka/src/render/optix/OptixRender.cpp
#include "OptixRender.h" #include "OptixBuffer.h" #include <optix_function_table_definition.h> #include <optix_stubs.h> #include <optix_stack_size.h> #include <glm/glm.hpp> #include <glm/mat4x3.hpp> #include <glm/gtx/compatibility.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/matrix_major_storage.hpp> #include <glm/ext/matrix_relational.hpp> #define STB_IMAGE_STATIC #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <vector_types.h> #include <vector_functions.h> #include <sutil/vec_math_adv.h> #include "texture_support_cuda.h" #include <filesystem> #include <array> #include <string> #include <sstream> #include <fstream> #include <log.h> #include "postprocessing/Tonemappers.h" #include "Camera.h" static void context_log_cb(unsigned int level, const char* tag, const char* message, void* /*cbdata */) { switch (level) { case 1: STRELKA_FATAL("OptiX [{0}]: {1}", tag, message); break; case 2: STRELKA_ERROR("OptiX [{0}]: {1}", tag, message); break; case 3: STRELKA_WARNING("OptiX [{0}]: {1}", tag, message); break; case 4: STRELKA_INFO("OptiX [{0}]: {1}", tag, message); break; default: break; } } static inline void optixCheck(OptixResult res, const char* call, const char* file, unsigned int line) { if (res != OPTIX_SUCCESS) { STRELKA_ERROR("OptiX call {0} failed: {1}:{2}", call, file, line); assert(0); } } static inline void optixCheckLog(OptixResult res, const char* log, size_t sizeof_log, size_t sizeof_log_returned, const char* call, const char* file, unsigned int line) { if (res != OPTIX_SUCCESS) { STRELKA_FATAL("OptiX call {0} failed: {1}:{2} : {3}", call, file, line, log); assert(0); } } inline void cudaCheck(cudaError_t error, const char* call, const char* file, unsigned int line) { if (error != cudaSuccess) { STRELKA_FATAL("CUDA call ({0}) failed with error: {1} {2}:{3}", call, cudaGetErrorString(error), file, line); assert(0); } } inline void cudaSyncCheck(const char* file, unsigned int line) { cudaDeviceSynchronize(); cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) { STRELKA_FATAL("CUDA error on synchronize with error {0} , {1}:{2}", cudaGetErrorString(error), file, line); assert(0); } } //------------------------------------------------------------------------------ // // OptiX error-checking // //------------------------------------------------------------------------------ #define OPTIX_CHECK(call) optixCheck(call, #call, __FILE__, __LINE__) #define OPTIX_CHECK_LOG(call) optixCheckLog(call, log, sizeof(log), sizeof_log, #call, __FILE__, __LINE__) #define CUDA_CHECK(call) cudaCheck(call, #call, __FILE__, __LINE__) #define CUDA_SYNC_CHECK() cudaSyncCheck(__FILE__, __LINE__) using namespace oka; namespace fs = std::filesystem; template <typename T> struct SbtRecord { __align__(OPTIX_SBT_RECORD_ALIGNMENT) char header[OPTIX_SBT_RECORD_HEADER_SIZE]; T data; }; typedef SbtRecord<RayGenData> RayGenSbtRecord; typedef SbtRecord<MissData> MissSbtRecord; typedef SbtRecord<HitGroupData> HitGroupSbtRecord; void configureCamera(::Camera& cam, const uint32_t width, const uint32_t height) { cam.setEye({ 0.0f, 0.0f, 2.0f }); cam.setLookat({ 0.0f, 0.0f, 0.0f }); cam.setUp({ 0.0f, 1.0f, 3.0f }); cam.setFovY(45.0f); cam.setAspectRatio((float)width / (float)height); } static bool readSourceFile(std::string& str, const fs::path& filename) { // Try to open file std::ifstream file(filename.c_str(), std::ios::binary); if (file.good()) { // Found usable source file std::vector<unsigned char> buffer = std::vector<unsigned char>(std::istreambuf_iterator<char>(file), {}); str.assign(buffer.begin(), buffer.end()); return true; } return false; } OptiXRender::OptiXRender(/* args */) { } OptiXRender::~OptiXRender() { } void OptiXRender::createContext() { // Initialize CUDA CUDA_CHECK(cudaFree(0)); CUstream stream; CUDA_CHECK(cudaStreamCreate(&stream)); mState.stream = stream; OptixDeviceContext context; CUcontext cu_ctx = 0; // zero means take the current context OPTIX_CHECK(optixInit()); OptixDeviceContextOptions options = {}; options.logCallbackFunction = &context_log_cb; options.logCallbackLevel = 4; if (mEnableValidation) { options.validationMode = OPTIX_DEVICE_CONTEXT_VALIDATION_MODE_ALL; } else { options.validationMode = OPTIX_DEVICE_CONTEXT_VALIDATION_MODE_OFF; } OPTIX_CHECK(optixDeviceContextCreate(cu_ctx, &options, &context)); mState.context = context; } bool OptiXRender::compactAccel(CUdeviceptr& buffer, OptixTraversableHandle& handle, CUdeviceptr result, size_t outputSizeInBytes) { bool flag = false; size_t compacted_size; CUDA_CHECK(cudaMemcpy(&compacted_size, (void*)result, sizeof(size_t), cudaMemcpyDeviceToHost)); CUdeviceptr compactedOutputBuffer; if (compacted_size < outputSizeInBytes) { CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&compactedOutputBuffer), compacted_size)); // use handle as input and output OPTIX_CHECK(optixAccelCompact(mState.context, 0, handle, compactedOutputBuffer, compacted_size, &handle)); CUDA_CHECK(cudaFree(reinterpret_cast<void*>(buffer))); buffer = compactedOutputBuffer; flag = true; } return flag; } OptiXRender::Curve* OptiXRender::createCurve(const oka::Curve& curve) { Curve* rcurve = new Curve(); OptixAccelBuildOptions accel_options = {}; accel_options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_ALLOW_RANDOM_VERTEX_ACCESS | OPTIX_BUILD_FLAG_PREFER_FAST_TRACE; accel_options.operation = OPTIX_BUILD_OPERATION_BUILD; const uint32_t pointsCount = mScene->getCurvesPoint().size(); // total points count in points buffer const int degree = 3; // each oka::Curves could contains many curves const uint32_t numCurves = curve.mVertexCountsCount; std::vector<int> segmentIndices; uint32_t offsetInsideCurveArray = 0; for (int curveIndex = 0; curveIndex < numCurves; ++curveIndex) { const std::vector<uint32_t>& vertexCounts = mScene->getCurvesVertexCounts(); const uint32_t numControlPoints = vertexCounts[curve.mVertexCountsStart + curveIndex]; const int segmentsCount = numControlPoints - degree; for (int i = 0; i < segmentsCount; ++i) { int index = curve.mPointsStart + offsetInsideCurveArray + i; segmentIndices.push_back(index); } offsetInsideCurveArray += numControlPoints; } const size_t segmentIndicesSize = sizeof(int) * segmentIndices.size(); CUdeviceptr d_segmentIndices = 0; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_segmentIndices), segmentIndicesSize)); CUDA_CHECK(cudaMemcpy( reinterpret_cast<void*>(d_segmentIndices), segmentIndices.data(), segmentIndicesSize, cudaMemcpyHostToDevice)); // Curve build input. OptixBuildInput curve_input = {}; curve_input.type = OPTIX_BUILD_INPUT_TYPE_CURVES; switch (degree) { case 1: curve_input.curveArray.curveType = OPTIX_PRIMITIVE_TYPE_ROUND_LINEAR; break; case 2: curve_input.curveArray.curveType = OPTIX_PRIMITIVE_TYPE_ROUND_QUADRATIC_BSPLINE; break; case 3: curve_input.curveArray.curveType = OPTIX_PRIMITIVE_TYPE_ROUND_CUBIC_BSPLINE; break; } curve_input.curveArray.numPrimitives = segmentIndices.size(); curve_input.curveArray.vertexBuffers = &d_points; curve_input.curveArray.numVertices = pointsCount; curve_input.curveArray.vertexStrideInBytes = sizeof(glm::float3); curve_input.curveArray.widthBuffers = &d_widths; curve_input.curveArray.widthStrideInBytes = sizeof(float); curve_input.curveArray.normalBuffers = 0; curve_input.curveArray.normalStrideInBytes = 0; curve_input.curveArray.indexBuffer = d_segmentIndices; curve_input.curveArray.indexStrideInBytes = sizeof(int); curve_input.curveArray.flag = OPTIX_GEOMETRY_FLAG_NONE; curve_input.curveArray.primitiveIndexOffset = 0; // curve_input.curveArray.endcapFlags = OPTIX_CURVE_ENDCAP_ON; OptixAccelBufferSizes gas_buffer_sizes; OPTIX_CHECK(optixAccelComputeMemoryUsage(mState.context, &accel_options, &curve_input, 1, // Number of build inputs &gas_buffer_sizes)); CUdeviceptr d_temp_buffer_gas; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_temp_buffer_gas), gas_buffer_sizes.tempSizeInBytes)); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&rcurve->d_gas_output_buffer), gas_buffer_sizes.outputSizeInBytes)); CUdeviceptr compactedSizeBuffer; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>((&compactedSizeBuffer)), sizeof(uint64_t))); OptixAccelEmitDesc property = {}; property.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; property.result = compactedSizeBuffer; OPTIX_CHECK(optixAccelBuild(mState.context, 0, // CUDA stream &accel_options, &curve_input, 1, // num build inputs d_temp_buffer_gas, gas_buffer_sizes.tempSizeInBytes, rcurve->d_gas_output_buffer, gas_buffer_sizes.outputSizeInBytes, &rcurve->gas_handle, &property, // emitted property list 1)); // num emitted properties compactAccel(rcurve->d_gas_output_buffer, rcurve->gas_handle, property.result, gas_buffer_sizes.outputSizeInBytes); // We can now free the scratch space buffer used during build and the vertex // inputs, since they are not needed by our trivial shading method CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_temp_buffer_gas))); CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_segmentIndices))); return rcurve; } OptiXRender::Mesh* OptiXRender::createMesh(const oka::Mesh& mesh) { OptixTraversableHandle gas_handle; CUdeviceptr d_gas_output_buffer; { // Use default options for simplicity. In a real use case we would want to // enable compaction, etc OptixAccelBuildOptions accel_options = {}; accel_options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_PREFER_FAST_TRACE; accel_options.operation = OPTIX_BUILD_OPERATION_BUILD; // std::vector<oka::Scene::Vertex>& vertices = mScene->getVertices(); // std::vector<uint32_t>& indices = mScene->getIndices(); const CUdeviceptr verticesDataStart = d_vb + mesh.mVbOffset * sizeof(oka::Scene::Vertex); CUdeviceptr indicesDataStart = d_ib + mesh.mIndex * sizeof(uint32_t); // Our build input is a simple list of non-indexed triangle vertices const uint32_t triangle_input_flags[1] = { OPTIX_GEOMETRY_FLAG_NONE }; OptixBuildInput triangle_input = {}; triangle_input.type = OPTIX_BUILD_INPUT_TYPE_TRIANGLES; triangle_input.triangleArray.vertexFormat = OPTIX_VERTEX_FORMAT_FLOAT3; triangle_input.triangleArray.numVertices = mesh.mVertexCount; triangle_input.triangleArray.vertexBuffers = &verticesDataStart; triangle_input.triangleArray.vertexStrideInBytes = sizeof(oka::Scene::Vertex); triangle_input.triangleArray.indexBuffer = indicesDataStart; triangle_input.triangleArray.indexFormat = OptixIndicesFormat::OPTIX_INDICES_FORMAT_UNSIGNED_INT3; triangle_input.triangleArray.indexStrideInBytes = sizeof(uint32_t) * 3; triangle_input.triangleArray.numIndexTriplets = mesh.mCount / 3; // triangle_input.triangleArray. triangle_input.triangleArray.flags = triangle_input_flags; triangle_input.triangleArray.numSbtRecords = 1; OptixAccelBufferSizes gas_buffer_sizes; OPTIX_CHECK(optixAccelComputeMemoryUsage(mState.context, &accel_options, &triangle_input, 1, // Number of build inputs &gas_buffer_sizes)); CUdeviceptr d_temp_buffer_gas; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_temp_buffer_gas), gas_buffer_sizes.tempSizeInBytes)); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_gas_output_buffer), gas_buffer_sizes.outputSizeInBytes)); CUdeviceptr compactedSizeBuffer; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>((&compactedSizeBuffer)), sizeof(uint64_t))); OptixAccelEmitDesc property = {}; property.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; property.result = compactedSizeBuffer; OPTIX_CHECK(optixAccelBuild(mState.context, 0, // CUDA stream &accel_options, &triangle_input, 1, // num build inputs d_temp_buffer_gas, gas_buffer_sizes.tempSizeInBytes, d_gas_output_buffer, gas_buffer_sizes.outputSizeInBytes, &gas_handle, &property, // emitted property list 1 // num emitted properties )); compactAccel(d_gas_output_buffer, gas_handle, property.result, gas_buffer_sizes.outputSizeInBytes); CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_temp_buffer_gas))); CUDA_CHECK(cudaFree(reinterpret_cast<void*>(compactedSizeBuffer))); } Mesh* rmesh = new Mesh(); rmesh->d_gas_output_buffer = d_gas_output_buffer; rmesh->gas_handle = gas_handle; return rmesh; } void OptiXRender::createAccelerationStructure() { const std::vector<oka::Mesh>& meshes = mScene->getMeshes(); const std::vector<oka::Curve>& curves = mScene->getCurves(); const std::vector<oka::Instance>& instances = mScene->getInstances(); if (meshes.empty() && curves.empty()) { return; } // TODO: add proper clear and free resources mOptixMeshes.clear(); for (int i = 0; i < meshes.size(); ++i) { Mesh* m = createMesh(meshes[i]); mOptixMeshes.push_back(m); } mOptixCurves.clear(); for (int i = 0; i < curves.size(); ++i) { Curve* c = createCurve(curves[i]); mOptixCurves.push_back(c); } std::vector<OptixInstance> optixInstances; glm::mat3x4 identity = glm::identity<glm::mat3x4>(); for (int i = 0; i < instances.size(); ++i) { OptixInstance oi = {}; const oka::Instance& curr = instances[i]; if (curr.type == oka::Instance::Type::eMesh) { oi.traversableHandle = mOptixMeshes[curr.mMeshId]->gas_handle; oi.visibilityMask = GEOMETRY_MASK_TRIANGLE; } else if (curr.type == oka::Instance::Type::eCurve) { oi.traversableHandle = mOptixCurves[curr.mCurveId]->gas_handle; oi.visibilityMask = GEOMETRY_MASK_CURVE; } else if (curr.type == oka::Instance::Type::eLight) { oi.traversableHandle = mOptixMeshes[curr.mMeshId]->gas_handle; oi.visibilityMask = GEOMETRY_MASK_LIGHT; } else { assert(0); } // fill common instance data memcpy(oi.transform, glm::value_ptr(glm::float3x4(glm::rowMajor4(curr.transform))), sizeof(float) * 12); oi.sbtOffset = static_cast<unsigned int>(i * RAY_TYPE_COUNT); optixInstances.push_back(oi); } size_t instances_size_in_bytes = sizeof(OptixInstance) * optixInstances.size(); CUDA_CHECK(cudaMalloc((void**)&mState.d_instances, instances_size_in_bytes)); CUDA_CHECK( cudaMemcpy((void*)mState.d_instances, optixInstances.data(), instances_size_in_bytes, cudaMemcpyHostToDevice)); OptixBuildInput ias_instance_input = {}; ias_instance_input.type = OPTIX_BUILD_INPUT_TYPE_INSTANCES; ias_instance_input.instanceArray.instances = mState.d_instances; ias_instance_input.instanceArray.numInstances = static_cast<int>(optixInstances.size()); OptixAccelBuildOptions ias_accel_options = {}; ias_accel_options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_PREFER_FAST_TRACE; ias_accel_options.motionOptions.numKeys = 1; ias_accel_options.operation = OPTIX_BUILD_OPERATION_BUILD; OptixAccelBufferSizes ias_buffer_sizes; OPTIX_CHECK( optixAccelComputeMemoryUsage(mState.context, &ias_accel_options, &ias_instance_input, 1, &ias_buffer_sizes)); // non-compacted output CUdeviceptr d_buffer_temp_output_ias_and_compacted_size; auto roundUp = [](size_t x, size_t y) { return ((x + y - 1) / y) * y; }; size_t compactedSizeOffset = roundUp(ias_buffer_sizes.outputSizeInBytes, 8ull); CUDA_CHECK( cudaMalloc(reinterpret_cast<void**>(&d_buffer_temp_output_ias_and_compacted_size), compactedSizeOffset + 8)); CUdeviceptr d_ias_temp_buffer; // bool needIASTempBuffer = ias_buffer_sizes.tempSizeInBytes > state.temp_buffer_size; // if( needIASTempBuffer ) { CUDA_CHECK(cudaMalloc((void**)&d_ias_temp_buffer, ias_buffer_sizes.tempSizeInBytes)); } // else // { // d_ias_temp_buffer = state.d_temp_buffer; // } CUdeviceptr compactedSizeBuffer; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>((&compactedSizeBuffer)), sizeof(uint64_t))); OptixAccelEmitDesc property = {}; property.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; property.result = compactedSizeBuffer; OPTIX_CHECK(optixAccelBuild(mState.context, 0, &ias_accel_options, &ias_instance_input, 1, d_ias_temp_buffer, ias_buffer_sizes.tempSizeInBytes, d_buffer_temp_output_ias_and_compacted_size, ias_buffer_sizes.outputSizeInBytes, &mState.ias_handle, &property, 1)); compactAccel(d_buffer_temp_output_ias_and_compacted_size, mState.ias_handle, property.result, ias_buffer_sizes.outputSizeInBytes); CUDA_CHECK(cudaFree(reinterpret_cast<void*>(compactedSizeBuffer))); CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_ias_temp_buffer))); } void OptiXRender::createModule() { OptixModule module = nullptr; OptixPipelineCompileOptions pipeline_compile_options = {}; OptixModuleCompileOptions module_compile_options = {}; { if (mEnableValidation) { module_compile_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_LEVEL_0; module_compile_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL; } else { module_compile_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_DEFAULT; module_compile_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_NONE; } pipeline_compile_options.usesMotionBlur = false; pipeline_compile_options.traversableGraphFlags = OPTIX_TRAVERSABLE_GRAPH_FLAG_ALLOW_SINGLE_LEVEL_INSTANCING; pipeline_compile_options.numPayloadValues = 2; pipeline_compile_options.numAttributeValues = 2; if (mEnableValidation) // Enables debug exceptions during optix launches. This may incur // significant performance cost and should only be done during // development. pipeline_compile_options.exceptionFlags = OPTIX_EXCEPTION_FLAG_USER | OPTIX_EXCEPTION_FLAG_TRACE_DEPTH | OPTIX_EXCEPTION_FLAG_STACK_OVERFLOW; else { pipeline_compile_options.exceptionFlags = OPTIX_EXCEPTION_FLAG_NONE; } pipeline_compile_options.pipelineLaunchParamsVariableName = "params"; pipeline_compile_options.usesPrimitiveTypeFlags = OPTIX_PRIMITIVE_TYPE_FLAGS_TRIANGLE | OPTIX_PRIMITIVE_TYPE_FLAGS_ROUND_CUBIC_BSPLINE; size_t inputSize = 0; std::string optixSource; const fs::path cwdPath = fs::current_path(); const fs::path precompiledOptixPath = cwdPath / "optix/render_generated_OptixRender.cu.optixir"; readSourceFile(optixSource, precompiledOptixPath); const char* input = optixSource.c_str(); inputSize = optixSource.size(); char log[2048]; // For error reporting from OptiX creation functions size_t sizeof_log = sizeof(log); OPTIX_CHECK_LOG(optixModuleCreate(mState.context, &module_compile_options, &pipeline_compile_options, input, inputSize, log, &sizeof_log, &module)); } mState.ptx_module = module; mState.pipeline_compile_options = pipeline_compile_options; mState.module_compile_options = module_compile_options; // hair modules OptixBuiltinISOptions builtinISOptions = {}; builtinISOptions.buildFlags = OPTIX_BUILD_FLAG_NONE; // builtinISOptions.curveEndcapFlags = OPTIX_CURVE_ENDCAP_ON; builtinISOptions.builtinISModuleType = OPTIX_PRIMITIVE_TYPE_ROUND_CUBIC_BSPLINE; OPTIX_CHECK(optixBuiltinISModuleGet(mState.context, &mState.module_compile_options, &mState.pipeline_compile_options, &builtinISOptions, &mState.m_catromCurveModule)); } OptixProgramGroup OptiXRender::createRadianceClosestHitProgramGroup(PathTracerState& state, char const* module_code, size_t module_size) { char log[2048]; size_t sizeof_log = sizeof(log); OptixModule mat_module = nullptr; OPTIX_CHECK_LOG(optixModuleCreate(state.context, &state.module_compile_options, &state.pipeline_compile_options, module_code, module_size, log, &sizeof_log, &mat_module)); OptixProgramGroupOptions program_group_options = {}; OptixProgramGroupDesc hit_prog_group_desc = {}; hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; hit_prog_group_desc.hitgroup.moduleCH = mat_module; hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__radiance"; hit_prog_group_desc.hitgroup.moduleIS = mState.m_catromCurveModule; hit_prog_group_desc.hitgroup.entryFunctionNameIS = 0; // automatically supplied for built-in module sizeof_log = sizeof(log); OptixProgramGroup ch_hit_group = nullptr; OPTIX_CHECK_LOG(optixProgramGroupCreate(state.context, &hit_prog_group_desc, /*numProgramGroups=*/1, &program_group_options, log, &sizeof_log, &ch_hit_group)); return ch_hit_group; } void OptiXRender::createProgramGroups() { OptixProgramGroupOptions program_group_options = {}; // Initialize to zeros OptixProgramGroupDesc raygen_prog_group_desc = {}; // raygen_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN; raygen_prog_group_desc.raygen.module = mState.ptx_module; raygen_prog_group_desc.raygen.entryFunctionName = "__raygen__rg"; char log[2048]; // For error reporting from OptiX creation functions size_t sizeof_log = sizeof(log); OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &raygen_prog_group_desc, 1, // num program groups &program_group_options, log, &sizeof_log, &mState.raygen_prog_group)); OptixProgramGroupDesc miss_prog_group_desc = {}; miss_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS; miss_prog_group_desc.miss.module = mState.ptx_module; miss_prog_group_desc.miss.entryFunctionName = "__miss__ms"; sizeof_log = sizeof(log); OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &miss_prog_group_desc, 1, // num program groups &program_group_options, log, &sizeof_log, &mState.radiance_miss_group)); memset(&miss_prog_group_desc, 0, sizeof(OptixProgramGroupDesc)); miss_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS; miss_prog_group_desc.miss.module = nullptr; // NULL miss program for occlusion rays miss_prog_group_desc.miss.entryFunctionName = nullptr; sizeof_log = sizeof(log); OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &miss_prog_group_desc, 1, // num program groups &program_group_options, log, &sizeof_log, &mState.occlusion_miss_group)); OptixProgramGroupDesc hit_prog_group_desc = {}; hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; hit_prog_group_desc.hitgroup.moduleCH = mState.ptx_module; hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__ch"; sizeof_log = sizeof(log); OptixProgramGroup radiance_hit_group; OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &hit_prog_group_desc, 1, // num program groups &program_group_options, log, &sizeof_log, &radiance_hit_group)); mState.radiance_default_hit_group = radiance_hit_group; OptixProgramGroupDesc light_hit_prog_group_desc = {}; light_hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; light_hit_prog_group_desc.hitgroup.moduleCH = mState.ptx_module; light_hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__light"; sizeof_log = sizeof(log); OptixProgramGroup light_hit_group; OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &light_hit_prog_group_desc, 1, // num program groups &program_group_options, log, &sizeof_log, &light_hit_group)); mState.light_hit_group = light_hit_group; memset(&hit_prog_group_desc, 0, sizeof(OptixProgramGroupDesc)); hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; hit_prog_group_desc.hitgroup.moduleCH = mState.ptx_module; hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__occlusion"; hit_prog_group_desc.hitgroup.moduleIS = mState.m_catromCurveModule; hit_prog_group_desc.hitgroup.entryFunctionNameIS = 0; // automatically supplied for built-in module sizeof_log = sizeof(log); OPTIX_CHECK(optixProgramGroupCreate(mState.context, &hit_prog_group_desc, 1, // num program groups &program_group_options, log, &sizeof_log, &mState.occlusion_hit_group)); } void OptiXRender::createPipeline() { OptixPipeline pipeline = nullptr; { const uint32_t max_trace_depth = 2; std::vector<OptixProgramGroup> program_groups = {}; program_groups.push_back(mState.raygen_prog_group); program_groups.push_back(mState.radiance_miss_group); program_groups.push_back(mState.radiance_default_hit_group); program_groups.push_back(mState.occlusion_miss_group); program_groups.push_back(mState.occlusion_hit_group); program_groups.push_back(mState.light_hit_group); for (auto& m : mMaterials) { program_groups.push_back(m.programGroup); } OptixPipelineLinkOptions pipeline_link_options = {}; pipeline_link_options.maxTraceDepth = max_trace_depth; // if (mEnableValidation) // { // pipeline_link_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL; // } // else // { // pipeline_link_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_NONE; // } char log[2048]; // For error reporting from OptiX creation functions size_t sizeof_log = sizeof(log); OPTIX_CHECK_LOG(optixPipelineCreate(mState.context, &mState.pipeline_compile_options, &pipeline_link_options, program_groups.data(), program_groups.size(), log, &sizeof_log, &pipeline)); OptixStackSizes stack_sizes = {}; for (auto& prog_group : program_groups) { OPTIX_CHECK(optixUtilAccumulateStackSizes(prog_group, &stack_sizes, pipeline)); } uint32_t direct_callable_stack_size_from_traversal; uint32_t direct_callable_stack_size_from_state; uint32_t continuation_stack_size; OPTIX_CHECK(optixUtilComputeStackSizes(&stack_sizes, max_trace_depth, 0, // maxCCDepth 0, // maxDCDepth &direct_callable_stack_size_from_traversal, &direct_callable_stack_size_from_state, &continuation_stack_size)); OPTIX_CHECK(optixPipelineSetStackSize(pipeline, direct_callable_stack_size_from_traversal, direct_callable_stack_size_from_state, continuation_stack_size, 2 // maxTraversableDepth )); } mState.pipeline = pipeline; } void OptiXRender::createSbt() { OptixShaderBindingTable sbt = {}; { CUdeviceptr raygen_record; const size_t raygen_record_size = sizeof(RayGenSbtRecord); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&raygen_record), raygen_record_size)); RayGenSbtRecord rg_sbt; OPTIX_CHECK(optixSbtRecordPackHeader(mState.raygen_prog_group, &rg_sbt)); CUDA_CHECK( cudaMemcpy(reinterpret_cast<void*>(raygen_record), &rg_sbt, raygen_record_size, cudaMemcpyHostToDevice)); CUdeviceptr miss_record; const uint32_t miss_record_count = RAY_TYPE_COUNT; size_t miss_record_size = sizeof(MissSbtRecord) * miss_record_count; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&miss_record), miss_record_size)); std::vector<MissSbtRecord> missGroupDataCpu(miss_record_count); MissSbtRecord& ms_sbt = missGroupDataCpu[RAY_TYPE_RADIANCE]; // ms_sbt.data.bg_color = { 0.5f, 0.5f, 0.5f }; ms_sbt.data.bg_color = { 0.0f, 0.0f, 0.0f }; OPTIX_CHECK(optixSbtRecordPackHeader(mState.radiance_miss_group, &ms_sbt)); MissSbtRecord& ms_sbt_occlusion = missGroupDataCpu[RAY_TYPE_OCCLUSION]; ms_sbt_occlusion.data = { 0.0f, 0.0f, 0.0f }; OPTIX_CHECK(optixSbtRecordPackHeader(mState.occlusion_miss_group, &ms_sbt_occlusion)); CUDA_CHECK(cudaMemcpy( reinterpret_cast<void*>(miss_record), missGroupDataCpu.data(), miss_record_size, cudaMemcpyHostToDevice)); uint32_t hitGroupRecordCount = RAY_TYPE_COUNT; CUdeviceptr hitgroup_record = 0; size_t hitgroup_record_size = hitGroupRecordCount * sizeof(HitGroupSbtRecord); const std::vector<oka::Instance>& instances = mScene->getInstances(); std::vector<HitGroupSbtRecord> hitGroupDataCpu(hitGroupRecordCount); // default sbt record if (!instances.empty()) { const std::vector<oka::Mesh>& meshes = mScene->getMeshes(); hitGroupRecordCount = instances.size() * RAY_TYPE_COUNT; hitgroup_record_size = sizeof(HitGroupSbtRecord) * hitGroupRecordCount; hitGroupDataCpu.resize(hitGroupRecordCount); for (int i = 0; i < instances.size(); ++i) { const oka::Instance& instance = instances[i]; int hg_index = i * RAY_TYPE_COUNT + RAY_TYPE_RADIANCE; HitGroupSbtRecord& hg_sbt = hitGroupDataCpu[hg_index]; // replace unknown material on default const int materialIdx = instance.mMaterialId == -1 ? 0 : instance.mMaterialId; const Material& mat = getMaterial(materialIdx); if (instance.type == oka::Instance::Type::eLight) { hg_sbt.data.lightId = instance.mLightId; const OptixProgramGroup& lightPg = mState.light_hit_group; OPTIX_CHECK(optixSbtRecordPackHeader(lightPg, &hg_sbt)); } else { const OptixProgramGroup& hitMaterial = mat.programGroup; OPTIX_CHECK(optixSbtRecordPackHeader(hitMaterial, &hg_sbt)); } // write all needed data for instances hg_sbt.data.argData = mat.d_argData; hg_sbt.data.roData = mat.d_roData; hg_sbt.data.resHandler = mat.d_textureHandler; if (instance.type == oka::Instance::Type::eMesh) { const oka::Mesh& mesh = meshes[instance.mMeshId]; hg_sbt.data.indexCount = mesh.mCount; hg_sbt.data.indexOffset = mesh.mIndex; hg_sbt.data.vertexOffset = mesh.mVbOffset; hg_sbt.data.lightId = -1; } memcpy(hg_sbt.data.object_to_world, glm::value_ptr(glm::float4x4(glm::rowMajor4(instance.transform))), sizeof(float4) * 4); glm::mat4 world_to_object = glm::inverse(instance.transform); memcpy(hg_sbt.data.world_to_object, glm::value_ptr(glm::float4x4(glm::rowMajor4(world_to_object))), sizeof(float4) * 4); // write data for visibility ray hg_index = i * RAY_TYPE_COUNT + RAY_TYPE_OCCLUSION; HitGroupSbtRecord& hg_sbt_occlusion = hitGroupDataCpu[hg_index]; OPTIX_CHECK(optixSbtRecordPackHeader(mState.occlusion_hit_group, &hg_sbt_occlusion)); } } else { // stub record HitGroupSbtRecord& hg_sbt = hitGroupDataCpu[RAY_TYPE_RADIANCE]; OPTIX_CHECK(optixSbtRecordPackHeader(mState.radiance_default_hit_group, &hg_sbt)); HitGroupSbtRecord& hg_sbt_occlusion = hitGroupDataCpu[RAY_TYPE_OCCLUSION]; OPTIX_CHECK(optixSbtRecordPackHeader(mState.occlusion_hit_group, &hg_sbt_occlusion)); } CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&hitgroup_record), hitgroup_record_size)); CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(hitgroup_record), hitGroupDataCpu.data(), hitgroup_record_size, cudaMemcpyHostToDevice)); sbt.raygenRecord = raygen_record; sbt.missRecordBase = miss_record; sbt.missRecordStrideInBytes = sizeof(MissSbtRecord); sbt.missRecordCount = RAY_TYPE_COUNT; sbt.hitgroupRecordBase = hitgroup_record; sbt.hitgroupRecordStrideInBytes = sizeof(HitGroupSbtRecord); sbt.hitgroupRecordCount = hitGroupRecordCount; } mState.sbt = sbt; } void OptiXRender::updatePathtracerParams(const uint32_t width, const uint32_t height) { bool needRealloc = false; if (mState.params.image_width != width || mState.params.image_height != height) { // new dimensions! needRealloc = true; // reset rendering getSharedContext().mSubframeIndex = 0; } mState.params.image_width = width; mState.params.image_height = height; if (needRealloc) { getSharedContext().mSettingsManager->setAs<bool>("render/pt/isResized", true); if (mState.params.accum) { CUDA_CHECK(cudaFree((void*)mState.params.accum)); } if (mState.params.diffuse) { CUDA_CHECK(cudaFree((void*)mState.params.diffuse)); } if (mState.params.specular) { CUDA_CHECK(cudaFree((void*)mState.params.specular)); } if (mState.d_params) { CUDA_CHECK(cudaFree((void*)mState.d_params)); } CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.d_params), sizeof(Params))); const size_t frameSize = mState.params.image_width * mState.params.image_height; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.accum), frameSize * sizeof(float4))); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.diffuse), frameSize * sizeof(float4))); CUDA_CHECK(cudaMemset(mState.params.diffuse, 0, frameSize * sizeof(float4))); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.diffuseCounter), frameSize * sizeof(uint16_t))); CUDA_CHECK(cudaMemset(mState.params.diffuseCounter, 0, frameSize * sizeof(uint16_t))); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.specular), frameSize * sizeof(float4))); CUDA_CHECK(cudaMemset(mState.params.specular, 0, frameSize * sizeof(float4))); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.specularCounter), frameSize * sizeof(uint16_t))); CUDA_CHECK(cudaMemset(mState.params.specularCounter, 0, frameSize * sizeof(uint16_t))); } } void OptiXRender::render(Buffer* output) { if (getSharedContext().mFrameNumber == 0) { createOptixMaterials(); createPipeline(); createVertexBuffer(); createIndexBuffer(); // upload all curve data createPointsBuffer(); createWidthsBuffer(); createAccelerationStructure(); createSbt(); createLightBuffer(); } const uint32_t width = output->width(); const uint32_t height = output->height(); updatePathtracerParams(width, height); oka::Camera& camera = mScene->getCamera(0); camera.updateAspectRatio(width / (float)height); camera.updateViewMatrix(); View currView = {}; currView.mCamMatrices = camera.matrices; if (glm::any(glm::notEqual(currView.mCamMatrices.perspective, mPrevView.mCamMatrices.perspective)) || glm::any(glm::notEqual(currView.mCamMatrices.view, mPrevView.mCamMatrices.view))) { // need reset getSharedContext().mSubframeIndex = 0; } SettingsManager& settings = *getSharedContext().mSettingsManager; bool settingsChanged = false; static uint32_t rectLightSamplingMethodPrev = 0; const uint32_t rectLightSamplingMethod = settings.getAs<uint32_t>("render/pt/rectLightSamplingMethod"); settingsChanged = (rectLightSamplingMethodPrev != rectLightSamplingMethod); rectLightSamplingMethodPrev = rectLightSamplingMethod; static bool enableAccumulationPrev = 0; bool enableAccumulation = settings.getAs<bool>("render/pt/enableAcc"); settingsChanged |= (enableAccumulationPrev != enableAccumulation); enableAccumulationPrev = enableAccumulation; static uint32_t sspTotalPrev = 0; const uint32_t sspTotal = settings.getAs<uint32_t>("render/pt/sppTotal"); settingsChanged |= (sspTotalPrev > sspTotal); // reset only if new spp less than already accumulated sspTotalPrev = sspTotal; const float gamma = settings.getAs<float>("render/post/gamma"); const ToneMapperType tonemapperType = (ToneMapperType)settings.getAs<uint32_t>("render/pt/tonemapperType"); if (settingsChanged) { getSharedContext().mSubframeIndex = 0; } Params& params = mState.params; params.scene.vb = (Vertex*)d_vb; params.scene.ib = (uint32_t*)d_ib; params.scene.lights = (UniformLight*)d_lights; params.scene.numLights = mScene->getLights().size(); params.image = (float4*)((OptixBuffer*)output)->getNativePtr(); params.samples_per_launch = settings.getAs<uint32_t>("render/pt/spp"); params.handle = mState.ias_handle; params.max_depth = settings.getAs<uint32_t>("render/pt/depth"); params.rectLightSamplingMethod = settings.getAs<uint32_t>("render/pt/rectLightSamplingMethod"); params.enableAccumulation = settings.getAs<bool>("render/pt/enableAcc"); params.debug = settings.getAs<uint32_t>("render/pt/debug"); params.shadowRayTmin = settings.getAs<float>("render/pt/dev/shadowRayTmin"); params.materialRayTmin = settings.getAs<float>("render/pt/dev/materialRayTmin"); memcpy(params.viewToWorld, glm::value_ptr(glm::transpose(glm::inverse(camera.matrices.view))), sizeof(params.viewToWorld)); memcpy(params.clipToView, glm::value_ptr(glm::transpose(camera.matrices.invPerspective)), sizeof(params.clipToView)); params.subframe_index = getSharedContext().mSubframeIndex; // Photometric Units from iray documentation // Controls the sensitivity of the “camera film” and is expressed as an index; the ISO number of the film, also // known as “film speed.” The higher this value, the greater the exposure. If this is set to a non-zero value, // “Photographic” mode is enabled. If this is set to 0, “Arbitrary” mode is enabled, and all color scaling is then // strictly defined by the value of cm^2 Factor. float filmIso = settings.getAs<float>("render/post/tonemapper/filmIso"); // The candela per meter square factor float cm2_factor = settings.getAs<float>("render/post/tonemapper/cm2_factor"); // The fractional aperture number; e.g., 11 means aperture “f/11.” It adjusts the size of the opening of the “camera // iris” and is expressed as a ratio. The higher this value, the lower the exposure. float fStop = settings.getAs<float>("render/post/tonemapper/fStop"); // Controls the duration, in fractions of a second, that the “shutter” is open; e.g., the value 100 means that the // “shutter” is open for 1/100th of a second. The higher this value, the greater the exposure float shutterSpeed = settings.getAs<float>("render/post/tonemapper/shutterSpeed"); // Specifies the main color temperature of the light sources; the color that will be mapped to “white” on output, // e.g., an incoming color of this hue/saturation will be mapped to grayscale, but its intensity will remain // unchanged. This is similar to white balance controls on digital cameras. float3 whitePoint { 1.0f, 1.0f, 1.0f }; float3 exposureValue = all(whitePoint) ? 1.0f / whitePoint : make_float3(1.0f); const float lum = dot(exposureValue, make_float3(0.299f, 0.587f, 0.114f)); if (filmIso > 0.0f) { // See https://www.nayuki.io/page/the-photographic-exposure-equation exposureValue *= cm2_factor * filmIso / (shutterSpeed * fStop * fStop) / 100.0f; } else { exposureValue *= cm2_factor; } exposureValue /= lum; params.exposure = exposureValue; const uint32_t totalSpp = settings.getAs<uint32_t>("render/pt/sppTotal"); const uint32_t samplesPerLaunch = settings.getAs<uint32_t>("render/pt/spp"); const int32_t leftSpp = totalSpp - getSharedContext().mSubframeIndex; // if accumulation is off then launch selected samples per pixel uint32_t samplesThisLaunch = enableAccumulation ? std::min((int32_t)samplesPerLaunch, leftSpp) : samplesPerLaunch; if (params.debug == 1) { samplesThisLaunch = 1; enableAccumulation = false; } params.samples_per_launch = samplesThisLaunch; params.enableAccumulation = enableAccumulation; params.maxSampleCount = totalSpp; CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(mState.d_params), &params, sizeof(params), cudaMemcpyHostToDevice)); if (samplesThisLaunch != 0) { OPTIX_CHECK(optixLaunch( mState.pipeline, mState.stream, mState.d_params, sizeof(Params), &mState.sbt, width, height, /*depth=*/1)); CUDA_SYNC_CHECK(); if (enableAccumulation) { getSharedContext().mSubframeIndex += samplesThisLaunch; } else { getSharedContext().mSubframeIndex = 0; } } else { // just copy latest accumulated raw radiance to destination if (params.debug == 0) { CUDA_CHECK(cudaMemcpy(params.image, params.accum, mState.params.image_width * mState.params.image_height * sizeof(float4), cudaMemcpyDeviceToDevice)); } if (params.debug == 2) { CUDA_CHECK(cudaMemcpy(params.image, params.diffuse, mState.params.image_width * mState.params.image_height * sizeof(float4), cudaMemcpyDeviceToDevice)); } if (params.debug == 3) { CUDA_CHECK(cudaMemcpy(params.image, params.specular, mState.params.image_width * mState.params.image_height * sizeof(float4), cudaMemcpyDeviceToDevice)); } } if (params.debug != 1) { // do not run post processing for debug output tonemap(tonemapperType, exposureValue, gamma, params.image, width, height); } output->unmap(); getSharedContext().mFrameNumber++; mPrevView = currView; mState.prevParams = mState.params; } void OptiXRender::init() { // TODO: move USD_DIR to settings const char* envUSDPath = std::getenv("USD_DIR"); mEnableValidation = getSharedContext().mSettingsManager->getAs<bool>("render/enableValidation"); fs::path usdMdlLibPath; if (envUSDPath) { usdMdlLibPath = (fs::path(envUSDPath) / fs::path("libraries/mdl/")).make_preferred(); } const fs::path cwdPath = fs::current_path(); STRELKA_DEBUG("cwdPath: {}", cwdPath.string().c_str()); const fs::path mtlxPath = (cwdPath / fs::path("data/materials/mtlx")).make_preferred(); STRELKA_DEBUG("mtlxPath: {}", mtlxPath.string().c_str()); const fs::path mdlPath = (cwdPath / fs::path("data/materials/mdl")).make_preferred(); const std::string usdMdlLibPathStr = usdMdlLibPath.string(); const std::string mtlxPathStr = mtlxPath.string().c_str(); const std::string mdlPathStr = mdlPath.string().c_str(); const char* paths[] = { usdMdlLibPathStr.c_str(), mtlxPathStr.c_str(), mdlPathStr.c_str() }; bool res = mMaterialManager.addMdlSearchPath(paths, sizeof(paths) / sizeof(char*)); if (!res) { STRELKA_FATAL("Wrong mdl paths configuration!"); assert(0); return; } // default material { oka::Scene::MaterialDescription defaultMaterial{}; defaultMaterial.file = "default.mdl"; defaultMaterial.name = "default_material"; defaultMaterial.type = oka::Scene::MaterialDescription::Type::eMdl; mScene->addMaterial(defaultMaterial); } createContext(); // createAccelerationStructure(); createModule(); createProgramGroups(); createPipeline(); // createSbt(); } Buffer* OptiXRender::createBuffer(const BufferDesc& desc) { const size_t size = desc.height * desc.width * Buffer::getElementSize(desc.format); assert(size != 0); void* devicePtr = nullptr; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&devicePtr), size)); OptixBuffer* res = new OptixBuffer(devicePtr, desc.format, desc.width, desc.height); return res; } void OptiXRender::createPointsBuffer() { const std::vector<glm::float3>& points = mScene->getCurvesPoint(); std::vector<float3> data(points.size()); for (int i = 0; i < points.size(); ++i) { data[i] = make_float3(points[i].x, points[i].y, points[i].z); } const size_t size = data.size() * sizeof(float3); if (d_points) { CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_points))); } CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_points), size)); CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_points), data.data(), size, cudaMemcpyHostToDevice)); } void OptiXRender::createWidthsBuffer() { const std::vector<float>& data = mScene->getCurvesWidths(); const size_t size = data.size() * sizeof(float); if (d_widths) { CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_widths))); } CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_widths), size)); CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_widths), data.data(), size, cudaMemcpyHostToDevice)); } void OptiXRender::createVertexBuffer() { const std::vector<oka::Scene::Vertex>& vertices = mScene->getVertices(); const size_t vbsize = vertices.size() * sizeof(oka::Scene::Vertex); if (d_vb) { CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_vb))); } CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_vb), vbsize)); CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_vb), vertices.data(), vbsize, cudaMemcpyHostToDevice)); } void OptiXRender::createIndexBuffer() { const std::vector<uint32_t>& indices = mScene->getIndices(); const size_t ibsize = indices.size() * sizeof(uint32_t); if (d_ib) { CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_ib))); } CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_ib), ibsize)); CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_ib), indices.data(), ibsize, cudaMemcpyHostToDevice)); } void OptiXRender::createLightBuffer() { const std::vector<Scene::Light>& lightDescs = mScene->getLights(); const size_t lightBufferSize = lightDescs.size() * sizeof(Scene::Light); if (d_lights) { CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_lights))); } if (lightBufferSize) { CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_lights), lightBufferSize)); CUDA_CHECK( cudaMemcpy(reinterpret_cast<void*>(d_lights), lightDescs.data(), lightBufferSize, cudaMemcpyHostToDevice)); } } Texture OptiXRender::loadTextureFromFile(const std::string& fileName) { int texWidth, texHeight, texChannels; stbi_uc* data = stbi_load(fileName.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); if (!data) { STRELKA_ERROR("Unable to load texture from file: {}", fileName.c_str()); return Texture(); } // convert to float4 format // TODO: add compression here: // std::vector<float> floatData(texWidth * texHeight * 4); // for (int i = 0; i < texHeight; ++i) // { // for (int j = 0; j < texWidth; ++j) // { // const size_t linearPixelIndex = (i * texWidth + j) * 4; // auto remapToFloat = [](const unsigned char v) // { // return float(v) / 255.0f; // }; // floatData[linearPixelIndex + 0] = remapToFloat(data[linearPixelIndex + 0]); // floatData[linearPixelIndex + 1] = remapToFloat(data[linearPixelIndex + 1]); // floatData[linearPixelIndex + 2] = remapToFloat(data[linearPixelIndex + 2]); // floatData[linearPixelIndex + 3] = remapToFloat(data[linearPixelIndex + 3]); // } // } const void* dataPtr = data; cudaChannelFormatDesc channel_desc = cudaCreateChannelDesc<uchar4>(); cudaResourceDesc res_desc{}; memset(&res_desc, 0, sizeof(res_desc)); cudaArray_t device_tex_array; CUDA_CHECK(cudaMallocArray(&device_tex_array, &channel_desc, texWidth, texHeight)); CUDA_CHECK(cudaMemcpy2DToArray(device_tex_array, 0, 0, dataPtr, texWidth * sizeof(char) * 4, texWidth * sizeof(char) * 4, texHeight, cudaMemcpyHostToDevice)); res_desc.resType = cudaResourceTypeArray; res_desc.res.array.array = device_tex_array; // Create filtered texture object cudaTextureDesc tex_desc; memset(&tex_desc, 0, sizeof(tex_desc)); cudaTextureAddressMode addr_mode = cudaAddressModeWrap; tex_desc.addressMode[0] = addr_mode; tex_desc.addressMode[1] = addr_mode; tex_desc.addressMode[2] = addr_mode; tex_desc.filterMode = cudaFilterModeLinear; tex_desc.readMode = cudaReadModeNormalizedFloat; tex_desc.normalizedCoords = 1; if (res_desc.resType == cudaResourceTypeMipmappedArray) { tex_desc.mipmapFilterMode = cudaFilterModeLinear; tex_desc.maxAnisotropy = 16; tex_desc.minMipmapLevelClamp = 0.f; tex_desc.maxMipmapLevelClamp = 1000.f; // default value in OpenGL } cudaTextureObject_t tex_obj = 0; CUDA_CHECK(cudaCreateTextureObject(&tex_obj, &res_desc, &tex_desc, nullptr)); // Create unfiltered texture object if necessary (cube textures have no texel functions) cudaTextureObject_t tex_obj_unfilt = 0; // if (texture_shape != mi::neuraylib::ITarget_code::Texture_shape_cube) { // Use a black border for access outside of the texture tex_desc.addressMode[0] = cudaAddressModeBorder; tex_desc.addressMode[1] = cudaAddressModeBorder; tex_desc.addressMode[2] = cudaAddressModeBorder; tex_desc.filterMode = cudaFilterModePoint; CUDA_CHECK(cudaCreateTextureObject(&tex_obj_unfilt, &res_desc, &tex_desc, nullptr)); } return Texture(tex_obj, tex_obj_unfilt, make_uint3(texWidth, texHeight, 1)); } bool OptiXRender::createOptixMaterials() { std::unordered_map<std::string, MaterialManager::Module*> mNameToModule; std::unordered_map<std::string, MaterialManager::MaterialInstance*> mNameToInstance; std::unordered_map<std::string, MaterialManager::CompiledMaterial*> mNameToCompiled; std::unordered_map<std::string, MaterialManager::TargetCode*> mNameToTargetCode; std::vector<MaterialManager::CompiledMaterial*> compiledMaterials; MaterialManager::TargetCode* targetCode; std::vector<Scene::MaterialDescription>& matDescs = mScene->getMaterials(); for (uint32_t i = 0; i < matDescs.size(); ++i) { oka::Scene::MaterialDescription& currMatDesc = matDescs[i]; if (currMatDesc.type == oka::Scene::MaterialDescription::Type::eMdl) { if (auto it = mNameToCompiled.find(currMatDesc.name); it != mNameToCompiled.end()) { compiledMaterials.emplace_back(it->second); continue; } MaterialManager::Module* mdlModule = nullptr; if (mNameToModule.find(currMatDesc.file) != mNameToModule.end()) { mdlModule = mNameToModule[currMatDesc.file]; } else { mdlModule = mMaterialManager.createModule(currMatDesc.file.c_str()); if (mdlModule == nullptr) { STRELKA_ERROR("Unable to load MDL file: {}, Force replaced to default.mdl", currMatDesc.file.c_str()); mdlModule = mNameToModule["default.mdl"]; } mNameToModule[currMatDesc.file] = mdlModule; } assert(mdlModule); MaterialManager::MaterialInstance* materialInst = nullptr; if (mNameToInstance.find(currMatDesc.name) != mNameToInstance.end()) { materialInst = mNameToInstance[currMatDesc.name]; } else { materialInst = mMaterialManager.createMaterialInstance(mdlModule, currMatDesc.name.c_str()); mNameToInstance[currMatDesc.name] = materialInst; } assert(materialInst); MaterialManager::CompiledMaterial* materialComp = nullptr; { materialComp = mMaterialManager.compileMaterial(materialInst); mNameToCompiled[currMatDesc.name] = materialComp; } assert(materialComp); compiledMaterials.push_back(materialComp); } else { MaterialManager::Module* mdlModule = mMaterialManager.createMtlxModule(currMatDesc.code.c_str()); assert(mdlModule); MaterialManager::MaterialInstance* materialInst = mMaterialManager.createMaterialInstance(mdlModule, ""); assert(materialInst); MaterialManager::CompiledMaterial* materialComp = mMaterialManager.compileMaterial(materialInst); assert(materialComp); compiledMaterials.push_back(materialComp); // MaterialManager::TargetCode* mdlTargetCode = mMaterialManager.generateTargetCode(&materialComp, 1); // assert(mdlTargetCode); // mNameToTargetCode[currMatDesc.name] = mdlTargetCode; // targetCodes.push_back(mdlTargetCode); } } targetCode = mMaterialManager.generateTargetCode(compiledMaterials.data(), compiledMaterials.size()); std::vector<Texture> materialTextures; const auto searchPath = getSharedContext().mSettingsManager->getAs<std::string>("resource/searchPath"); fs::path resourcePath = fs::path(getSharedContext().mSettingsManager->getAs<std::string>("resource/searchPath")); for (uint32_t i = 0; i < matDescs.size(); ++i) { for (const auto& param : matDescs[i].params) { bool res = false; if (param.type == MaterialManager::Param::Type::eTexture) { std::string texPath(param.value.size(), 0); memcpy(texPath.data(), param.value.data(), param.value.size()); // int texId = getTexManager()->loadTextureMdl(texPath); fs::path fullTextureFilePath = resourcePath / texPath; ::Texture tex = loadTextureFromFile(fullTextureFilePath.string()); materialTextures.push_back(tex); int texId = 0; int resId = mMaterialManager.registerResource(targetCode, texId); assert(resId > 0); MaterialManager::Param newParam; newParam.name = param.name; newParam.type = MaterialManager::Param::Type::eInt; newParam.value.resize(sizeof(resId)); memcpy(newParam.value.data(), &resId, sizeof(resId)); res = mMaterialManager.setParam(targetCode, i, compiledMaterials[i], newParam); } else { res = mMaterialManager.setParam(targetCode, i, compiledMaterials[i], param); } if (!res) { STRELKA_ERROR( "Unable to set parameter: {0} for material: {1}", param.name.c_str(), matDescs[i].name.c_str()); // assert(0); } } mMaterialManager.dumpParams(targetCode, i, compiledMaterials[i]); } const uint8_t* argData = mMaterialManager.getArgBufferData(targetCode); const size_t argDataSize = mMaterialManager.getArgBufferSize(targetCode); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_materialArgData), argDataSize)); CUDA_CHECK(cudaMemcpy((void*)d_materialArgData, argData, argDataSize, cudaMemcpyHostToDevice)); const uint8_t* roData = mMaterialManager.getReadOnlyBlockData(targetCode); const size_t roDataSize = mMaterialManager.getReadOnlyBlockSize(targetCode); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_materialRoData), roDataSize)); CUDA_CHECK(cudaMemcpy((void*)d_materialRoData, roData, roDataSize, cudaMemcpyHostToDevice)); const size_t texturesBuffSize = sizeof(Texture) * materialTextures.size(); CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_texturesData), texturesBuffSize)); CUDA_CHECK(cudaMemcpy((void*)d_texturesData, materialTextures.data(), texturesBuffSize, cudaMemcpyHostToDevice)); Texture_handler resourceHandler; resourceHandler.num_textures = materialTextures.size(); resourceHandler.textures = (const Texture*)d_texturesData; CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_texturesHandler), sizeof(Texture_handler))); CUDA_CHECK(cudaMemcpy((void*)d_texturesHandler, &resourceHandler, sizeof(Texture_handler), cudaMemcpyHostToDevice)); std::unordered_map<MaterialManager::CompiledMaterial*, OptixProgramGroup> compiledToOptixPG; for (int i = 0; i < compiledMaterials.size(); ++i) { if (compiledToOptixPG.find(compiledMaterials[i]) == compiledToOptixPG.end()) { const char* codeData = mMaterialManager.getShaderCode(targetCode, i); assert(codeData); const size_t codeSize = strlen(codeData); assert(codeSize); OptixProgramGroup pg = createRadianceClosestHitProgramGroup(mState, codeData, codeSize); compiledToOptixPG[compiledMaterials[i]] = pg; } Material optixMaterial; optixMaterial.programGroup = compiledToOptixPG[compiledMaterials[i]]; optixMaterial.d_argData = d_materialArgData + mMaterialManager.getArgBlockOffset(targetCode, i); optixMaterial.d_argDataSize = argDataSize; optixMaterial.d_roData = d_materialRoData + mMaterialManager.getReadOnlyOffset(targetCode, i); optixMaterial.d_roSize = roDataSize; optixMaterial.d_textureHandler = d_texturesHandler; mMaterials.push_back(optixMaterial); } return true; } OptiXRender::Material& OptiXRender::getMaterial(int id) { assert(id < mMaterials.size()); return mMaterials[id]; }
61,289
C++
41.5625
127
0.640066
arhix52/Strelka/src/render/optix/postprocessing/Utils.h
#pragma once #include <sutil/vec_math.h> // utility function for accumulation and HDR <=> LDR __device__ __inline__ float3 tonemap(float3 color, const float3 exposure) { color *= exposure; return color / (color + 1.0f); } __device__ __inline__ float3 inverseTonemap(const float3 color, const float3 exposure) { return color / (exposure - color * exposure); }
373
C
23.933332
86
0.683646
arhix52/Strelka/src/render/optix/postprocessing/Tonemappers.h
#pragma once #include <sutil/vec_math.h> #include <stdint.h> enum class ToneMapperType : uint32_t { eNone = 0, eReinhard, eACES, eFilmic, }; extern "C" void tonemap(const ToneMapperType type, const float3 exposure, const float gamma, float4* image, const uint32_t width, const uint32_t height);
433
C
21.842104
50
0.512702
arhix52/Strelka/src/render/metal/MetalBuffer.h
#pragma once #include "buffer.h" #include <Metal/Metal.hpp> namespace oka { class MetalBuffer : public Buffer { public: MetalBuffer(MTL::Buffer* buff, BufferFormat format, uint32_t width, uint32_t height); ~MetalBuffer() override; void resize(uint32_t width, uint32_t height) override; void* map() override; void unmap() override; MTL::Buffer* getNativePtr() { return mBuffer; } void* getHostPointer() override { return map(); } size_t getHostDataSize() override { return mBuffer->length(); } protected: MTL::Buffer* mBuffer; }; } // namespace oka
640
C
15.868421
89
0.63125
arhix52/Strelka/src/render/metal/MetalBuffer.cpp
#include "MetalBuffer.h" using namespace oka; oka::MetalBuffer::MetalBuffer(MTL::Buffer* buff, BufferFormat format, uint32_t width, uint32_t height) : mBuffer(buff) { mFormat = format; mWidth = width; mHeight = height; } oka::MetalBuffer::~MetalBuffer() { mBuffer->release(); } void oka::MetalBuffer::resize(uint32_t width, uint32_t height) { } void* oka::MetalBuffer::map() { return mBuffer->contents(); } void oka::MetalBuffer::unmap() { }
470
C++
14.193548
118
0.676596
arhix52/Strelka/src/render/metal/MetalRender.cpp
#define NS_PRIVATE_IMPLEMENTATION #define MTL_PRIVATE_IMPLEMENTATION #define MTK_PRIVATE_IMPLEMENTATION #include <Metal/Metal.hpp> #include "MetalRender.h" #include "MetalBuffer.h" #include <cassert> #include <filesystem> #include <glm/glm.hpp> #include <glm/mat4x3.hpp> #include <glm/gtx/compatibility.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/matrix_major_storage.hpp> #include <glm/ext/matrix_relational.hpp> #define STB_IMAGE_STATIC #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <log.h> #include <simd/simd.h> #include "shaders/ShaderTypes.h" using namespace oka; namespace fs = std::filesystem; MetalRender::MetalRender(/* args */) = default; MetalRender::~MetalRender() = default; void MetalRender::init() { mDevice = MTL::CreateSystemDefaultDevice(); mCommandQueue = mDevice->newCommandQueue(); buildComputePipeline(); buildTonemapperPipeline(); } MTL::Texture* MetalRender::loadTextureFromFile(const std::string& fileName) { int texWidth = 0; int texHeight = 0; int texChannels = 0; stbi_uc* data = stbi_load(fileName.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); if (data == nullptr) { STRELKA_ERROR("Unable to load texture from file: {}", fileName.c_str()); return nullptr; } MTL::TextureDescriptor* pTextureDesc = MTL::TextureDescriptor::alloc()->init(); pTextureDesc->setWidth(texWidth); pTextureDesc->setHeight(texHeight); pTextureDesc->setPixelFormat(MTL::PixelFormatRGBA8Unorm); pTextureDesc->setTextureType(MTL::TextureType2D); pTextureDesc->setStorageMode(MTL::StorageModeManaged); pTextureDesc->setUsage(MTL::ResourceUsageSample | MTL::ResourceUsageRead); MTL::Texture* pTexture = mDevice->newTexture(pTextureDesc); const MTL::Region region = MTL::Region::Make3D(0, 0, 0, texWidth, texHeight, 1); pTexture->replaceRegion(region, 0, data, 4ull * texWidth); pTextureDesc->release(); return pTexture; } void MetalRender::createMetalMaterials() { using simd::float3; const std::vector<Scene::MaterialDescription>& matDescs = mScene->getMaterials(); std::vector<Material> gpuMaterials; const fs::path resourcePath = getSharedContext().mSettingsManager->getAs<std::string>("resource/searchPath"); for (const Scene::MaterialDescription& currMatDesc : matDescs) { Material material = {}; material.diffuse = { 1.0f, 1.0f, 1.0f }; for (const auto& param : currMatDesc.params) { if (param.name == "diffuse_color" || param.name == "diffuseColor" || param.name == "diffuse_color_constant") { memcpy(&material.diffuse, param.value.data(), sizeof(float) * 3); } if (param.type == MaterialManager::Param::Type::eTexture) { std::string texPath(param.value.size(), 0); memcpy(texPath.data(), param.value.data(), param.value.size()); const fs::path fullTextureFilePath = resourcePath / texPath; if (param.name == "diffuse_texture") { MTL::Texture* diffuseTex = loadTextureFromFile(fullTextureFilePath.string()); mMaterialTextures.push_back(diffuseTex); material.diffuseTexture = diffuseTex->gpuResourceID(); } if (param.name == "normalmap_texture") { MTL::Texture* normalTex = loadTextureFromFile(fullTextureFilePath.string()); mMaterialTextures.push_back(normalTex); material.normalTexture = normalTex->gpuResourceID(); } } } gpuMaterials.push_back(material); } const size_t materialsDataSize = sizeof(Material) * gpuMaterials.size(); mMaterialBuffer = mDevice->newBuffer(materialsDataSize, MTL::ResourceStorageModeManaged); memcpy(mMaterialBuffer->contents(), gpuMaterials.data(), materialsDataSize); mMaterialBuffer->didModifyRange(NS::Range::Make(0, mMaterialBuffer->length())); } void MetalRender::render(Buffer* output) { using simd::float3; using simd::float4; using simd::float4x4; NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init(); if (getSharedContext().mFrameNumber == 0) { buildBuffers(); createMetalMaterials(); createAccelerationStructures(); // create accum buffer, we don't need cpu access, make it device only mAccumulationBuffer = mDevice->newBuffer( output->width() * output->height() * output->getElementSize(), MTL::ResourceStorageModePrivate); } mFrameIndex = (mFrameIndex + 1) % kMaxFramesInFlight; // Update camera state: const uint32_t width = output->width(); const uint32_t height = output->height(); oka::Camera& camera = mScene->getCamera(1); camera.updateAspectRatio(width / (float)height); camera.updateViewMatrix(); View currView = {}; currView.mCamMatrices = camera.matrices; if (glm::any(glm::notEqual(currView.mCamMatrices.perspective, mPrevView.mCamMatrices.perspective)) || glm::any(glm::notEqual(currView.mCamMatrices.view, mPrevView.mCamMatrices.view))) { // need reset getSharedContext().mSubframeIndex = 0; } SettingsManager& settings = *getSharedContext().mSettingsManager; MTL::Buffer* pUniformBuffer = mUniformBuffers[mFrameIndex]; MTL::Buffer* pUniformTMBuffer = mUniformTMBuffers[mFrameIndex]; Uniforms* pUniformData = reinterpret_cast<Uniforms*>(pUniformBuffer->contents()); UniformsTonemap* pUniformTonemap = reinterpret_cast<UniformsTonemap*>(pUniformTMBuffer->contents()); pUniformData->frameIndex = mFrameIndex; pUniformData->subframeIndex = getSharedContext().mSubframeIndex; pUniformData->height = height; pUniformData->width = width; pUniformData->numLights = mScene->getLightsDesc().size(); pUniformData->samples_per_launch = settings.getAs<uint32_t>("render/pt/spp"); pUniformData->enableAccumulation = (uint32_t)settings.getAs<bool>("render/pt/enableAcc"); pUniformData->missColor = float3(0.0f); pUniformData->maxDepth = settings.getAs<uint32_t>("render/pt/depth"); pUniformData->debug = settings.getAs<uint32_t>("render/pt/debug"); pUniformTonemap->width = width; pUniformTonemap->height = height; pUniformTonemap->tonemapperType = settings.getAs<uint32_t>("render/pt/tonemapperType"); pUniformTonemap->gamma = settings.getAs<float>("render/post/gamma"); bool settingsChanged = false; static uint32_t rectLightSamplingMethodPrev = 0; pUniformData->rectLightSamplingMethod = settings.getAs<uint32_t>("render/pt/rectLightSamplingMethod"); settingsChanged = (rectLightSamplingMethodPrev != pUniformData->rectLightSamplingMethod); rectLightSamplingMethodPrev = pUniformData->rectLightSamplingMethod; static bool enableAccumulationPrev = false; const bool enableAccumulation = settings.getAs<bool>("render/pt/enableAcc"); settingsChanged |= (enableAccumulationPrev != enableAccumulation); enableAccumulationPrev = enableAccumulation; static uint32_t sspTotalPrev = 0; const uint32_t sspTotal = settings.getAs<uint32_t>("render/pt/sppTotal"); settingsChanged |= (sspTotalPrev > sspTotal); // reset only if new spp less than already accumulated sspTotalPrev = sspTotal; if (settingsChanged) { getSharedContext().mSubframeIndex = 0; } glm::float4x4 invView = glm::inverse(camera.matrices.view); for (int column = 0; column < 4; column++) { for (int row = 0; row < 4; row++) { pUniformData->viewToWorld.columns[column][row] = invView[column][row]; } } for (int column = 0; column < 4; column++) { for (int row = 0; row < 4; row++) { pUniformData->clipToView.columns[column][row] = camera.matrices.invPerspective[column][row]; } } pUniformData->subframeIndex = getSharedContext().mSubframeIndex; // Photometric Units from iray documentation // Controls the sensitivity of the “camera film” and is expressed as an index; the ISO number of the film, also // known as “film speed.” The higher this value, the greater the exposure. If this is set to a non-zero value, // “Photographic” mode is enabled. If this is set to 0, “Arbitrary” mode is enabled, and all color scaling is then // strictly defined by the value of cm^2 Factor. float filmIso = settings.getAs<float>("render/post/tonemapper/filmIso"); // The candela per meter square factor float cm2_factor = settings.getAs<float>("render/post/tonemapper/cm2_factor"); // The fractional aperture number; e.g., 11 means aperture “f/11.” It adjusts the size of the opening of the “camera // iris” and is expressed as a ratio. The higher this value, the lower the exposure. float fStop = settings.getAs<float>("render/post/tonemapper/fStop"); // Controls the duration, in fractions of a second, that the “shutter” is open; e.g., the value 100 means that the // “shutter” is open for 1/100th of a second. The higher this value, the greater the exposure float shutterSpeed = settings.getAs<float>("render/post/tonemapper/shutterSpeed"); // Specifies the main color temperature of the light sources; the color that will be mapped to “white” on output, // e.g., an incoming color of this hue/saturation will be mapped to grayscale, but its intensity will remain // unchanged. This is similar to white balance controls on digital cameras. float3 whitePoint{ 1.0f, 1.0f, 1.0f }; auto all = [](float3 v) { return v.x > 0.0f && v.y > 0.0f && v.z > 0.0f; }; float3 exposureValue = all(whitePoint) ? 1.0f / whitePoint : float3(1.0f); const float lum = simd::dot(exposureValue, float3{ 0.299f, 0.587f, 0.114f }); if (filmIso > 0.0f) { // See https://www.nayuki.io/page/the-photographic-exposure-equation exposureValue *= cm2_factor * filmIso / (shutterSpeed * fStop * fStop) / 100.0f; } else { exposureValue *= cm2_factor; } exposureValue /= lum; pUniformTonemap->exposureValue = exposureValue; pUniformData->exposureValue = exposureValue; // need for proper accumulation const uint32_t totalSpp = settings.getAs<uint32_t>("render/pt/sppTotal"); const uint32_t samplesPerLaunch = settings.getAs<uint32_t>("render/pt/spp"); const int32_t leftSpp = totalSpp - getSharedContext().mSubframeIndex; // if accumulation is off then launch selected samples per pixel const uint32_t samplesThisLaunch = enableAccumulation ? std::min((int32_t)samplesPerLaunch, leftSpp) : samplesPerLaunch; if (samplesThisLaunch != 0) { pUniformData->samples_per_launch = samplesThisLaunch; pUniformBuffer->didModifyRange(NS::Range::Make(0, sizeof(Uniforms))); pUniformTMBuffer->didModifyRange(NS::Range::Make(0, sizeof(UniformsTonemap))); MTL::CommandBuffer* pCmd = mCommandQueue->commandBuffer(); MTL::ComputeCommandEncoder* pComputeEncoder = pCmd->computeCommandEncoder(); pComputeEncoder->useResource(mMaterialBuffer, MTL::ResourceUsageRead); pComputeEncoder->useResource(mLightBuffer, MTL::ResourceUsageRead); pComputeEncoder->useResource(mInstanceAccelerationStructure, MTL::ResourceUsageRead); for (const MTL::AccelerationStructure* primitiveAccel : mPrimitiveAccelerationStructures) { pComputeEncoder->useResource(primitiveAccel, MTL::ResourceUsageRead); } for (auto& materialTexture : mMaterialTextures) { pComputeEncoder->useResource(materialTexture, MTL::ResourceUsageRead); } pComputeEncoder->useResource(((MetalBuffer*)output)->getNativePtr(), MTL::ResourceUsageWrite); pComputeEncoder->setComputePipelineState(mPathTracingPSO); pComputeEncoder->setBuffer(pUniformBuffer, 0, 0); pComputeEncoder->setBuffer(mInstanceBuffer, 0, 1); pComputeEncoder->setAccelerationStructure(mInstanceAccelerationStructure, 2); pComputeEncoder->setBuffer(mLightBuffer, 0, 3); pComputeEncoder->setBuffer(mMaterialBuffer, 0, 4); // Output pComputeEncoder->setBuffer(((MetalBuffer*)output)->getNativePtr(), 0, 5); pComputeEncoder->setBuffer(mAccumulationBuffer, 0, 6); { const MTL::Size gridSize = MTL::Size(width, height, 1); const NS::UInteger threadGroupSize = mPathTracingPSO->maxTotalThreadsPerThreadgroup(); const MTL::Size threadgroupSize(threadGroupSize, 1, 1); pComputeEncoder->dispatchThreads(gridSize, threadgroupSize); } // Disable tonemapping for debug output if (pUniformData->debug == 0) { pComputeEncoder->setComputePipelineState(mTonemapperPSO); pComputeEncoder->useResource( ((MetalBuffer*)output)->getNativePtr(), MTL::ResourceUsageRead | MTL::ResourceUsageWrite); pComputeEncoder->setBuffer(pUniformTMBuffer, 0, 0); pComputeEncoder->setBuffer(((MetalBuffer*)output)->getNativePtr(), 0, 1); { const MTL::Size gridSize = MTL::Size(width, height, 1); const NS::UInteger threadGroupSize = mTonemapperPSO->maxTotalThreadsPerThreadgroup(); const MTL::Size threadgroupSize(threadGroupSize, 1, 1); pComputeEncoder->dispatchThreads(gridSize, threadgroupSize); } } pComputeEncoder->endEncoding(); pCmd->commit(); pCmd->waitUntilCompleted(); if (enableAccumulation) { getSharedContext().mSubframeIndex += samplesThisLaunch; } else { getSharedContext().mSubframeIndex = 0; } } else { MTL::CommandBuffer* pCmd = mCommandQueue->commandBuffer(); MTL::BlitCommandEncoder* pBlitEncoder = pCmd->blitCommandEncoder(); pBlitEncoder->copyFromBuffer( mAccumulationBuffer, 0, ((MetalBuffer*)output)->getNativePtr(), 0, width * height * sizeof(float4)); pBlitEncoder->endEncoding(); // Disable tonemapping for debug output if (pUniformData->debug == 0) { MTL::ComputeCommandEncoder* pComputeEncoder = pCmd->computeCommandEncoder(); pComputeEncoder->setComputePipelineState(mTonemapperPSO); pComputeEncoder->useResource( ((MetalBuffer*)output)->getNativePtr(), MTL::ResourceUsageRead | MTL::ResourceUsageWrite); pComputeEncoder->setBuffer(pUniformTMBuffer, 0, 0); pComputeEncoder->setBuffer(((MetalBuffer*)output)->getNativePtr(), 0, 1); { const MTL::Size gridSize = MTL::Size(width, height, 1); const NS::UInteger threadGroupSize = mTonemapperPSO->maxTotalThreadsPerThreadgroup(); const MTL::Size threadgroupSize(threadGroupSize, 1, 1); pComputeEncoder->dispatchThreads(gridSize, threadgroupSize); } pComputeEncoder->endEncoding(); } pCmd->commit(); pCmd->waitUntilCompleted(); } pPool->release(); mPrevView = currView; getSharedContext().mFrameNumber++; } Buffer* MetalRender::createBuffer(const BufferDesc& desc) { assert(mDevice); const size_t size = desc.height * desc.width * Buffer::getElementSize(desc.format); assert(size != 0); MTL::Buffer* buff = mDevice->newBuffer(size, MTL::ResourceStorageModeManaged); assert(buff); MetalBuffer* res = new MetalBuffer(buff, desc.format, desc.width, desc.height); assert(res); return res; } void MetalRender::buildComputePipeline() { NS::Error* pError = nullptr; MTL::Library* pComputeLibrary = mDevice->newLibrary(NS::String::string("./metal/shaders/pathtrace.metallib", NS::UTF8StringEncoding), &pError); if (!pComputeLibrary) { STRELKA_FATAL("{}", pError->localizedDescription()->utf8String()); assert(false); } MTL::Function* pPathTraceFn = pComputeLibrary->newFunction(NS::String::string("raytracingKernel", NS::UTF8StringEncoding)); mPathTracingPSO = mDevice->newComputePipelineState(pPathTraceFn, &pError); if (!mPathTracingPSO) { STRELKA_FATAL("{}", pError->localizedDescription()->utf8String()); assert(false); } pPathTraceFn->release(); pComputeLibrary->release(); } void MetalRender::buildTonemapperPipeline() { NS::Error* pError = nullptr; MTL::Library* pComputeLibrary = mDevice->newLibrary(NS::String::string("./metal/shaders/tonemapper.metallib", NS::UTF8StringEncoding), &pError); if (!pComputeLibrary) { STRELKA_FATAL("{}", pError->localizedDescription()->utf8String()); assert(false); } MTL::Function* pTonemapperFn = pComputeLibrary->newFunction(NS::String::string("toneMappingComputeShader", NS::UTF8StringEncoding)); mTonemapperPSO = mDevice->newComputePipelineState(pTonemapperFn, &pError); if (!mTonemapperPSO) { STRELKA_FATAL("{}", pError->localizedDescription()->utf8String()); assert(false); } pTonemapperFn->release(); pComputeLibrary->release(); } void MetalRender::buildBuffers() { const std::vector<Scene::Vertex>& vertices = mScene->getVertices(); const std::vector<uint32_t>& indices = mScene->getIndices(); const std::vector<Scene::Light>& lightDescs = mScene->getLights(); static_assert(sizeof(Scene::Light) == sizeof(UniformLight)); const size_t lightBufferSize = sizeof(Scene::Light) * lightDescs.size(); const size_t vertexDataSize = sizeof(Scene::Vertex) * vertices.size(); const size_t indexDataSize = sizeof(uint32_t) * indices.size(); MTL::Buffer* pLightBuffer = mDevice->newBuffer(lightBufferSize, MTL::ResourceStorageModeManaged); MTL::Buffer* pVertexBuffer = mDevice->newBuffer(vertexDataSize, MTL::ResourceStorageModeManaged); MTL::Buffer* pIndexBuffer = mDevice->newBuffer(indexDataSize, MTL::ResourceStorageModeManaged); mLightBuffer = pLightBuffer; mVertexBuffer = pVertexBuffer; mIndexBuffer = pIndexBuffer; memcpy(mLightBuffer->contents(), lightDescs.data(), lightBufferSize); memcpy(mVertexBuffer->contents(), vertices.data(), vertexDataSize); memcpy(mIndexBuffer->contents(), indices.data(), indexDataSize); mLightBuffer->didModifyRange(NS::Range::Make(0, mLightBuffer->length())); mVertexBuffer->didModifyRange(NS::Range::Make(0, mVertexBuffer->length())); mIndexBuffer->didModifyRange(NS::Range::Make(0, mIndexBuffer->length())); for (MTL::Buffer*& uniformBuffer : mUniformBuffers) { uniformBuffer = mDevice->newBuffer(sizeof(Uniforms), MTL::ResourceStorageModeManaged); } for (MTL::Buffer*& uniformBuffer : mUniformTMBuffers) { uniformBuffer = mDevice->newBuffer(sizeof(UniformsTonemap), MTL::ResourceStorageModeManaged); } } MTL::AccelerationStructure* MetalRender::createAccelerationStructure(MTL::AccelerationStructureDescriptor* descriptor) { NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init(); // Query for the sizes needed to store and build the acceleration structure. const MTL::AccelerationStructureSizes accelSizes = mDevice->accelerationStructureSizes(descriptor); // Allocate an acceleration structure large enough for this descriptor. This doesn't actually // build the acceleration structure, it just allocates memory. MTL::AccelerationStructure* accelerationStructure = mDevice->newAccelerationStructure(accelSizes.accelerationStructureSize); // Allocate scratch space Metal uses to build the acceleration structure. // Use MTLResourceStorageModePrivate for best performance because the sample // doesn't need access to the buffer's contents. MTL::Buffer* scratchBuffer = mDevice->newBuffer(accelSizes.buildScratchBufferSize, MTL::ResourceStorageModePrivate); // Create a command buffer to perform the acceleration structure build. MTL::CommandBuffer* commandBuffer = mCommandQueue->commandBuffer(); // Create an acceleration structure command encoder. MTL::AccelerationStructureCommandEncoder* commandEncoder = commandBuffer->accelerationStructureCommandEncoder(); // Allocate a buffer for Metal to write the compacted accelerated structure's size into. MTL::Buffer* compactedSizeBuffer = mDevice->newBuffer(sizeof(uint32_t), MTL::ResourceStorageModeShared); // Schedule the actual acceleration structure build. commandEncoder->buildAccelerationStructure(accelerationStructure, descriptor, scratchBuffer, 0UL); // Compute and write the compacted acceleration structure size into the buffer. You // need to already have a built accelerated structure because Metal determines the compacted // size based on the final size of the acceleration structure. Compacting an acceleration // structure can potentially reclaim significant amounts of memory because Metal must // create the initial structure using a conservative approach. commandEncoder->writeCompactedAccelerationStructureSize(accelerationStructure, compactedSizeBuffer, 0UL); // End encoding and commit the command buffer so the GPU can start building the // acceleration structure. commandEncoder->endEncoding(); commandBuffer->commit(); // The sample waits for Metal to finish executing the command buffer so that it can // read back the compacted size. // Note: Don't wait for Metal to finish executing the command buffer if you aren't compacting // the acceleration structure because doing so requires CPU/GPU synchronization. You don't have // to compact acceleration structures, but it's helpful when creating large static acceleration // structures, such as static scene geometry. Avoid compacting acceleration structures that // you rebuild every frame because the synchronization cost may be significant. commandBuffer->waitUntilCompleted(); const uint32_t compactedSize = *(uint32_t*)compactedSizeBuffer->contents(); // commandBuffer->release(); // commandEncoder->release(); // Allocate a smaller acceleration structure based on the returned size. MTL::AccelerationStructure* compactedAccelerationStructure = mDevice->newAccelerationStructure(compactedSize); // Create another command buffer and encoder. commandBuffer = mCommandQueue->commandBuffer(); commandEncoder = commandBuffer->accelerationStructureCommandEncoder(); // Encode the command to copy and compact the acceleration structure into the // smaller acceleration structure. commandEncoder->copyAndCompactAccelerationStructure(accelerationStructure, compactedAccelerationStructure); // End encoding and commit the command buffer. You don't need to wait for Metal to finish // executing this command buffer as long as you synchronize any ray-intersection work // to run after this command buffer completes. The sample relies on Metal's default // dependency tracking on resources to automatically synchronize access to the new // compacted acceleration structure. commandEncoder->endEncoding(); commandBuffer->commit(); // commandEncoder->release(); // commandBuffer->release(); accelerationStructure->release(); scratchBuffer->release(); compactedSizeBuffer->release(); pPool->release(); return compactedAccelerationStructure->retain(); } constexpr simd_float4x4 makeIdentity() { using simd::float4; return (simd_float4x4){ (float4){ 1.f, 0.f, 0.f, 0.f }, (float4){ 0.f, 1.f, 0.f, 0.f }, (float4){ 0.f, 0.f, 1.f, 0.f }, (float4){ 0.f, 0.f, 0.f, 1.f } }; } MetalRender::Mesh* MetalRender::createMesh(const oka::Mesh& mesh) { MetalRender::Mesh* result = new MetalRender::Mesh(); const uint32_t triangleCount = mesh.mCount / 3; const std::vector<Scene::Vertex>& vertices = mScene->getVertices(); const std::vector<uint32_t>& indices = mScene->getIndices(); std::vector<Triangle> triangleData(triangleCount); for (int i = 0; i < triangleCount; ++i) { Triangle& curr = triangleData[i]; const uint32_t i0 = indices[mesh.mIndex + i * 3 + 0]; const uint32_t i1 = indices[mesh.mIndex + i * 3 + 1]; const uint32_t i2 = indices[mesh.mIndex + i * 3 + 2]; // Positions using simd::float3; curr.positions[0] = { vertices[mesh.mVbOffset + i0].pos.x, vertices[mesh.mVbOffset + i0].pos.y, vertices[mesh.mVbOffset + i0].pos.z }; curr.positions[1] = { vertices[mesh.mVbOffset + i1].pos.x, vertices[mesh.mVbOffset + i1].pos.y, vertices[mesh.mVbOffset + i1].pos.z }; curr.positions[2] = { vertices[mesh.mVbOffset + i2].pos.x, vertices[mesh.mVbOffset + i2].pos.y, vertices[mesh.mVbOffset + i2].pos.z }; // Normals curr.normals[0] = vertices[mesh.mVbOffset + i0].normal; curr.normals[1] = vertices[mesh.mVbOffset + i1].normal; curr.normals[2] = vertices[mesh.mVbOffset + i2].normal; // Tangents curr.tangent[0] = vertices[mesh.mVbOffset + i0].tangent; curr.tangent[1] = vertices[mesh.mVbOffset + i1].tangent; curr.tangent[2] = vertices[mesh.mVbOffset + i2].tangent; // UVs curr.uv[0] = vertices[mesh.mVbOffset + i0].uv; curr.uv[1] = vertices[mesh.mVbOffset + i1].uv; curr.uv[2] = vertices[mesh.mVbOffset + i2].uv; } MTL::Buffer* perPrimitiveBuffer = mDevice->newBuffer(triangleData.size() * sizeof(Triangle), MTL::ResourceStorageModeManaged); memcpy(perPrimitiveBuffer->contents(), triangleData.data(), sizeof(Triangle) * triangleData.size()); perPrimitiveBuffer->didModifyRange(NS::Range(0, perPrimitiveBuffer->length())); MTL::AccelerationStructureTriangleGeometryDescriptor* geomDescriptor = MTL::AccelerationStructureTriangleGeometryDescriptor::alloc()->init(); geomDescriptor->setVertexBuffer(mVertexBuffer); geomDescriptor->setVertexBufferOffset(mesh.mVbOffset * sizeof(Scene::Vertex)); geomDescriptor->setVertexStride(sizeof(Scene::Vertex)); geomDescriptor->setIndexBuffer(mIndexBuffer); geomDescriptor->setIndexBufferOffset(mesh.mIndex * sizeof(uint32_t)); geomDescriptor->setIndexType(MTL::IndexTypeUInt32); geomDescriptor->setTriangleCount(triangleCount); // Setup per primitive data geomDescriptor->setPrimitiveDataBuffer(perPrimitiveBuffer); geomDescriptor->setPrimitiveDataBufferOffset(0); geomDescriptor->setPrimitiveDataElementSize(sizeof(Triangle)); geomDescriptor->setPrimitiveDataStride(sizeof(Triangle)); const NS::Array* geomDescriptors = NS::Array::array((const NS::Object* const*)&geomDescriptor, 1UL); MTL::PrimitiveAccelerationStructureDescriptor* primDescriptor = MTL::PrimitiveAccelerationStructureDescriptor::alloc()->init(); primDescriptor->setGeometryDescriptors(geomDescriptors); result->mGas = createAccelerationStructure(primDescriptor); primDescriptor->release(); geomDescriptor->release(); perPrimitiveBuffer->release(); return result; } void MetalRender::createAccelerationStructures() { NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init(); const std::vector<oka::Mesh>& meshes = mScene->getMeshes(); const std::vector<oka::Curve>& curves = mScene->getCurves(); const std::vector<oka::Instance>& instances = mScene->getInstances(); if (meshes.empty() && curves.empty()) { return; } for (const oka::Mesh& currMesh : meshes) { MetalRender::Mesh* metalMesh = createMesh(currMesh); mMetalMeshes.push_back(metalMesh); mPrimitiveAccelerationStructures.push_back(metalMesh->mGas); } mInstanceBuffer = mDevice->newBuffer( sizeof(MTL::AccelerationStructureUserIDInstanceDescriptor) * instances.size(), MTL::ResourceStorageModeManaged); MTL::AccelerationStructureUserIDInstanceDescriptor* instanceDescriptors = (MTL::AccelerationStructureUserIDInstanceDescriptor*)mInstanceBuffer->contents(); for (int i = 0; i < instances.size(); ++i) { const Instance& curr = instances[i]; instanceDescriptors[i].accelerationStructureIndex = curr.mMeshId; instanceDescriptors[i].options = MTL::AccelerationStructureInstanceOptionOpaque; instanceDescriptors[i].intersectionFunctionTableOffset = 0; instanceDescriptors[i].userID = curr.type == Instance::Type::eLight ? curr.mLightId : curr.mMaterialId; instanceDescriptors[i].mask = curr.type == Instance::Type::eLight ? GEOMETRY_MASK_LIGHT : GEOMETRY_MASK_TRIANGLE; for (int column = 0; column < 4; column++) { for (int row = 0; row < 3; row++) { instanceDescriptors[i].transformationMatrix.columns[column][row] = curr.transform[column][row]; } } } mInstanceBuffer->didModifyRange(NS::Range::Make(0, mInstanceBuffer->length())); const NS::Array* instancedAccelerationStructures = NS::Array::array( (const NS::Object* const*)mPrimitiveAccelerationStructures.data(), mPrimitiveAccelerationStructures.size()); MTL::InstanceAccelerationStructureDescriptor* accelDescriptor = MTL::InstanceAccelerationStructureDescriptor::descriptor(); accelDescriptor->setInstancedAccelerationStructures(instancedAccelerationStructures); accelDescriptor->setInstanceCount(instances.size()); accelDescriptor->setInstanceDescriptorBuffer(mInstanceBuffer); accelDescriptor->setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorTypeUserID); mInstanceAccelerationStructure = createAccelerationStructure(accelDescriptor); pPool->release(); }
30,059
C++
43.932735
121
0.69144
arhix52/Strelka/src/render/metal/MetalRender.h
#pragma once #include "render.h" #include <Metal/Metal.hpp> #include <MetalKit/MetalKit.hpp> namespace oka { static constexpr size_t kMaxFramesInFlight = 3; class MetalRender : public Render { public: MetalRender(/* args */); ~MetalRender() override; void init() override; void render(Buffer* output) override; Buffer* createBuffer(const BufferDesc& desc) override; void* getNativeDevicePtr() override { return mDevice; } private: struct Mesh { MTL::AccelerationStructure* mGas; }; Mesh* createMesh(const oka::Mesh& mesh); struct View { oka::Camera::Matrices mCamMatrices; }; View mPrevView; MTL::Device* mDevice; MTL::CommandQueue* mCommandQueue; MTL::Library* mShaderLibrary; MTL::ComputePipelineState* mPathTracingPSO; MTL::ComputePipelineState* mTonemapperPSO; MTL::Buffer* mAccumulationBuffer; MTL::Buffer* mLightBuffer; MTL::Buffer* mVertexBuffer; MTL::Buffer* mUniformBuffers[kMaxFramesInFlight]; MTL::Buffer* mUniformTMBuffers[kMaxFramesInFlight]; MTL::Buffer* mIndexBuffer; uint32_t mTriangleCount; std::vector<MetalRender::Mesh*> mMetalMeshes; std::vector<MTL::AccelerationStructure*> mPrimitiveAccelerationStructures; MTL::AccelerationStructure* mInstanceAccelerationStructure; MTL::Buffer* mInstanceBuffer; MTL::Buffer* mMaterialBuffer; std::vector<MTL::Texture*> mMaterialTextures; uint32_t mFrameIndex; void buildComputePipeline(); void buildTonemapperPipeline(); void buildBuffers(); MTL::Texture* loadTextureFromFile(const std::string& fileName); void createMetalMaterials(); MTL::AccelerationStructure* createAccelerationStructure(MTL::AccelerationStructureDescriptor* descriptor); void createAccelerationStructures(); }; } // namespace oka
1,873
C
24.324324
110
0.710091
arhix52/Strelka/src/render/metal/shaders/random.h
#pragma once #include <simd/simd.h> using namespace metal; float uintToFloat(uint x) { return as_type<float>(0x3f800000 | (x >> 9)) - 1.f; } enum class SampleDimension : uint32_t { ePixelX, ePixelY, eLightId, eLightPointX, eLightPointY, eBSDF0, eBSDF1, eBSDF2, eBSDF3, eRussianRoulette, eNUM_DIMENSIONS }; struct SamplerState { uint32_t seed; uint32_t sampleIdx; uint32_t depth; }; #define MAX_BOUNCES 128 // Based on: https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/ inline unsigned pcg_hash(unsigned seed) { unsigned state = seed * 747796405u + 2891336453u; unsigned word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u; return (word >> 22u) ^ word; } inline unsigned hash_with(unsigned seed, unsigned hash) { // Wang hash seed = (seed ^ 61) ^ hash; seed += seed << 3; seed ^= seed >> 4; seed *= 0x27d4eb2d; return seed; } // jenkins hash unsigned int hash(unsigned int a) { a = (a + 0x7ED55D16) + (a << 12); a = (a ^ 0xC761C23C) ^ (a >> 19); a = (a + 0x165667B1) + (a << 5); a = (a + 0xD3A2646C) ^ (a << 9); a = (a + 0xFD7046C5) + (a << 3); a = (a ^ 0xB55A4F09) ^ (a >> 16); return a; } uint32_t hash2(uint32_t x, uint32_t seed) { x ^= x * 0x3d20adea; x += seed; x *= (seed >> 16) | 1; x ^= x * 0x05526c56; x ^= x * 0x53a22864; return x; } uint jenkinsHash(uint x) { x += x << 10; x ^= x >> 6; x += x << 3; x ^= x >> 11; x += x << 15; return x; } constant unsigned int primeNumbers[32] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131 }; float halton(uint32_t index, uint32_t base) { const float s = 1.0f / float(base); unsigned int i = index; float result = 0.0f; float f = s; while (i) { const unsigned int digit = i % base; result += f * float(digit); i = (i - digit) / base; f *= s; } return clamp(result, 0.0f, 1.0f - 1e-6f); // TODO: 1minusEps } static SamplerState initSampler(uint32_t linearPixelIndex, uint32_t pixelSampleIndex, uint32_t seed) { SamplerState sampler {}; sampler.seed = hash(linearPixelIndex); //^ 0x736caf6fu; sampler.sampleIdx = pixelSampleIndex; sampler.depth = 0; return sampler; } template <SampleDimension Dim> static float random(thread SamplerState& state) { const uint32_t dimension = uint32_t(Dim) + state.depth * uint32_t(SampleDimension::eNUM_DIMENSIONS); const uint32_t base = primeNumbers[dimension & 31u]; return halton(state.seed + state.sampleIdx, base); } uint xorshift(thread uint& rngState) { rngState ^= rngState << 13; rngState ^= rngState >> 17; rngState ^= rngState << 5; return rngState; } template<unsigned int N> static __inline__ unsigned int tea( unsigned int val0, unsigned int val1 ) { unsigned int v0 = val0; unsigned int v1 = val1; unsigned int s0 = 0; for( unsigned int n = 0; n < N; n++ ) { s0 += 0x9e3779b9; v0 += ((v1<<4)+0xa341316c)^(v1+s0)^((v1>>5)+0xc8013ea4); v1 += ((v0<<4)+0xad90777d)^(v0+s0)^((v0>>5)+0x7e95761e); } return v0; } // Generate random unsigned int in [0, 2^24) static __inline__ unsigned int lcg(thread unsigned int &prev) { const unsigned int LCG_A = 1664525u; const unsigned int LCG_C = 1013904223u; prev = (LCG_A * prev + LCG_C); return prev & 0x00FFFFFF; } static __inline__ unsigned int lcg2(thread unsigned int &prev) { prev = (prev*8121 + 28411) % 134456; return prev; } // Generate random float in [0, 1) static __inline__ float rnd(thread unsigned int &prev) { return ((float) lcg(prev) / (float) 0x01000000); } static __inline__ unsigned int rot_seed( unsigned int seed, unsigned int frame ) { return seed ^ frame; } // Implementetion from Ray Tracing gems // https://github.com/boksajak/referencePT/blob/master/shaders/PathTracer.hlsl uint initRNG(uint2 pixelCoords, uint2 resolution, uint frameNumber) { uint t = dot(float2(pixelCoords), float2(1, resolution.x)); uint seed = t ^ jenkinsHash(frameNumber); // uint seed = dot(pixelCoords, uint2(1, resolution.x)) ^ jenkinsHash(frameNumber); return jenkinsHash(seed); } uint owen_scramble_rev(uint x, uint seed) { x ^= x * 0x3d20adea; x += seed; x *= (seed >> 16) | 1; x ^= x * 0x05526c56; x ^= x * 0x53a22864; return x; }
4,402
C
21.695876
104
0.62199
arhix52/Strelka/src/render/metal/shaders/lights.h
#pragma once #include <metal_stdlib> #include <simd/simd.h> #include "ShaderTypes.h" using namespace metal; struct LightSampleData { float3 pointOnLight; float pdf; float3 normal; float area; float3 L; float distToLight; }; __inline__ float misWeightBalance(const float a, const float b) { return 1.0f / ( 1.0f + (b / a) ); } static float calcLightArea(device const UniformLight& l) { float area = 0.0f; if (l.type == 0) // rectangle area { float3 e1 = float3(l.points[1]) - float3(l.points[0]); float3 e2 = float3(l.points[3]) - float3(l.points[0]); area = length(cross(e1, e2)); } else if (l.type == 1) // disc area { area = l.points[0].x * l.points[0].x * M_PI_F; // pi * radius^2 } else if (l.type == 2) // sphere area { area = l.points[0].x * l.points[0].x * 4.0f * M_PI_F; // 4 * pi * radius^2 } return area; } static float3 calcLightNormal(device const UniformLight& l, thread const float3& hitPoint) { float3 norm = float3(0.0f); if (l.type == 0) { float3 e1 = float3(l.points[1]) - float3(l.points[0]); float3 e2 = float3(l.points[3]) - float3(l.points[0]); norm = -normalize(cross(e1, e2)); } else if (l.type == 1) { norm = float3(l.normal); } else if (l.type == 2) { norm = normalize(hitPoint - float3(l.points[1])); } return norm; } static void fillLightData(device const UniformLight& l, thread const float3& hitPoint, thread LightSampleData& lightSampleData) { lightSampleData.area = calcLightArea(l); lightSampleData.normal = calcLightNormal(l, hitPoint); const float3 toLight = lightSampleData.pointOnLight - hitPoint; const float lenToLight = length(toLight); lightSampleData.L = toLight / lenToLight; lightSampleData.distToLight = lenToLight; } struct SphQuad { float3 o, x, y, z; float z0, z0sq; float x0, y0, y0sq; // rectangle coords in ’R’ float x1, y1, y1sq; float b0, b1, b0sq, k; float S; }; // Precomputation of constants for the spherical rectangle Q. static SphQuad init(device const UniformLight& l, const float3 o) { SphQuad squad; float3 ex = float3(l.points[1]) - float3(l.points[0]); float3 ey = float3(l.points[3]) - float3(l.points[0]); float3 s = float3(l.points[0]); float exl = length(ex); float eyl = length(ey); squad.o = o; squad.x = ex / exl; squad.y = ey / eyl; squad.z = cross(squad.x, squad.y); // compute rectangle coords in local reference system float3 d = s - o; squad.z0 = dot(d, squad.z); // flip ’z’ to make it point against ’Q’ if (squad.z0 > 0.0f) { squad.z *= -1.0f; squad.z0 *= -1.0f; } squad.z0sq = squad.z0 * squad.z0; squad.x0 = dot(d, squad.x); squad.y0 = dot(d, squad.y); squad.x1 = squad.x0 + exl; squad.y1 = squad.y0 + eyl; squad.y0sq = squad.y0 * squad.y0; squad.y1sq = squad.y1 * squad.y1; // create vectors to four vertices float3 v00 = { squad.x0, squad.y0, squad.z0 }; float3 v01 = { squad.x0, squad.y1, squad.z0 }; float3 v10 = { squad.x1, squad.y0, squad.z0 }; float3 v11 = { squad.x1, squad.y1, squad.z0 }; // compute normals to edges float3 n0 = normalize(cross(v00, v10)); float3 n1 = normalize(cross(v10, v11)); float3 n2 = normalize(cross(v11, v01)); float3 n3 = normalize(cross(v01, v00)); // compute internal angles (gamma_i) float g0 = fast::acos(-dot(n0, n1)); float g1 = fast::acos(-dot(n1, n2)); float g2 = fast::acos(-dot(n2, n3)); float g3 = fast::acos(-dot(n3, n0)); // compute predefined constants squad.b0 = n0.z; squad.b1 = n2.z; squad.b0sq = squad.b0 * squad.b0; const float twoPi = 2.0f * M_PI_F; squad.k = twoPi - g2 - g3; // compute solid angle from internal angles squad.S = g0 + g1 - squad.k; return squad; } static float3 SphQuadSample(const SphQuad squad, const float2 uv) { float u = uv.x; float v = uv.y; // 1. compute cu float au = u * squad.S + squad.k; float fu = (cos(au) * squad.b0 - squad.b1) / sin(au); float cu = 1 / sqrt(fu * fu + squad.b0sq) * (fu > 0 ? 1 : -1); cu = clamp(cu, -1.0f, 1.0f); // avoid NaNs // 2. compute xu float xu = -(cu * squad.z0) / sqrt(1 - cu * cu); xu = clamp(xu, squad.x0, squad.x1); // avoid Infs // 3. compute yv float d = sqrt(xu * xu + squad.z0sq); float h0 = squad.y0 / sqrt(d * d + squad.y0sq); float h1 = squad.y1 / sqrt(d * d + squad.y1sq); float hv = h0 + v * (h1 - h0); float hv2 = hv * hv; float eps = 1e-6f; float yv = (hv2 < 1.0f - eps) ? (hv * d) / sqrt(1.0f - hv2) : squad.y1; // 4. transform (xu, yv, z0) to world coords return (squad.o + xu * squad.x + yv * squad.y + squad.z0 * squad.z); } static LightSampleData SampleRectLight(device const UniformLight& l, thread const float2& u, thread const float3& hitPoint) { LightSampleData lightSampleData; float3 e1 = float3(l.points[1]) - float3(l.points[0]); float3 e2 = float3(l.points[3]) - float3(l.points[0]); // https://www.arnoldrenderer.com/research/egsr2013_spherical_rectangle.pdf SphQuad quad = init(l, hitPoint); if (quad.S <= 0.0f) { lightSampleData.pdf = 0.0f; lightSampleData.pointOnLight = float3(l.points[0]) + e1 * u.x + e2 * u.y; fillLightData(l, hitPoint, lightSampleData); return lightSampleData; } if (quad.S < 1e-3f) { // light too small, use uniform lightSampleData.pointOnLight = float3(l.points[0]) + e1 * u.x + e2 * u.y; fillLightData(l, hitPoint, lightSampleData); lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight / (dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area); return lightSampleData; } lightSampleData.pointOnLight = SphQuadSample(quad, u); fillLightData(l, hitPoint, lightSampleData); lightSampleData.pdf = max(0.0f, 1.0f / quad.S); return lightSampleData; } static __inline__ LightSampleData SampleRectLightUniform(device const UniformLight& l, thread const float2& u, thread const float3& hitPoint) { LightSampleData lightSampleData; // uniform sampling float3 e1 = float3(l.points[1]) - float3(l.points[0]); float3 e2 = float3(l.points[3]) - float3(l.points[0]); lightSampleData.pointOnLight = float3(l.points[0]) + e1 * u.x + e2 * u.y; fillLightData(l, hitPoint, lightSampleData); lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight / (dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area); return lightSampleData; } static __inline__ float getRectLightPdf(device const UniformLight& l, const float3 lightHitPoint, const float3 surfaceHitPoint) { LightSampleData lightSampleData {}; lightSampleData.pointOnLight = lightHitPoint; fillLightData(l, surfaceHitPoint, lightSampleData); lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight / (dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area); return lightSampleData.pdf; } static void createCoordinateSystem(thread const float3& N, thread float3& Nt, thread float3& Nb) { if (fabs(N.x) > fabs(N.y)) { float invLen = 1.0f / sqrt(N.x * N.x + N.z * N.z); Nt = float3(-N.z * invLen, 0.0f, N.x * invLen); } else { float invLen = 1.0f / sqrt(N.y * N.y + N.z * N.z); Nt = float3(0.0f, N.z * invLen, -N.y * invLen); } Nb = cross(N, Nt); } static __inline__ float getDirectLightPdf(float angle) { return 1.0f / (2.0f * M_PI_F * (1.0f - cos(angle))); } static __inline__ float getSphereLightPdf() { return 1.0f / (4.0f * M_PI_F); } static float3 SampleCone(float2 uv, float angle, float3 direction, thread float& pdf) { float phi = 2.0 * M_PI_F * uv.x; float cosTheta = 1.0 - uv.y * (1.0 - cos(angle)); // Convert spherical coordinates to 3D direction float sinTheta = sqrt(1.0 - cosTheta * cosTheta); float3 u, v; createCoordinateSystem(direction, u, v); float3 sampledDir = normalize(cos(phi) * sinTheta * u + sin(phi) * sinTheta * v + cosTheta * direction); // Calculate the PDF for the sampled direction pdf = getDirectLightPdf(angle); return sampledDir; } static __inline__ LightSampleData SampleDistantLight(device const UniformLight& l, const float2 u, const float3 hitPoint) { LightSampleData lightSampleData; float pdf = 0.0f; float3 coneSample = SampleCone(u, l.halfAngle, -float3(l.normal), pdf); lightSampleData.area = 0.0f; lightSampleData.distToLight = 1e9; lightSampleData.L = coneSample; lightSampleData.normal = float3(l.normal); lightSampleData.pdf = pdf; lightSampleData.pointOnLight = coneSample; return lightSampleData; } static __inline__ LightSampleData SampleSphereLight(device const UniformLight& l, const float2 u, const float3 hitPoint) { LightSampleData lightSampleData; // Generate a random direction on the sphere using solid angle sampling float cosTheta = 1.0f - 2.0f * u.x; // cosTheta is uniformly distributed between [-1, 1] float sinTheta = sqrt(1.0f - cosTheta * cosTheta); float phi = 2.0f * M_PI_F * u.y; // phi is uniformly distributed between [0, 2*pi] const float radius = l.points[0].x; // Convert spherical coordinates to Cartesian coordinates float3 sphereDirection = float3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); // Scale the direction by the radius of the sphere and move it to the light position float3 lightPoint = float3(l.points[1]) + radius * sphereDirection; // Calculate the direction from the hit point to the sampled point on the light lightSampleData.L = normalize(lightPoint - hitPoint); // Calculate the distance to the light lightSampleData.distToLight = length(lightPoint - hitPoint); lightSampleData.area = 0.0f; lightSampleData.normal = sphereDirection; lightSampleData.pdf = 1.0f / (4.0f * M_PI_F); lightSampleData.pointOnLight = lightPoint; return lightSampleData; } static __inline__ float getLightPdf(device const UniformLight& l, const float3 lightHitPoint, const float3 surfaceHitPoint) { switch (l.type) { case 0: // Rect return getRectLightPdf(l, lightHitPoint, surfaceHitPoint); break; case 2: // sphere return getSphereLightPdf(); break; case 3: // Distant return getDirectLightPdf(l.halfAngle); break; default: break; } return 0.0f; }
10,860
C
30.75731
141
0.630295
arhix52/Strelka/src/render/metal/shaders/tonemappers.h
#pragma once #include <simd/simd.h> using namespace metal; enum class ToneMapperType : uint32_t { eNone = 0, eReinhard, eACES, eFilmic, }; // https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT static constant float3x3 ACESInputMat = { {0.59719, 0.35458, 0.04823}, {0.07600, 0.90834, 0.01566}, {0.02840, 0.13383, 0.83777} }; // ODT_SAT => XYZ => D60_2_D65 => sRGB static constant float3x3 ACESOutputMat = { { 1.60475, -0.53108, -0.07367}, {-0.10208, 1.10813, -0.00605}, {-0.00327, -0.07276, 1.07602} }; float3 RRTAndODTFit(float3 v) { float3 a = v * (v + 0.0245786f) - 0.000090537f; float3 b = v * (0.983729f * v + 0.4329510f) + 0.238081f; return a / b; } float3 ACESFitted(float3 color) { color = transpose(ACESInputMat) * color; // Apply RRT and ODT color = RRTAndODTFit(color); color = transpose(ACESOutputMat) * color; // Clamp to [0, 1] color = saturate(color); return color; } // https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/ float3 ACESFilm(float3 x) { float a = 2.51f; float b = 0.03f; float c = 2.43f; float d = 0.59f; float e = 0.14f; return saturate((x*(a*x+b))/(x*(c*x+d)+e)); } // original implementation https://github.com/NVIDIAGameWorks/Falcor/blob/5236495554f57a734cc815522d95ae9a7dfe458a/Source/RenderPasses/ToneMapper/ToneMapping.ps.slang float calcLuminance(float3 color) { return dot(color, float3(0.299, 0.587, 0.114)); } float3 reinhard(float3 color) { float luminance = calcLuminance(color); // float reinhard = luminance / (luminance + 1); return color / (luminance + 1.0f); } float gammaFloat(const float c, const float gamma) { if (isnan(c)) { return 0.0f; } if (c > 1.0f) { return 1.0f; } else if (c < 0.0f) { return 0.0f; } else if (c < 0.0031308f) { return 12.92f * c; } else { return 1.055f * pow(c, 1.0f / gamma) - 0.055f; } } float3 srgbGamma(const float3 color, const float gamma) { return float3(gammaFloat(color.r, gamma), gammaFloat(color.g, gamma), gammaFloat(color.b, gamma)); } // utility function for accumulation and HDR <=> LDR float3 tonemap(float3 color, const float3 exposure) { color *= exposure; return color / (color + 1.0f); } float3 inverseTonemap(const float3 color, const float3 exposure) { return color / (exposure - color * exposure); }
2,540
C
21.289473
166
0.626378
arhix52/Strelka/src/render/metal/shaders/ShaderTypes.h
#ifndef ShaderTypes_h #define ShaderTypes_h #include <simd/simd.h> #ifndef __METAL_VERSION__ #ifdef __cplusplus #include <Metal/MTLTypes.hpp> #endif #endif #define GEOMETRY_MASK_TRIANGLE 1 #define GEOMETRY_MASK_CURVE 2 #define GEOMETRY_MASK_LIGHT 4 #define GEOMETRY_MASK_GEOMETRY (GEOMETRY_MASK_TRIANGLE | GEOMETRY_MASK_CURVE) #define RAY_MASK_PRIMARY (GEOMETRY_MASK_GEOMETRY | GEOMETRY_MASK_LIGHT) #define RAY_MASK_SHADOW GEOMETRY_MASK_GEOMETRY #define RAY_MASK_SECONDARY GEOMETRY_MASK_GEOMETRY #ifndef __METAL_VERSION__ struct packed_float3 { # ifdef __cplusplus packed_float3() = default; packed_float3(vector_float3 v) : x(v.x), y(v.y), z(v.z) { } # endif float x; float y; float z; }; #endif enum class DebugMode : uint32_t { eNone = 0, eNormal, }; struct Vertex { vector_float3 pos; uint32_t tangent; uint32_t normal; uint32_t uv; float pad0; float pad1; }; struct Uniforms { simd::float4x4 viewToWorld; simd::float4x4 clipToView; vector_float3 missColor; uint32_t width; uint32_t height; uint32_t frameIndex; uint32_t subframeIndex; uint32_t numLights; uint32_t enableAccumulation; uint32_t samples_per_launch; uint32_t maxDepth; uint32_t rectLightSamplingMethod; uint32_t tonemapperType; // 0 - "None", "Reinhard", "ACES", "Filmic" float gamma; // 0 - off vector_float3 exposureValue; uint32_t debug; }; struct UniformsTonemap { uint32_t width; uint32_t height; uint32_t tonemapperType; // 0 - "None", "Reinhard", "ACES", "Filmic" float gamma; // 0 - off vector_float3 exposureValue; }; struct Triangle { vector_float3 positions[3]; uint32_t normals[3]; uint32_t tangent[3]; uint32_t uv[3]; }; // GPU side structure struct UniformLight { vector_float4 points[4]; vector_float4 color; vector_float4 normal; int type; float halfAngle; float pad0; float pad1; }; struct Material { simd::float3 diffuse; #ifdef __METAL_VERSION__ texture2d<float> diffuseTexture; texture2d<float> normalTexture; #else MTL::ResourceID diffuseTexture; // uint64_t - alignment 8 MTL::ResourceID normalTexture; #endif }; #endif
2,255
C
17.491803
77
0.668736
arhix52/Strelka/src/settings/settings.cpp
#include "settings/settings.h" namespace oka { } // namespace oka
68
C++
8.857142
30
0.705882
arhix52/Strelka/src/app/main.cpp
#include <display/Display.h> #include <render/common.h> #include <render/buffer.h> #include <render/Render.h> #include <sceneloader/gltfloader.h> #include <log.h> #include <logmanager.h> #include <cxxopts.hpp> #include <filesystem> class CameraController : public oka::InputHandler { oka::Camera mCam; glm::quat mOrientation; glm::float3 mPosition; glm::float3 mWorldUp; glm::float3 mWorldForward; float rotationSpeed = 0.025f; float movementSpeed = 1.0f; double pitch = 0.0; double yaw = 0.0; double max_pitch_rate = 5; double max_yaw_rate = 5; public: virtual ~CameraController() = default; struct { bool left = false; bool right = false; bool up = false; bool down = false; bool forward = false; bool back = false; } keys; struct MouseButtons { bool left = false; bool right = false; bool middle = false; } mouseButtons; glm::float2 mMousePos; // // local cameras axis // glm::float3 getFront() const // { // return mOrientation.Transform(GfVec3d(0.0, 0.0, -1.0)); // } // glm::float3 getUp() const // { // return mOrientation.Transform(GfVec3d(0.0, 1.0, 0.0)); // } // glm::float3 getRight() const // { // return mOrientation.Transform(GfVec3d(1.0, 0.0, 0.0)); // } // // global camera axis depending on scene settings // GfVec3d getWorldUp() const // { // return mWorldUp; // } // GfVec3d getWorldForward() const // { // return mWorldForward; // } bool moving() { return keys.left || keys.right || keys.up || keys.down || keys.forward || keys.back || mouseButtons.right || mouseButtons.left || mouseButtons.middle; } void update(double deltaTime, float speed) { mCam.rotationSpeed = rotationSpeed; mCam.movementSpeed = speed; mCam.update(deltaTime); // movementSpeed = speed; // if (moving()) // { // const float moveSpeed = deltaTime * movementSpeed; // if (keys.up) // mPosition += getWorldUp() * moveSpeed; // if (keys.down) // mPosition -= getWorldUp() * moveSpeed; // if (keys.left) // mPosition -= getRight() * moveSpeed; // if (keys.right) // mPosition += getRight() * moveSpeed; // if (keys.forward) // mPosition += getFront() * moveSpeed; // if (keys.back) // mPosition -= getFront() * moveSpeed; // updateViewMatrix(); // } } // void rotate(double rightAngle, double upAngle) // { // GfRotation a(getRight(), upAngle * rotationSpeed); // GfRotation b(getWorldUp(), rightAngle * rotationSpeed); // GfRotation c = a * b; // GfQuatd cq = c.GetQuat(); // cq.Normalize(); // mOrientation = cq * mOrientation; // mOrientation.Normalize(); // updateViewMatrix(); // } // void translate(GfVec3d delta) // { // // mPosition += mOrientation.Transform(delta); // // updateViewMatrix(); // mCam.translate() // } void updateViewMatrix() { // GfMatrix4d view(1.0); // view.SetRotateOnly(mOrientation); // view.SetTranslateOnly(mPosition); // mGfCam.SetTransform(view); mCam.updateViewMatrix(); } oka::Camera& getCamera() { return mCam; } CameraController(oka::Camera& cam, bool isYup) { if (isYup) { cam.setWorldUp(glm::float3(0.0, 1.0, 0.0)); cam.setWorldForward(glm::float3(0.0, 0.0, -1.0)); } else { cam.setWorldUp(glm::float3(0.0, 0.0, 1.0)); cam.setWorldForward(glm::float3(0.0, 1.0, 0.0)); } mCam = cam; // GfMatrix4d xform = mGfCam.GetTransform(); // xform.Orthonormalize(); // mOrientation = xform.ExtractRotationQuat(); // mOrientation.Normalize(); // mPosition = xform.ExtractTranslation(); } void keyCallback(int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods) override { const bool keyState = ((GLFW_REPEAT == action) || (GLFW_PRESS == action)) ? true : false; switch (key) { case GLFW_KEY_W: { mCam.keys.forward = keyState; break; } case GLFW_KEY_S: { mCam.keys.back = keyState; break; } case GLFW_KEY_A: { mCam.keys.left = keyState; break; } case GLFW_KEY_D: { mCam.keys.right = keyState; break; } case GLFW_KEY_Q: { mCam.keys.up = keyState; break; } case GLFW_KEY_E: { mCam.keys.down = keyState; break; } default: break; } } void mouseButtonCallback(int button, int action, [[maybe_unused]] int mods) override { if (button == GLFW_MOUSE_BUTTON_RIGHT) { if (action == GLFW_PRESS) { mCam.mouseButtons.right = true; } else if (action == GLFW_RELEASE) { mCam.mouseButtons.right = false; } } else if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { mCam.mouseButtons.left = true; } else if (action == GLFW_RELEASE) { mCam.mouseButtons.left = false; } } } void handleMouseMoveCallback([[maybe_unused]] double xpos, [[maybe_unused]] double ypos) override { const float dx = mCam.mousePos[0] - xpos; const float dy = mCam.mousePos[1] - ypos; // ImGuiIO& io = ImGui::GetIO(); // bool handled = io.WantCaptureMouse; // if (handled) //{ // camera.mousePos = glm::vec2((float)xpos, (float)ypos); // return; //} if (mCam.mouseButtons.right) { mCam.rotate(-dx, -dy); } if (mCam.mouseButtons.left) { mCam.translate(glm::float3(-0.0, 0.0, -dy * .005 * movementSpeed)); } if (mCam.mouseButtons.middle) { mCam.translate(glm::float3(-dx * 0.01, -dy * 0.01, 0.0f)); } mCam.mousePos[0] = xpos; mCam.mousePos[1] = ypos; } }; int main(int argc, const char* argv[]) { const oka::Logmanager loggerManager; cxxopts::Options options("Strelka -s <Scene path>", "commands"); // clang-format off options.add_options() ("s, scene", "scene path", cxxopts::value<std::string>()->default_value("")) ("i, iteration", "Iteration to capture", cxxopts::value<int32_t>()->default_value("-1")) ("h, help", "Print usage")("t, spp_total", "spp total", cxxopts::value<int32_t>()->default_value("64")) ("f, spp_subframe", "spp subframe", cxxopts::value<int32_t>()->default_value("1")) ("c, need_screenshot", "Screenshot after spp total", cxxopts::value<bool>()->default_value("false")) ("v, validation", "Enable Validation", cxxopts::value<bool>()->default_value("false")); // clang-format on options.parse_positional({ "s" }); auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help() << std::endl; return 0; } // check params const std::string sceneFile(result["s"].as<std::string>()); if (sceneFile.empty()) { STRELKA_FATAL("Specify scene file name"); return 1; } if (!std::filesystem::exists(sceneFile)) { STRELKA_FATAL("Specified scene file: {} doesn't exist", sceneFile.c_str()); return -1; } const std::filesystem::path sceneFilePath = { sceneFile.c_str() }; const std::string resourceSearchPath = sceneFilePath.parent_path().string(); STRELKA_DEBUG("Resource search path {}", resourceSearchPath); auto* ctx = new oka::SharedContext(); // Set up rendering context. uint32_t imageWidth = 1024; uint32_t imageHeight = 768; ctx->mSettingsManager = new oka::SettingsManager(); ctx->mSettingsManager->setAs<uint32_t>("render/width", imageWidth); ctx->mSettingsManager->setAs<uint32_t>("render/height", imageHeight); ctx->mSettingsManager->setAs<uint32_t>("render/pt/depth", 4); ctx->mSettingsManager->setAs<uint32_t>("render/pt/sppTotal", result["t"].as<int32_t>()); ctx->mSettingsManager->setAs<uint32_t>("render/pt/spp", result["f"].as<int32_t>()); ctx->mSettingsManager->setAs<uint32_t>("render/pt/iteration", 0); ctx->mSettingsManager->setAs<uint32_t>("render/pt/stratifiedSamplingType", 0); // 0 - none, 1 - random, 2 - // stratified sampling, 3 - optimized // stratified sampling ctx->mSettingsManager->setAs<uint32_t>("render/pt/tonemapperType", 0); // 0 - reinhard, 1 - aces, 2 - filmic ctx->mSettingsManager->setAs<uint32_t>("render/pt/debug", 0); // 0 - none, 1 - normals ctx->mSettingsManager->setAs<float>("render/cameraSpeed", 1.0f); ctx->mSettingsManager->setAs<float>("render/pt/upscaleFactor", 0.5f); ctx->mSettingsManager->setAs<bool>("render/pt/enableUpscale", true); ctx->mSettingsManager->setAs<bool>("render/pt/enableAcc", true); ctx->mSettingsManager->setAs<bool>("render/pt/enableTonemap", true); ctx->mSettingsManager->setAs<bool>("render/pt/isResized", false); ctx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", false); ctx->mSettingsManager->setAs<bool>("render/pt/screenshotSPP", result["c"].as<bool>()); ctx->mSettingsManager->setAs<uint32_t>("render/pt/rectLightSamplingMethod", 0); ctx->mSettingsManager->setAs<bool>("render/enableValidation", result["v"].as<bool>()); ctx->mSettingsManager->setAs<std::string>("resource/searchPath", resourceSearchPath); // Postprocessing settings: ctx->mSettingsManager->setAs<float>("render/post/tonemapper/filmIso", 100.0f); ctx->mSettingsManager->setAs<float>("render/post/tonemapper/cm2_factor", 1.0f); ctx->mSettingsManager->setAs<float>("render/post/tonemapper/fStop", 4.0f); ctx->mSettingsManager->setAs<float>("render/post/tonemapper/shutterSpeed", 100.0f); ctx->mSettingsManager->setAs<float>("render/post/gamma", 2.4f); // 0.0f - off // Dev settings: ctx->mSettingsManager->setAs<float>("render/pt/dev/shadowRayTmin", 0.0f); // offset to avoid self-collision in light // sampling ctx->mSettingsManager->setAs<float>("render/pt/dev/materialRayTmin", 0.0f); // offset to avoid self-collision in oka::Display* display = oka::DisplayFactory::createDisplay(); display->init(imageWidth, imageHeight, ctx); oka::RenderType type = oka::RenderType::eOptiX; oka::Render* render = oka::RenderFactory::createRender(type); oka::Scene scene; oka::GltfLoader sceneLoader; sceneLoader.loadGltf(sceneFilePath.string(), scene); CameraController cameraController(scene.getCamera(0), true); oka::Camera camera; camera.name = "Main"; camera.fov = 45; camera.position = glm::vec3(0, 0, -10); camera.mOrientation = glm::quat(glm::vec3(0,0,0)); camera.updateViewMatrix(); scene.addCamera(camera); render->setScene(&scene); render->setSharedContext(ctx); render->init(); ctx->mRender = render; oka::BufferDesc desc{}; desc.format = oka::BufferFormat::FLOAT4; desc.width = imageWidth; desc.height = imageHeight; oka::Buffer* outputBuffer = ctx->mRender->createBuffer(desc); display->setInputHandler(&cameraController); while (!display->windowShouldClose()) { auto start = std::chrono::high_resolution_clock::now(); display->pollEvents(); static auto prevTime = std::chrono::high_resolution_clock::now(); auto currentTime = std::chrono::high_resolution_clock::now(); const double deltaTime = std::chrono::duration<double, std::milli>(currentTime - prevTime).count() / 1000.0; const auto cameraSpeed = ctx->mSettingsManager->getAs<float>("render/cameraSpeed"); cameraController.update(deltaTime, cameraSpeed); prevTime = currentTime; scene.updateCamera(cameraController.getCamera(), 0); display->onBeginFrame(); render->render(outputBuffer); outputBuffer->map(); oka::ImageBuffer outputImage; outputImage.data = outputBuffer->getHostPointer(); outputImage.dataSize = outputBuffer->getHostDataSize(); outputImage.height = outputBuffer->height(); outputImage.width = outputBuffer->width(); outputImage.pixel_format = oka::BufferFormat::FLOAT4; display->drawFrame(outputImage); // blit rendered image to swapchain display->drawUI(); // render ui to swapchain image in window resolution display->onEndFrame(); // submit command buffer and present outputBuffer->unmap(); const uint32_t currentSpp = ctx->mSubframeIndex; auto finish = std::chrono::high_resolution_clock::now(); const double frameTime = std::chrono::duration<double, std::milli>(finish - start).count(); display->setWindowTitle((std::string("Strelka") + " [" + std::to_string(frameTime) + " ms]" + " [" + std::to_string(currentSpp) + " spp]") .c_str()); } display->destroy(); return 0; }
13,969
C++
33.408867
120
0.573198
arhix52/Strelka/src/hdRunner/SimpleRenderTask.h
#pragma once #include <pxr/pxr.h> #include <pxr/imaging/hd/task.h> #include <pxr/imaging/hd/renderPass.h> #include <pxr/imaging/hd/renderPassState.h> PXR_NAMESPACE_OPEN_SCOPE class SimpleRenderTask final : public HdTask { public: SimpleRenderTask(const HdRenderPassSharedPtr& renderPass, const HdRenderPassStateSharedPtr& renderPassState, const TfTokenVector& renderTags); void Sync(HdSceneDelegate* sceneDelegate, HdTaskContext* taskContext, HdDirtyBits* dirtyBits) override; void Prepare(HdTaskContext* taskContext, HdRenderIndex* renderIndex) override; void Execute(HdTaskContext* taskContext) override; const TfTokenVector& GetRenderTags() const override; private: HdRenderPassSharedPtr m_renderPass; HdRenderPassStateSharedPtr m_renderPassState; TfTokenVector m_renderTags; }; PXR_NAMESPACE_CLOSE_SCOPE
936
C
25.771428
71
0.719017
arhix52/Strelka/src/hdRunner/SimpleRenderTask.cpp
#include "SimpleRenderTask.h" PXR_NAMESPACE_OPEN_SCOPE SimpleRenderTask::SimpleRenderTask(const HdRenderPassSharedPtr& renderPass, const HdRenderPassStateSharedPtr& renderPassState, const TfTokenVector& renderTags) : HdTask(SdfPath::EmptyPath()), m_renderPass(renderPass), m_renderPassState(renderPassState), m_renderTags(renderTags) { } void SimpleRenderTask::Sync(HdSceneDelegate* sceneDelegate, HdTaskContext* taskContext, HdDirtyBits* dirtyBits) { TF_UNUSED(sceneDelegate); TF_UNUSED(taskContext); m_renderPass->Sync(); *dirtyBits = HdChangeTracker::Clean; } void SimpleRenderTask::Prepare(HdTaskContext* taskContext, HdRenderIndex* renderIndex) { TF_UNUSED(taskContext); const HdResourceRegistrySharedPtr& resourceRegistry = renderIndex->GetResourceRegistry(); m_renderPassState->Prepare(resourceRegistry); //m_renderPass->Prepare(m_renderTags); } void SimpleRenderTask::Execute(HdTaskContext* taskContext) { TF_UNUSED(taskContext); m_renderPass->Execute(m_renderPassState, m_renderTags); } const TfTokenVector& SimpleRenderTask::GetRenderTags() const { return m_renderTags; } PXR_NAMESPACE_CLOSE_SCOPE
1,325
C++
26.624999
122
0.685283
arhix52/Strelka/src/hdRunner/main.cpp
#include "SimpleRenderTask.h" #include <pxr/base/gf/gamma.h> #include <pxr/base/gf/rotation.h> #include <pxr/base/tf/stopwatch.h> #include <pxr/imaging/hd/camera.h> #include <pxr/imaging/hd/engine.h> #include <pxr/imaging/hd/pluginRenderDelegateUniqueHandle.h> #include <pxr/imaging/hd/renderBuffer.h> #include <pxr/imaging/hd/renderDelegate.h> #include <pxr/imaging/hd/renderIndex.h> #include <pxr/imaging/hd/renderPass.h> #include <pxr/imaging/hd/renderPassState.h> #include <pxr/imaging/hd/rendererPlugin.h> #include <pxr/imaging/hd/rendererPluginRegistry.h> #include <pxr/imaging/hf/pluginDesc.h> #include <pxr/imaging/hgi/hgi.h> #include <pxr/imaging/hgi/tokens.h> #include <pxr/imaging/hio/image.h> #include <pxr/imaging/hio/imageRegistry.h> #include <pxr/imaging/hio/types.h> #include <pxr/pxr.h> #include <pxr/usd/ar/resolver.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usdGeom/camera.h> #include <pxr/usd/usdGeom/metrics.h> #include <pxr/usdImaging/usdImaging/delegate.h> #include <render/common.h> #include <render/buffer.h> #include <display/Display.h> #include <log.h> #include <logmanager.h> #include <algorithm> #include <cxxopts.hpp> #include <iostream> #include <filesystem> // #include <cuda_runtime.h> PXR_NAMESPACE_USING_DIRECTIVE TF_DEFINE_PRIVATE_TOKENS(_AppTokens, (HdStrelkaDriver)(HdStrelkaRendererPlugin)); HdRendererPluginHandle GetHdStrelkaPlugin() { HdRendererPluginRegistry& registry = HdRendererPluginRegistry::GetInstance(); const TfToken& pluginId = _AppTokens->HdStrelkaRendererPlugin; HdRendererPluginHandle plugin = registry.GetOrCreateRendererPlugin(pluginId); return plugin; } HdCamera* FindCamera(UsdStageRefPtr& stage, HdRenderIndex* renderIndex, SdfPath& cameraPath) { UsdPrimRange primRange = stage->TraverseAll(); for (auto prim = primRange.cbegin(); prim != primRange.cend(); prim++) { if (!prim->IsA<UsdGeomCamera>()) { continue; } cameraPath = prim->GetPath(); break; } auto* camera = (HdCamera*)dynamic_cast<HdCamera*>(renderIndex->GetSprim(HdTokens->camera, cameraPath)); return camera; } std::vector<std::pair<HdCamera*, SdfPath>> FindAllCameras(UsdStageRefPtr& stage, HdRenderIndex* renderIndex) { UsdPrimRange primRange = stage->TraverseAll(); HdCamera* camera{}; SdfPath cameraPath{}; std::vector<std::pair<HdCamera*, SdfPath>> cameras{}; for (auto prim = primRange.cbegin(); prim != primRange.cend(); prim++) { if (!prim->IsA<UsdGeomCamera>()) { continue; } cameraPath = prim->GetPath(); camera = (HdCamera*)dynamic_cast<HdCamera*>(renderIndex->GetSprim(HdTokens->camera, cameraPath)); cameras.emplace_back(camera, cameraPath); } return cameras; } class CameraController : public oka::InputHandler { GfCamera mGfCam; GfQuatd mOrientation; GfVec3d mPosition; GfVec3d mWorldUp; GfVec3d mWorldForward; float rotationSpeed = 0.025f; float movementSpeed = 1.0f; double pitch = 0.0; double yaw = 0.0; double max_pitch_rate = 5; double max_yaw_rate = 5; public: virtual ~CameraController() = default; struct { bool left = false; bool right = false; bool up = false; bool down = false; bool forward = false; bool back = false; } keys; struct MouseButtons { bool left = false; bool right = false; bool middle = false; } mouseButtons; GfVec2d mMousePos; // local cameras axis GfVec3d getFront() const { return mOrientation.Transform(GfVec3d(0.0, 0.0, -1.0)); } GfVec3d getUp() const { return mOrientation.Transform(GfVec3d(0.0, 1.0, 0.0)); } GfVec3d getRight() const { return mOrientation.Transform(GfVec3d(1.0, 0.0, 0.0)); } // global camera axis depending on scene settings GfVec3d getWorldUp() const { return mWorldUp; } GfVec3d getWorldForward() const { return mWorldForward; } bool moving() { return keys.left || keys.right || keys.up || keys.down || keys.forward || keys.back || mouseButtons.right || mouseButtons.left || mouseButtons.middle; } void update(double deltaTime, float speed) { movementSpeed = speed; if (moving()) { const float moveSpeed = deltaTime * movementSpeed; if (keys.up) mPosition += getWorldUp() * moveSpeed; if (keys.down) mPosition -= getWorldUp() * moveSpeed; if (keys.left) mPosition -= getRight() * moveSpeed; if (keys.right) mPosition += getRight() * moveSpeed; if (keys.forward) mPosition += getFront() * moveSpeed; if (keys.back) mPosition -= getFront() * moveSpeed; updateViewMatrix(); } } void rotate(double rightAngle, double upAngle) { GfRotation a(getRight(), upAngle * rotationSpeed); GfRotation b(getWorldUp(), rightAngle * rotationSpeed); GfRotation c = a * b; GfQuatd cq = c.GetQuat(); cq.Normalize(); mOrientation = cq * mOrientation; mOrientation.Normalize(); updateViewMatrix(); } void translate(GfVec3d delta) { mPosition += mOrientation.Transform(delta); updateViewMatrix(); } void updateViewMatrix() { GfMatrix4d view(1.0); view.SetRotateOnly(mOrientation); view.SetTranslateOnly(mPosition); mGfCam.SetTransform(view); } GfCamera& getCamera() { return mGfCam; } CameraController(UsdGeomCamera& cam, bool isYup) { if (isYup) { mWorldUp = GfVec3d(0.0, 1.0, 0.0); mWorldForward = GfVec3d(0.0, 0.0, -1.0); } else { mWorldUp = GfVec3d(0.0, 0.0, 1.0); mWorldForward = GfVec3d(0.0, 1.0, 0.0); } mGfCam = cam.GetCamera(0.0); GfMatrix4d xform = mGfCam.GetTransform(); xform.Orthonormalize(); mOrientation = xform.ExtractRotationQuat(); mOrientation.Normalize(); mPosition = xform.ExtractTranslation(); } void keyCallback(int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods) override { const bool keyState = ((GLFW_REPEAT == action) || (GLFW_PRESS == action)) ? true : false; switch (key) { case GLFW_KEY_W: { keys.forward = keyState; break; } case GLFW_KEY_S: { keys.back = keyState; break; } case GLFW_KEY_A: { keys.left = keyState; break; } case GLFW_KEY_D: { keys.right = keyState; break; } case GLFW_KEY_Q: { keys.up = keyState; break; } case GLFW_KEY_E: { keys.down = keyState; break; } default: break; } } void mouseButtonCallback(int button, int action, [[maybe_unused]] int mods) override { if (button == GLFW_MOUSE_BUTTON_RIGHT) { if (action == GLFW_PRESS) { mouseButtons.right = true; } else if (action == GLFW_RELEASE) { mouseButtons.right = false; } } else if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { mouseButtons.left = true; } else if (action == GLFW_RELEASE) { mouseButtons.left = false; } } } void handleMouseMoveCallback([[maybe_unused]] double xpos, [[maybe_unused]] double ypos) override { const float dx = mMousePos[0] - xpos; const float dy = mMousePos[1] - ypos; // ImGuiIO& io = ImGui::GetIO(); // bool handled = io.WantCaptureMouse; // if (handled) //{ // camera.mousePos = glm::vec2((float)xpos, (float)ypos); // return; //} if (mouseButtons.right) { rotate(dx, dy); } if (mouseButtons.left) { translate(GfVec3d(-0.0, 0.0, -dy * .005 * movementSpeed)); } if (mouseButtons.middle) { translate(GfVec3d(-dx * 0.01, -dy * 0.01, 0.0f)); } mMousePos[0] = xpos; mMousePos[1] = ypos; } }; class RenderSurfaceController : public oka::ResizeHandler { uint32_t imageWidth = 800; uint32_t imageHeight = 600; oka::SettingsManager* mSettingsManager = nullptr; std::array<HdRenderBuffer*, 3> mRenderBuffers; bool mDirty[3] = { true }; bool mInUse[3] = { false }; public: RenderSurfaceController(oka::SettingsManager* settingsManager, std::array<HdRenderBuffer*, 3>& renderBuffers) : mSettingsManager(settingsManager), mRenderBuffers(renderBuffers) { imageWidth = mSettingsManager->getAs<uint32_t>("render/width"); imageHeight = mSettingsManager->getAs<uint32_t>("render/height"); } void framebufferResize(int newWidth, int newHeight) { assert(mSettingsManager); mSettingsManager->setAs<uint32_t>("render/width", newWidth); mSettingsManager->setAs<uint32_t>("render/height", newHeight); imageWidth = newWidth; imageHeight = newHeight; for (bool& i : mDirty) { i = true; } // reallocateBuffers(); } bool isDirty(uint32_t index) { return mDirty[index]; } void acquire(uint32_t index) { mInUse[index] = true; } void release(uint32_t index) { mInUse[index] = false; } HdRenderBuffer* getRenderBuffer(uint32_t index) { assert(index < 3); if (mDirty[index] && !mInUse[index]) { mRenderBuffers[index]->Allocate(GfVec3i(imageWidth, imageHeight, 1), HdFormatFloat32Vec4, false); mDirty[index] = false; } return mRenderBuffers[index]; } }; void setDefaultCamera(UsdGeomCamera& cam) { // y - up, camera looks at (0, 0, 0) std::vector<float> r0 = { 0, -1, 0, 0 }; std::vector<float> r1 = { 0, 0, 1, 0 }; std::vector<float> r2 = { -1, 0, 0, 0 }; std::vector<float> r3 = { 0, 0, 0, 1 }; GfMatrix4d xform(r0, r1, r2, r3); GfCamera mGfCam{}; mGfCam.SetTransform(xform); GfRange1f clippingRange = GfRange1f{ 0.1, 1000 }; mGfCam.SetClippingRange(clippingRange); mGfCam.SetVerticalAperture(20.25); mGfCam.SetVerticalApertureOffset(0); mGfCam.SetHorizontalAperture(36); mGfCam.SetHorizontalApertureOffset(0); mGfCam.SetFocalLength(50); GfCamera::Projection projection = GfCamera::Projection::Perspective; mGfCam.SetProjection(projection); cam.SetFromCamera(mGfCam, 0.0); } bool saveScreenshot(std::string& outputFilePath, unsigned char* mappedMem, uint32_t imageWidth, uint32_t imageHeight) { TF_VERIFY(mappedMem != nullptr); int pixelCount = imageWidth * imageHeight; // Write image to file. TfStopwatch timerWrite; timerWrite.Start(); HioImageSharedPtr image = HioImage::OpenForWriting(outputFilePath); if (!image) { STRELKA_ERROR("Unable to open output file for writing!"); return false; } HioImage::StorageSpec storage; storage.width = (int)imageWidth; storage.height = (int)imageHeight; storage.depth = (int)1; storage.format = HioFormat::HioFormatFloat32Vec4; storage.flipped = true; storage.data = mappedMem; VtDictionary metadata; image->Write(storage, metadata); timerWrite.Stop(); STRELKA_INFO("Wrote image {}", timerWrite.GetSeconds()); return true; } int main(int argc, const char* argv[]) { const oka::Logmanager loggerManager; // config. options cxxopts::Options options("Strelka -s <USD Scene path>", "commands"); // clang-format off options.add_options() ("s, scene", "scene path", cxxopts::value<std::string>()->default_value("")) ("i, iteration", "Iteration to capture", cxxopts::value<int32_t>()->default_value("-1")) ("h, help", "Print usage")("t, spp_total", "spp total", cxxopts::value<int32_t>()->default_value("64")) ("f, spp_subframe", "spp subframe", cxxopts::value<int32_t>()->default_value("1")) ("c, need_screenshot", "Screenshot after spp total", cxxopts::value<bool>()->default_value("false")) ("v, validation", "Enable Validation", cxxopts::value<bool>()->default_value("false")); // clang-format on options.parse_positional({ "s" }); auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help() << std::endl; return 0; } // check params const std::string usdFile(result["s"].as<std::string>()); if (usdFile.empty()) { STRELKA_FATAL("Specify usd file name"); return 1; } if (!std::filesystem::exists(usdFile)) { STRELKA_FATAL("Specified usd file: {} doesn't exist", usdFile.c_str()); return -1; } const std::filesystem::path usdFilePath = { usdFile.c_str() }; const std::string resourceSearchPath = usdFilePath.parent_path().string(); STRELKA_DEBUG("Resource path {}", resourceSearchPath); const int32_t iterationToCapture(result["i"].as<int32_t>()); // Init plugin. const HdRendererPluginHandle pluginHandle = GetHdStrelkaPlugin(); if (!pluginHandle) { STRELKA_FATAL("HdStrelka plugin not found!"); return EXIT_FAILURE; } if (!pluginHandle->IsSupported()) { STRELKA_FATAL("HdStrelka plugin is not supported!"); return EXIT_FAILURE; } HdDriverVector drivers; // Set up rendering context. uint32_t imageWidth = 1024; uint32_t imageHeight = 768; auto* ctx = new oka::SharedContext(); // &display.getSharedContext(); ctx->mSettingsManager = new oka::SettingsManager(); ctx->mSettingsManager->setAs<uint32_t>("render/width", imageWidth); ctx->mSettingsManager->setAs<uint32_t>("render/height", imageHeight); ctx->mSettingsManager->setAs<uint32_t>("render/pt/depth", 4); ctx->mSettingsManager->setAs<uint32_t>("render/pt/sppTotal", result["t"].as<int32_t>()); ctx->mSettingsManager->setAs<uint32_t>("render/pt/spp", result["f"].as<int32_t>()); ctx->mSettingsManager->setAs<uint32_t>("render/pt/iteration", 0); ctx->mSettingsManager->setAs<uint32_t>("render/pt/stratifiedSamplingType", 0); // 0 - none, 1 - random, 2 - // stratified sampling, 3 - optimized // stratified sampling ctx->mSettingsManager->setAs<uint32_t>("render/pt/tonemapperType", 0); // 0 - reinhard, 1 - aces, 2 - filmic ctx->mSettingsManager->setAs<uint32_t>("render/pt/debug", 0); // 0 - none, 1 - normals ctx->mSettingsManager->setAs<float>("render/cameraSpeed", 1.0f); ctx->mSettingsManager->setAs<float>("render/pt/upscaleFactor", 0.5f); ctx->mSettingsManager->setAs<bool>("render/pt/enableUpscale", true); ctx->mSettingsManager->setAs<bool>("render/pt/enableAcc", true); ctx->mSettingsManager->setAs<bool>("render/pt/enableTonemap", true); ctx->mSettingsManager->setAs<bool>("render/pt/isResized", false); ctx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", false); ctx->mSettingsManager->setAs<bool>("render/pt/screenshotSPP", result["c"].as<bool>()); ctx->mSettingsManager->setAs<uint32_t>("render/pt/rectLightSamplingMethod", 0); ctx->mSettingsManager->setAs<bool>("render/enableValidation", result["v"].as<bool>()); ctx->mSettingsManager->setAs<std::string>("resource/searchPath", resourceSearchPath); // Postprocessing settings: ctx->mSettingsManager->setAs<float>("render/post/tonemapper/filmIso", 100.0f); ctx->mSettingsManager->setAs<float>("render/post/tonemapper/cm2_factor", 1.0f); ctx->mSettingsManager->setAs<float>("render/post/tonemapper/fStop", 4.0f); ctx->mSettingsManager->setAs<float>("render/post/tonemapper/shutterSpeed", 100.0f); ctx->mSettingsManager->setAs<float>("render/post/gamma", 2.4f); // 0.0f - off // Dev settings: ctx->mSettingsManager->setAs<float>("render/pt/dev/shadowRayTmin", 0.0f); // offset to avoid self-collision in light // sampling ctx->mSettingsManager->setAs<float>("render/pt/dev/materialRayTmin", 0.0f); // offset to avoid self-collision in // bsdf sampling HdDriver driver; driver.name = _AppTokens->HdStrelkaDriver; driver.driver = VtValue(ctx); drivers.push_back(&driver); HdRenderDelegate* renderDelegate = pluginHandle->CreateRenderDelegate(); TF_VERIFY(renderDelegate); renderDelegate->SetDrivers(drivers); oka::Display* display = oka::DisplayFactory::createDisplay(); display->init(imageWidth, imageHeight, ctx); // Handle cmdline args. // Load scene. TfStopwatch timerLoad; timerLoad.Start(); // ArGetResolver().ConfigureResolverForAsset(settings.sceneFilePath); const std::string& usdPath = usdFile; UsdStageRefPtr stage = UsdStage::Open(usdPath); timerLoad.Stop(); if (!stage) { STRELKA_FATAL("Unable to open USD stage file."); return EXIT_FAILURE; } STRELKA_INFO("USD scene loaded {}", timerLoad.GetSeconds()); // Print the up-axis const TfToken upAxis = UsdGeomGetStageUpAxis(stage); STRELKA_INFO("Stage up-axis: {}", (std::string)upAxis); // Print the stage's linear units, or "meters per unit" STRELKA_INFO("Meters per unit: {}", UsdGeomGetStageMetersPerUnit(stage)); HdRenderIndex* renderIndex = HdRenderIndex::New(renderDelegate, HdDriverVector()); TF_VERIFY(renderIndex); UsdImagingDelegate sceneDelegate(renderIndex, SdfPath::AbsoluteRootPath()); sceneDelegate.Populate(stage->GetPseudoRoot()); sceneDelegate.SetTime(0); sceneDelegate.SetRefineLevelFallback(4); const double meterPerUnit = UsdGeomGetStageMetersPerUnit(stage); // Init camera from scene SdfPath cameraPath = SdfPath::EmptyPath(); HdCamera* camera = FindCamera(stage, renderIndex, cameraPath); UsdGeomCamera cam; if (camera) { cam = UsdGeomCamera::Get(stage, cameraPath); } else { // Init default camera cameraPath = SdfPath("/defaultCamera"); cam = UsdGeomCamera::Define(stage, cameraPath); setDefaultCamera(cam); } CameraController cameraController(cam, upAxis == UsdGeomTokens->y); // std::vector<std::pair<HdCamera*, SdfPath>> cameras = FindAllCameras(stage, renderIndex); std::array<HdRenderBuffer*, 3> renderBuffers{}; for (int i = 0; i < 3; ++i) { renderBuffers[i] = (HdRenderBuffer*)renderDelegate->CreateFallbackBprim(HdPrimTypeTokens->renderBuffer); renderBuffers[i]->Allocate(GfVec3i(imageWidth, imageHeight, 1), HdFormatFloat32Vec4, false); } CameraUtilFraming framing; framing.dataWindow = GfRect2i(GfVec2i(0, 0), GfVec2i(imageWidth, imageHeight)); framing.displayWindow = GfRange2f(GfVec2f(0.0f, 0.0f), GfVec2f((float)imageWidth, (float)imageHeight)); framing.pixelAspectRatio = 1.0f; const std::optional<CameraUtilConformWindowPolicy> overrideWindowPolicy(CameraUtilFit); // TODO: add UI control here TfTokenVector renderTags{ HdRenderTagTokens->geometry, HdRenderTagTokens->render }; HdRprimCollection renderCollection(HdTokens->geometry, HdReprSelector(HdReprTokens->refined)); HdRenderPassSharedPtr renderPass = renderDelegate->CreateRenderPass(renderIndex, renderCollection); std::shared_ptr<HdRenderPassState> renderPassState[3]; std::shared_ptr<SimpleRenderTask> renderTasks[3]; for (int i = 0; i < 3; ++i) { renderPassState[i] = std::make_shared<HdRenderPassState>(); renderPassState[i]->SetCamera(camera); renderPassState[i]->SetFraming(framing); renderPassState[i]->SetOverrideWindowPolicy(overrideWindowPolicy); HdRenderPassAovBindingVector aovBindings(1); aovBindings[0].aovName = HdAovTokens->color; aovBindings[0].renderBuffer = renderBuffers[i]; renderPassState[i]->SetAovBindings(aovBindings); renderTasks[i] = std::make_shared<SimpleRenderTask>(renderPass, renderPassState[i], renderTags); } // Perform rendering. TfStopwatch timerRender; timerRender.Start(); HdEngine engine; display->setInputHandler(&cameraController); RenderSurfaceController surfaceController(ctx->mSettingsManager, renderBuffers); display->setResizeHandler(&surfaceController); uint64_t frameCount = 0; while (!display->windowShouldClose()) { auto start = std::chrono::high_resolution_clock::now(); HdTaskSharedPtrVector tasks; const uint32_t versionId = frameCount % oka::MAX_FRAMES_IN_FLIGHT; // relocation? surfaceController.acquire(versionId); if (surfaceController.isDirty(versionId)) { HdRenderPassAovBindingVector aovBindings(1); aovBindings[0].aovName = HdAovTokens->color; surfaceController.release(versionId); aovBindings[0].renderBuffer = surfaceController.getRenderBuffer(versionId); surfaceController.acquire(versionId); renderPassState[versionId]->SetAovBindings(aovBindings); renderTasks[versionId] = std::make_shared<SimpleRenderTask>(renderPass, renderPassState[versionId], renderTags); } tasks.push_back(renderTasks[versionId]); sceneDelegate.SetTime(1.0f); display->pollEvents(); static auto prevTime = std::chrono::high_resolution_clock::now(); auto currentTime = std::chrono::high_resolution_clock::now(); const double deltaTime = std::chrono::duration<double, std::milli>(currentTime - prevTime).count() / 1000.0; const auto cameraSpeed = ctx->mSettingsManager->getAs<float>("render/cameraSpeed"); cameraController.update(deltaTime, cameraSpeed); prevTime = currentTime; cam.SetFromCamera(cameraController.getCamera(), 0.0); display->onBeginFrame(); engine.Execute(renderIndex, &tasks); // main path tracing rendering in fixed render resolution auto* outputBuffer = surfaceController.getRenderBuffer(versionId)->GetResource(false).UncheckedGet<oka::Buffer*>(); oka::ImageBuffer outputImage; // upload to host outputBuffer->map(); outputImage.data = outputBuffer->getHostPointer(); outputImage.dataSize = outputBuffer->getHostDataSize(); outputImage.height = outputBuffer->height(); outputImage.width = outputBuffer->width(); outputImage.pixel_format = outputBuffer->getFormat(); const auto totalSpp = ctx->mSettingsManager->getAs<uint32_t>("render/pt/sppTotal"); const uint32_t currentSpp = ctx->mSubframeIndex; bool needScreenshot = ctx->mSettingsManager->getAs<bool>("render/pt/needScreenshot"); if (ctx->mSettingsManager->getAs<bool>("render/pt/screenshotSPP") && (currentSpp == totalSpp)) { needScreenshot = true; // need to store screen only once ctx->mSettingsManager->setAs<bool>("render/pt/screenshotSPP", false); } if (needScreenshot) { const std::size_t foundSlash = usdPath.find_last_of("/\\"); const std::size_t foundDot = usdPath.find_last_of('.'); std::string fileName = usdPath.substr(0, foundDot); fileName = fileName.substr(foundSlash + 1); auto generateName = [&](const uint32_t attempt) { std::string outputFilePath = fileName + "_" + std::to_string(currentSpp) + "i_" + std::to_string(ctx->mSettingsManager->getAs<uint32_t>("render/pt/depth")) + "d_" + std::to_string(totalSpp) + "spp_" + std::to_string(attempt) + ".png"; return outputFilePath; }; uint32_t attempt = 0; std::string outputFilePath; do { outputFilePath = generateName(attempt++); } while (std::filesystem::exists(std::filesystem::path(outputFilePath.c_str()))); unsigned char* mappedMem = (unsigned char*)outputImage.data; if (saveScreenshot(outputFilePath, mappedMem, outputImage.width, outputImage.height)) { ctx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", false); } } display->drawFrame(outputImage); // blit rendered image to swapchain display->drawUI(); // render ui to swapchain image in window resolution display->onEndFrame(); // submit command buffer and present auto finish = std::chrono::high_resolution_clock::now(); const double frameTime = std::chrono::duration<double, std::milli>(finish - start).count(); surfaceController.release(versionId); display->setWindowTitle((std::string("Strelka") + " [" + std::to_string(frameTime) + " ms]" + " [" + std::to_string(currentSpp) + " spp]") .c_str()); ++frameCount; } // renderBuffer->Resolve(); // TF_VERIFY(renderBuffer->IsConverged()); timerRender.Stop(); display->destroy(); STRELKA_INFO("Rendering finished {}", timerRender.GetSeconds()); for (int i = 0; i < 3; ++i) { renderDelegate->DestroyBprim(renderBuffers[i]); } return EXIT_SUCCESS; }
26,275
C++
32.687179
121
0.61785
arhix52/Strelka/src/scene/camera.cpp
#include "camera.h" #include <glm/gtx/quaternion.hpp> #include <glm-wrapper.hpp> namespace oka { void Camera::updateViewMatrix() { const glm::float4x4 rotM{ mOrientation }; const glm::float4x4 transM = glm::translate(glm::float4x4(1.0f), -position); if (type == CameraType::firstperson) { matrices.view = rotM * transM; } else { matrices.view = transM * rotM; } updated = true; } glm::float3 Camera::getFront() const { return glm::conjugate(mOrientation) * glm::float3(0.0f, 0.0f, -1.0f); } glm::float3 Camera::getUp() const { return glm::conjugate(mOrientation) * glm::float3(0.0f, 1.0f, 0.0f); } glm::float3 Camera::getRight() const { return glm::conjugate(mOrientation) * glm::float3(1.0f, 0.0f, 0.0f); } bool Camera::moving() const { return keys.left || keys.right || keys.up || keys.down || keys.forward || keys.back || mouseButtons.right || mouseButtons.left || mouseButtons.middle; } float Camera::getNearClip() const { return znear; } float Camera::getFarClip() const { return zfar; } void Camera::setFov(float fov) { this->fov = fov; } // original implementation: https://vincent-p.github.io/notes/20201216234910-the_projection_matrix_in_vulkan/ glm::float4x4 perspective(float fov, float aspect_ratio, float n, float f, glm::float4x4* inverse) { const float focal_length = 1.0f / std::tan(glm::radians(fov) / 2.0f); const float x = focal_length / aspect_ratio; const float y = focal_length; const float A = n / (f - n); const float B = f * A; //glm::float4x4 projection = glm::perspective(fov, aspect_ratio, n, f); //if (inverse) //{ // *inverse = glm::inverse(projection); //} glm::float4x4 projection({ x, 0.0f, 0.0f, 0.0f, 0.0f, y, 0.0f, 0.0f, 0.0f, 0.0f, A, B, 0.0f, 0.0f, -1.0f, 0.0f, }); if (inverse) { *inverse = glm::transpose(glm::float4x4({ // glm inverse 1 / x, 0.0f, 0.0f, 0.0f, 0.0f, 1 / y, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1 / B, A / B, })); } return glm::transpose(projection); } void Camera::setPerspective(float _fov, float _aspect, float _znear, float _zfar) { fov = _fov; znear = _znear; zfar = _zfar; // swap near and far plane for reverse z matrices.perspective = perspective(fov, _aspect, zfar, znear, &matrices.invPerspective); } void Camera::setWorldUp(const glm::float3 up) { mWorldUp = up; } glm::float3 Camera::getWorldUp() { return mWorldUp; } void Camera::setWorldForward(const glm::float3 forward) { mWorldForward = forward; } glm::float3 Camera::getWorldForward() { return mWorldForward; } glm::float4x4& Camera::getPerspective() { return matrices.perspective; } glm::float4x4 Camera::getView() { return matrices.view; } void Camera::updateAspectRatio(float _aspect) { setPerspective(fov, _aspect, znear, zfar); } void Camera::setPosition(glm::float3 _position) { position = _position; updateViewMatrix(); } glm::float3 Camera::getPosition() { return position; } void Camera::setRotation(glm::quat rotation) { mOrientation = rotation; updateViewMatrix(); } void Camera::rotate(float rightAngle, float upAngle) { const glm::quat a = glm::angleAxis(glm::radians(upAngle) * rotationSpeed, glm::float3(1.0f, 0.0f, 0.0f)); const glm::quat b = glm::angleAxis(glm::radians(rightAngle) * rotationSpeed, glm::float3(0.0f, 1.0f, 0.0f)); // const glm::quat a = glm::angleAxis(glm::radians(upAngle) * rotationSpeed, getRight()); // const glm::quat b = glm::angleAxis(glm::radians(rightAngle) * rotationSpeed, getWorldUp()); // auto c = a * b; // c = glm::normalize(c); mOrientation = glm::normalize(a * mOrientation * b); // mOrientation = glm::normalize(c * mOrientation); updateViewMatrix(); } glm::quat Camera::getOrientation() { return mOrientation; } void Camera::setTranslation(glm::float3 translation) { position = translation; updateViewMatrix(); } void Camera::translate(glm::float3 delta) { position += glm::conjugate(mOrientation) * delta; updateViewMatrix(); } void Camera::update(float deltaTime) { updated = false; if (type == CameraType::firstperson) { if (moving()) { float moveSpeed = deltaTime * movementSpeed; if (keys.up) position += getWorldUp() * moveSpeed; if (keys.down) position -= getWorldUp() * moveSpeed; if (keys.left) position -= getRight() * moveSpeed; if (keys.right) position += getRight() * moveSpeed; if (keys.forward) position += getFront() * moveSpeed; if (keys.back) position -= getFront() * moveSpeed; updateViewMatrix(); } } } } // namespace oka
5,209
C++
20.618257
154
0.582261
arhix52/Strelka/src/scene/scene.cpp
#include "scene.h" #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/norm.hpp> #include <algorithm> #include <array> #include <filesystem> #include <map> #include <utility> namespace fs = std::filesystem; namespace oka { uint32_t Scene::createMesh(const std::vector<Vertex>& vb, const std::vector<uint32_t>& ib) { std::scoped_lock lock(mMeshMutex); Mesh* mesh = nullptr; uint32_t meshId = -1; if (mDelMesh.empty()) { meshId = mMeshes.size(); // add mesh to storage mMeshes.push_back({}); mesh = &mMeshes.back(); } else { meshId = mDelMesh.top(); // get index from stack mDelMesh.pop(); // del taken index from stack mesh = &mMeshes[meshId]; } mesh->mIndex = mIndices.size(); // Index of 1st index in index buffer mesh->mCount = ib.size(); // amount of indices in mesh mesh->mVbOffset = mVertices.size(); mesh->mVertexCount = vb.size(); // const uint32_t ibOffset = mVertices.size(); // adjust indices for global index buffer // for (int i = 0; i < ib.size(); ++i) // { // mIndices.push_back(ibOffset + ib[i]); // } mIndices.insert(mIndices.end(), ib.begin(), ib.end()); mVertices.insert(mVertices.end(), vb.begin(), vb.end()); // copy vertices return meshId; } uint32_t Scene::createInstance(const Instance::Type type, const uint32_t geomId, const uint32_t materialId, const glm::mat4& transform, const uint32_t lightId) { std::scoped_lock lock(mInstanceMutex); Instance* inst = nullptr; uint32_t instId = -1; if (mDelInstances.empty()) { instId = mInstances.size(); // add instance to storage mInstances.push_back({}); inst = &mInstances.back(); } else { instId = mDelInstances.top(); // get index from stack mDelInstances.pop(); // del taken index from stack inst = &mInstances[instId]; } inst->type = type; if (inst->type == Instance::Type::eMesh || inst->type == Instance::Type::eLight) { inst->mMeshId = geomId; } else if (inst->type == Instance::Type::eCurve) { inst->mCurveId = geomId; } inst->mMaterialId = materialId; inst->transform = transform; inst->mLightId = lightId; mOpaqueInstances.push_back(instId); return instId; } uint32_t Scene::addMaterial(const MaterialDescription& material) { // TODO: fix here uint32_t res = mMaterialsDescs.size(); mMaterialsDescs.push_back(material); return res; } std::string Scene::getSceneFileName() { fs::path p(modelPath); return p.filename().string(); }; std::string Scene::getSceneDir() { fs::path p(modelPath); return p.parent_path().string(); }; // valid range of coordinates [-1; 1] uint32_t packNormals(const glm::float3& normal) { uint32_t packed = (uint32_t)((normal.x + 1.0f) / 2.0f * 511.99999f); packed += (uint32_t)((normal.y + 1.0f) / 2.0f * 511.99999f) << 10; packed += (uint32_t)((normal.z + 1.0f) / 2.0f * 511.99999f) << 20; return packed; } uint32_t Scene::createRectLightMesh() { if (mRectLightMeshId != -1) { return mRectLightMeshId; } std::vector<Scene::Vertex> vb; Scene::Vertex v1, v2, v3, v4; v1.pos = glm::float4(0.5f, 0.5f, 0.0f, 1.0f); // top right 0 v2.pos = glm::float4(-0.5f, 0.5f, 0.0f, 1.0f); // top left 1 v3.pos = glm::float4(-0.5f, -0.5f, 0.0f, 1.0f); // bottom left 2 v4.pos = glm::float4(0.5f, -0.5f, 0.0f, 1.0f); // bottom right 3 glm::float3 normal = glm::float3(0.f, 0.f, 1.f); v1.normal = v2.normal = v3.normal = v4.normal = packNormals(normal); std::vector<uint32_t> ib = { 0, 1, 2, 2, 3, 0 }; vb.push_back(v1); vb.push_back(v2); vb.push_back(v3); vb.push_back(v4); uint32_t meshId = createMesh(vb, ib); assert(meshId != -1); return meshId; } uint32_t Scene::createSphereLightMesh() { if (mSphereLightMeshId != -1) { return mSphereLightMeshId; } std::vector<Scene::Vertex> vertices; std::vector<uint32_t> indices; const int segments = 16; const int rings = 16; const float radius = 1.0f; // Generate vertices and normals for (int i = 0; i <= rings; ++i) { float theta = static_cast<float>(i) * static_cast<float>(M_PI) / static_cast<float>(rings); float sinTheta = sin(theta); float cosTheta = cos(theta); for (int j = 0; j <= segments; ++j) { float phi = static_cast<float>(j) * 2.0f * static_cast<float>(M_PI) / static_cast<float>(segments); float sinPhi = sin(phi); float cosPhi = cos(phi); float x = cosPhi * sinTheta; float y = cosTheta; float z = sinPhi * sinTheta; glm::float3 pos = { radius * x, radius * y, radius * z }; glm::float3 normal = { x, y, z }; vertices.push_back(Scene::Vertex{ pos, 0, packNormals(normal) }); } } // Generate indices for (int i = 0; i < rings; ++i) { for (int j = 0; j < segments; ++j) { int p0 = i * (segments + 1) + j; int p1 = p0 + 1; int p2 = (i + 1) * (segments + 1) + j; int p3 = p2 + 1; indices.push_back(p0); indices.push_back(p1); indices.push_back(p2); indices.push_back(p2); indices.push_back(p1); indices.push_back(p3); } } const uint32_t meshId = createMesh(vertices, indices); assert(meshId != -1); return meshId; } uint32_t Scene::createDiscLightMesh() { if (mDiskLightMeshId != -1) { return mDiskLightMeshId; } std::vector<Scene::Vertex> vertices; std::vector<uint32_t> indices; Scene::Vertex v1, v2; v1.pos = glm::float4(0.f, 0.f, 0.f, 1.f); v2.pos = glm::float4(1.0f, 0.f, 0.f, 1.f); glm::float3 normal = glm::float3(0.f, 0.f, 1.f); v1.normal = v2.normal = packNormals(normal); vertices.push_back(v1); // central point vertices.push_back(v2); // first point const float diskRadius = 1.0f; // param const float step = 2.0f * M_PI / 16; float angle = 0; for (int i = 0; i < 16; ++i) { indices.push_back(0); // each triangle have central point indices.push_back(vertices.size() - 1); // prev vertex angle += step; const float x = cos(angle) * diskRadius; const float y = sin(angle) * diskRadius; Scene::Vertex v; v.pos = glm::float4(x, y, 0.0f, 1.0f); v.normal = packNormals(normal); vertices.push_back(v); indices.push_back(vertices.size() - 1); // added vertex } uint32_t meshId = createMesh(vertices, indices); assert(meshId != -1); return meshId; } void Scene::updateAnimation(const float time) { if (mAnimations.empty()) { return; } auto& animation = mAnimations[0]; for (auto& channel : animation.channels) { assert(channel.node < mNodes.size()); auto& sampler = animation.samplers[channel.samplerIndex]; if (sampler.inputs.size() > sampler.outputsVec4.size()) { continue; } for (size_t i = 0; i < sampler.inputs.size() - 1; i++) { if ((time >= sampler.inputs[i]) && (time <= sampler.inputs[i + 1])) { float u = std::max(0.0f, time - sampler.inputs[i]) / (sampler.inputs[i + 1] - sampler.inputs[i]); if (u <= 1.0f) { switch (channel.path) { case AnimationChannel::PathType::TRANSLATION: { glm::vec4 trans = glm::mix(sampler.outputsVec4[i], sampler.outputsVec4[i + 1], u); mNodes[channel.node].translation = glm::float3(trans); break; } case AnimationChannel::PathType::SCALE: { glm::vec4 scale = glm::mix(sampler.outputsVec4[i], sampler.outputsVec4[i + 1], u); mNodes[channel.node].scale = glm::float3(scale); break; } case AnimationChannel::PathType::ROTATION: { float floatRotation[4] = { (float)sampler.outputsVec4[i][3], (float)sampler.outputsVec4[i][0], (float)sampler.outputsVec4[i][1], (float)sampler.outputsVec4[i][2] }; float floatRotation1[4] = { (float)sampler.outputsVec4[i + 1][3], (float)sampler.outputsVec4[i + 1][0], (float)sampler.outputsVec4[i + 1][1], (float)sampler.outputsVec4[i + 1][2] }; glm::quat q1 = glm::make_quat(floatRotation); glm::quat q2 = glm::make_quat(floatRotation1); mNodes[channel.node].rotation = glm::normalize(glm::slerp(q1, q2, u)); break; } } } } } } mCameras[0].matrices.view = getTransform(mCameras[0].node); } uint32_t Scene::createLight(const UniformLightDesc& desc) { uint32_t lightId = (uint32_t)mLights.size(); Light l; mLights.push_back(l); mLightDesc.push_back(desc); updateLight(lightId, desc); // TODO: only for rect light // Lazy init light mesh glm::float4x4 scaleMatrix = glm::float4x4(0.f); uint32_t currentLightMeshId = 0; if (desc.type == 0) { mRectLightMeshId = createRectLightMesh(); currentLightMeshId = mRectLightMeshId; scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.width, desc.height, 1.0f)); } else if (desc.type == 1) { mDiskLightMeshId = createDiscLightMesh(); currentLightMeshId = mDiskLightMeshId; scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius)); } else if (desc.type == 2) { mSphereLightMeshId = createSphereLightMesh(); currentLightMeshId = mSphereLightMeshId; scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius)); } else if (desc.type == 3) { // distant light currentLightMeshId = 0; // empty scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius)); } const glm::float4x4 transform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc); uint32_t instId = createInstance(Instance::Type::eLight, currentLightMeshId, (uint32_t)-1, transform, lightId); assert(instId != -1); mLightIdToInstanceId[lightId] = instId; return lightId; } void Scene::updateLight(const uint32_t lightId, const UniformLightDesc& desc) { const float intensityPerPoint = desc.intensity; // light intensity // transform to GPU light // Rect Light if (desc.type == 0) { const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.width, desc.height, 1.0f)); const glm::float4x4 localTransform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc); mLights[lightId].points[0] = localTransform * glm::float4(0.5f, 0.5f, 0.0f, 1.0f); mLights[lightId].points[1] = localTransform * glm::float4(-0.5f, 0.5f, 0.0f, 1.0f); mLights[lightId].points[2] = localTransform * glm::float4(-0.5f, -0.5f, 0.0f, 1.0f); mLights[lightId].points[3] = localTransform * glm::float4(0.5f, -0.5f, 0.0f, 1.0f); mLights[lightId].type = 0; } else if (desc.type == 1) { // Disk Light const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius)); const glm::float4x4 localTransform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc); mLights[lightId].points[0] = glm::float4(desc.radius, 0.f, 0.f, 0.f); // save radius mLights[lightId].points[1] = localTransform * glm::float4(0.f, 0.f, 0.f, 1.f); // save O mLights[lightId].points[2] = localTransform * glm::float4(1.f, 0.f, 0.f, 0.f); // OXws mLights[lightId].points[3] = localTransform * glm::float4(0.f, 1.f, 0.f, 0.f); // OYws glm::float4 normal = localTransform * glm::float4(0, 0, 1.f, 0.0f); mLights[lightId].normal = normal; mLights[lightId].type = 1; } else if (desc.type == 2) { // Sphere Light const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(1.0f, 1.0f, 1.0f)); const glm::float4x4 localTransform = desc.useXform ? scaleMatrix * desc.xform : getTransform(desc); mLights[lightId].points[0] = glm::float4(desc.radius, 0.f, 0.f, 0.f); // save radius mLights[lightId].points[1] = localTransform * glm::float4(0.f, 0.f, 0.f, 1.f); // save O mLights[lightId].type = 2; } else if (desc.type == 3) { // distant light https://openusd.org/release/api/class_usd_lux_distant_light.html mLights[lightId].type = 3; mLights[lightId].halfAngle = desc.halfAngle; const glm::float4x4 scaleMatrix = glm::float4x4(1.0f); const glm::float4x4 localTransform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc); mLights[lightId].normal = glm::normalize(localTransform * glm::float4(0.0f, 0.0f, -1.0f, 0.0f)); // -Z } mLights[lightId].color = glm::float4(desc.color, 1.0f) * intensityPerPoint; } void Scene::removeInstance(const uint32_t instId) { mDelInstances.push(instId); // marked as removed } void Scene::removeMesh(const uint32_t meshId) { mDelMesh.push(meshId); // marked as removed } void Scene::removeMaterial(const uint32_t materialId) { mDelMaterial.push(materialId); // marked as removed } std::vector<uint32_t>& Scene::getOpaqueInstancesToRender(const glm::float3& camPos) { return mOpaqueInstances; } std::vector<uint32_t>& Scene::getTransparentInstancesToRender(const glm::float3& camPos) { return mTransparentInstances; } std::set<uint32_t> Scene::getDirtyInstances() { return this->mDirtyInstances; } bool Scene::getFrMod() { return this->FrMod; } void Scene::updateInstanceTransform(uint32_t instId, glm::float4x4 newTransform) { Instance& inst = mInstances[instId]; inst.transform = newTransform; mDirtyInstances.insert(instId); } void Scene::beginFrame() { FrMod = true; mDirtyInstances.clear(); } void Scene::endFrame() { FrMod = false; } uint32_t Scene::createCurve(const Curve::Type type, const std::vector<uint32_t>& vertexCounts, const std::vector<glm::float3>& points, const std::vector<float>& widths) { Curve c = {}; c.mPointsStart = mCurvePoints.size(); c.mPointsCount = points.size(); mCurvePoints.insert(mCurvePoints.end(), points.begin(), points.end()); c.mVertexCountsStart = mCurveVertexCounts.size(); c.mVertexCountsCount = vertexCounts.size(); mCurveVertexCounts.insert(mCurveVertexCounts.end(), vertexCounts.begin(), vertexCounts.end()); if (!widths.empty()) { c.mWidthsCount = widths.size(); c.mWidthsStart = mCurveWidths.size(); mCurveWidths.insert(mCurveWidths.end(), widths.begin(), widths.end()); } else { c.mWidthsCount = -1; c.mWidthsStart = -1; } uint32_t res = mCurves.size(); mCurves.push_back(c); return res; } } // namespace oka
15,925
C++
31.108871
120
0.576641
arhix52/Strelka/src/log/logmanager.cpp
#include "logmanager.h" #include <spdlog/spdlog.h> #include <spdlog/cfg/env.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/sinks/basic_file_sink.h> #include <memory> #include <vector> oka::Logmanager::Logmanager() { initialize(); } oka::Logmanager::~Logmanager() { shutdown(); } void oka::Logmanager::initialize() { auto logger = spdlog::get("Strelka"); if (!logger) { spdlog::cfg::load_env_levels(); auto consolesink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("strelka.log"); std::vector<spdlog::sink_ptr> sinks = { consolesink, fileSink }; logger = std::make_shared<spdlog::logger>("Strelka", sinks.begin(), sinks.end()); // TODO: env var doesn't work on linux logger->set_level(spdlog::level::trace); logger->flush_on(spdlog::level::trace); #if defined(WIN32) logger->set_level(spdlog::level::trace); logger->flush_on(spdlog::level::trace); #endif spdlog::register_logger(logger); } } void oka::Logmanager::shutdown() { spdlog::shutdown(); }
1,170
C++
23.914893
91
0.637607
arhix52/Strelka/src/sceneloader/gltfloader.cpp
#include "gltfloader.h" #include "camera.h" #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define TINYGLTF_IMPLEMENTATION #include "tiny_gltf.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/compatibility.hpp> #include <glm/gtx/matrix_decompose.hpp> #include <iostream> #include <log/log.h> namespace fs = std::filesystem; #include "nlohmann/json.hpp" using json = nlohmann::json; namespace oka { // valid range of coordinates [-10; 10] uint32_t packUV(const glm::float2& uv) { int32_t packed = (uint32_t)((uv.x + 10.0f) / 20.0f * 16383.99999f); packed += (uint32_t)((uv.y + 10.0f) / 20.0f * 16383.99999f) << 16; return packed; } // valid range of coordinates [-1; 1] uint32_t packNormal(const glm::float3& normal) { uint32_t packed = (uint32_t)((normal.x + 1.0f) / 2.0f * 511.99999f); packed += (uint32_t)((normal.y + 1.0f) / 2.0f * 511.99999f) << 10; packed += (uint32_t)((normal.z + 1.0f) / 2.0f * 511.99999f) << 20; return packed; } // valid range of coordinates [-10; 10] uint32_t packTangent(const glm::float3& tangent) { uint32_t packed = (uint32_t)((tangent.x + 10.0f) / 20.0f * 511.99999f); packed += (uint32_t)((tangent.y + 10.0f) / 20.0f * 511.99999f) << 10; packed += (uint32_t)((tangent.z + 10.0f) / 20.0f * 511.99999f) << 20; return packed; } glm::float2 unpackUV(uint32_t val) { glm::float2 uv; uv.y = ((val & 0xffff0000) >> 16) / 16383.99999f * 10.0f - 5.0f; uv.x = (val & 0x0000ffff) / 16383.99999f * 10.0f - 5.0f; return uv; } void computeTangent(std::vector<Scene::Vertex>& vertices, const std::vector<uint32_t>& indices) { const size_t lastIndex = indices.size(); Scene::Vertex& v0 = vertices[indices[lastIndex - 3]]; Scene::Vertex& v1 = vertices[indices[lastIndex - 2]]; Scene::Vertex& v2 = vertices[indices[lastIndex - 1]]; glm::float2 uv0 = unpackUV(v0.uv); glm::float2 uv1 = unpackUV(v1.uv); glm::float2 uv2 = unpackUV(v2.uv); glm::float3 deltaPos1 = v1.pos - v0.pos; glm::float3 deltaPos2 = v2.pos - v0.pos; glm::vec2 deltaUV1 = uv1 - uv0; glm::vec2 deltaUV2 = uv2 - uv0; glm::vec3 tangent{ 0.0f, 0.0f, 1.0f }; const float d = deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x; if (abs(d) > 1e-6) { float r = 1.0f / d; tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y) * r; } glm::uint32_t packedTangent = packTangent(tangent); v0.tangent = packedTangent; v1.tangent = packedTangent; v2.tangent = packedTangent; } void processPrimitive(const tinygltf::Model& model, oka::Scene& scene, const tinygltf::Primitive& primitive, const glm::float4x4& transform, const float globalScale) { using namespace std; assert(primitive.attributes.find("POSITION") != primitive.attributes.end()); const tinygltf::Accessor& positionAccessor = model.accessors[primitive.attributes.find("POSITION")->second]; const tinygltf::BufferView& positionView = model.bufferViews[positionAccessor.bufferView]; const float* positionData = reinterpret_cast<const float*>(&model.buffers[positionView.buffer].data[positionAccessor.byteOffset + positionView.byteOffset]); assert(positionData != nullptr); const uint32_t vertexCount = static_cast<uint32_t>(positionAccessor.count); assert(vertexCount != 0); const int byteStride = positionAccessor.ByteStride(positionView); assert(byteStride > 0); // -1 means invalid glTF int posStride = byteStride / sizeof(float); // Normals const float* normalsData = nullptr; int normalStride = 0; if (primitive.attributes.find("NORMAL") != primitive.attributes.end()) { const tinygltf::Accessor& normalAccessor = model.accessors[primitive.attributes.find("NORMAL")->second]; const tinygltf::BufferView& normView = model.bufferViews[normalAccessor.bufferView]; normalsData = reinterpret_cast<const float*>(&(model.buffers[normView.buffer].data[normalAccessor.byteOffset + normView.byteOffset])); assert(normalsData != nullptr); normalStride = normalAccessor.ByteStride(normView) / sizeof(float); assert(normalStride > 0); } // UVs const float* texCoord0Data = nullptr; int texCoord0Stride = 0; if (primitive.attributes.find("TEXCOORD_0") != primitive.attributes.end()) { const tinygltf::Accessor& uvAccessor = model.accessors[primitive.attributes.find("TEXCOORD_0")->second]; const tinygltf::BufferView& uvView = model.bufferViews[uvAccessor.bufferView]; texCoord0Data = reinterpret_cast<const float*>(&(model.buffers[uvView.buffer].data[uvAccessor.byteOffset + uvView.byteOffset])); texCoord0Stride = uvAccessor.ByteStride(uvView) / sizeof(float); } int matId = primitive.material; if (matId == -1) { matId = 0; // TODO: should be index of default material } glm::float3 sum = glm::float3(0.0f, 0.0f, 0.0f); std::vector<oka::Scene::Vertex> vertices; vertices.reserve(vertexCount); for (uint32_t v = 0; v < vertexCount; ++v) { oka::Scene::Vertex vertex{}; vertex.pos = glm::make_vec3(&positionData[v * posStride]) * globalScale; vertex.normal = packNormal(glm::normalize(glm::vec3(normalsData ? glm::make_vec3(&normalsData[v * normalStride]) : glm::vec3(0.0f)))); vertex.uv = packUV(texCoord0Data ? glm::make_vec2(&texCoord0Data[v * texCoord0Stride]) : glm::vec3(0.0f)); vertices.push_back(vertex); sum += vertex.pos; } const glm::float3 massCenter = sum / (float)vertexCount; uint32_t indexCount = 0; std::vector<uint32_t> indices; const bool hasIndices = (primitive.indices != -1); assert(hasIndices); // currently support only this mode if (hasIndices) { const tinygltf::Accessor& accessor = model.accessors[primitive.indices > -1 ? primitive.indices : 0]; const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; indexCount = static_cast<uint32_t>(accessor.count); assert(indexCount != 0 && (indexCount % 3 == 0)); const void* dataPtr = &(buffer.data[accessor.byteOffset + bufferView.byteOffset]); indices.reserve(indexCount); switch (accessor.componentType) { case TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT: { const uint32_t* buf = static_cast<const uint32_t*>(dataPtr); for (size_t index = 0; index < indexCount; index++) { indices.push_back(buf[index]); } computeTangent(vertices, indices); break; } case TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT: { const uint16_t* buf = static_cast<const uint16_t*>(dataPtr); for (size_t index = 0; index < indexCount; index++) { indices.push_back(buf[index]); } computeTangent(vertices, indices); break; } case TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE: { const uint8_t* buf = static_cast<const uint8_t*>(dataPtr); for (size_t index = 0; index < indexCount; index++) { indices.push_back(buf[index]); } computeTangent(vertices, indices); break; } default: std::cerr << "Index component type " << accessor.componentType << " not supported!" << std::endl; return; } } uint32_t meshId = scene.createMesh(vertices, indices); assert(meshId != -1); uint32_t instId = scene.createInstance(Instance::Type::eMesh, meshId, matId, transform); assert(instId != -1); } void processMesh(const tinygltf::Model& model, oka::Scene& scene, const tinygltf::Mesh& mesh, const glm::float4x4& transform, const float globalScale) { using namespace std; cout << "Mesh name: " << mesh.name << endl; cout << "Primitive count: " << mesh.primitives.size() << endl; for (size_t i = 0; i < mesh.primitives.size(); ++i) { processPrimitive(model, scene, mesh.primitives[i], transform, globalScale); } } glm::float4x4 getTransform(const tinygltf::Node& node, const float globalScale) { if (node.matrix.empty()) { glm::float3 scale{ 1.0f }; if (!node.scale.empty()) { scale = glm::float3((float)node.scale[0], (float)node.scale[1], (float)node.scale[2]); // check that scale is uniform, otherwise we have to support it in shader // assert(scale.x == scale.y && scale.y == scale.z); } glm::quat rotation = glm::quat(1.0f, 0.0f, 0.0f, 0.0f); if (!node.rotation.empty()) { const float floatRotation[4] = { (float)node.rotation[3], (float)node.rotation[0], (float)node.rotation[1], (float)node.rotation[2], }; rotation = glm::make_quat(floatRotation); } glm::float3 translation{ 0.0f }; if (!node.translation.empty()) { translation = glm::float3((float)node.translation[0], (float)node.translation[1], (float)node.translation[2]); translation *= globalScale; } const glm::float4x4 translationMatrix = glm::translate(glm::float4x4(1.0f), translation); const glm::float4x4 rotationMatrix{ rotation }; const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), scale); const glm::float4x4 localTransform = translationMatrix * rotationMatrix * scaleMatrix; return localTransform; } else { glm::float4x4 localTransform = glm::make_mat4(node.matrix.data()); return localTransform; } } void processNode(const tinygltf::Model& model, oka::Scene& scene, const tinygltf::Node& node, const uint32_t currentNodeId, const glm::float4x4& baseTransform, const float globalScale) { using namespace std; cout << "Node name: " << node.name << endl; const glm::float4x4 localTransform = getTransform(node, globalScale); const glm::float4x4 globalTransform = baseTransform * localTransform; if (node.mesh != -1) // mesh exist { const tinygltf::Mesh& mesh = model.meshes[node.mesh]; processMesh(model, scene, mesh, globalTransform, globalScale); } else if (node.camera != -1) // camera node { glm::vec3 scale; glm::quat rotation; glm::vec3 translation; glm::vec3 skew; glm::vec4 perspective; glm::decompose(globalTransform, scale, rotation, translation, skew, perspective); rotation = glm::conjugate(rotation); scene.getCamera(node.camera).node = currentNodeId; scene.getCamera(node.camera).position = translation * scale; scene.getCamera(node.camera).mOrientation = rotation; scene.getCamera(node.camera).updateViewMatrix(); } for (int i = 0; i < node.children.size(); ++i) { scene.mNodes[node.children[i]].parent = currentNodeId; processNode(model, scene, model.nodes[node.children[i]], node.children[i], globalTransform, globalScale); } } oka::Scene::MaterialDescription convertToOmniPBR(const tinygltf::Model& model, const tinygltf::Material& material) { const std::string& fileUri = "OmniPBR.mdl"; const std::string& name = "OmniPBR"; oka::Scene::MaterialDescription materialDesc{}; materialDesc.file = fileUri; materialDesc.name = name; materialDesc.type = oka::Scene::MaterialDescription::Type::eMdl; materialDesc.color = glm::float3(material.pbrMetallicRoughness.baseColorFactor[0], material.pbrMetallicRoughness.baseColorFactor[1], material.pbrMetallicRoughness.baseColorFactor[2]); materialDesc.hasColor = true; oka::MaterialManager::Param colorParam = {}; colorParam.name = "diffuse_color_constant"; colorParam.type = oka::MaterialManager::Param::Type::eFloat3; colorParam.value.resize(sizeof(float) * 3); memcpy(colorParam.value.data(), glm::value_ptr(materialDesc.color), sizeof(float) * 3); materialDesc.params.push_back(colorParam); auto addFloat = [&](float value, const char* materialParamName) { oka::MaterialManager::Param param{}; param.name = materialParamName; param.type = oka::MaterialManager::Param::Type::eFloat; param.value.resize(sizeof(float)); *((float*)param.value.data()) = value; materialDesc.params.push_back(param); }; addFloat((float)material.pbrMetallicRoughness.roughnessFactor, "reflection_roughness_constant"); addFloat((float)material.pbrMetallicRoughness.metallicFactor, "metallic_constant"); auto addTexture = [&](int texId, const char* materialParamName) { const auto imageId = model.textures[texId].source; const auto textureUri = model.images[imageId].uri; oka::MaterialManager::Param paramTexture{}; paramTexture.name = materialParamName; paramTexture.type = oka::MaterialManager::Param::Type::eTexture; paramTexture.value.resize(textureUri.size()); memcpy(paramTexture.value.data(), textureUri.data(), textureUri.size()); materialDesc.params.push_back(paramTexture); }; auto texId = material.pbrMetallicRoughness.baseColorTexture.index; if (texId >= 0) { addTexture(texId, "diffuse_texture"); } auto normalTexId = material.normalTexture.index; if (normalTexId >= 0) { addTexture(normalTexId, "normalmap_texture"); } return materialDesc; } oka::Scene::MaterialDescription convertToOmniGlass(const tinygltf::Model& model, const tinygltf::Material& material) { oka::Scene::MaterialDescription materialDesc{}; materialDesc.file = "OmniGlass.mdl"; materialDesc.name = "OmniGlass"; materialDesc.type = oka::Scene::MaterialDescription::Type::eMdl; oka::MaterialManager::Param param{}; param.name = "enable_opacity"; param.type = oka::MaterialManager::Param::Type::eBool; param.value.resize(sizeof(bool)); *((bool*)param.value.data()) = true; materialDesc.params.push_back(param); // materialDesc.color = // glm::float3(material.pbrMetallicRoughness.baseColorFactor[0], material.pbrMetallicRoughness.baseColorFactor[1], // material.pbrMetallicRoughness.baseColorFactor[2]); // oka::MaterialManager::Param colorParam = {}; // colorParam.name = "glass_color"; // colorParam.type = oka::MaterialManager::Param::Type::eFloat3; // colorParam.value.resize(sizeof(float) * 3); // memcpy(colorParam.value.data(), glm::value_ptr(materialDesc.color), sizeof(float) * 3); // materialDesc.params.push_back(colorParam); auto addBool = [&](bool value, const char* materialParamName) { oka::MaterialManager::Param param{}; param.name = materialParamName; param.type = oka::MaterialManager::Param::Type::eBool; param.value.resize(sizeof(float)); *((bool*)param.value.data()) = value; materialDesc.params.push_back(param); }; addBool(false, "thin_walled"); auto addFloat = [&](float value, const char* materialParamName) { oka::MaterialManager::Param param{}; param.name = materialParamName; param.type = oka::MaterialManager::Param::Type::eFloat; param.value.resize(sizeof(float)); *((float*)param.value.data()) = value; materialDesc.params.push_back(param); }; addFloat((float)material.pbrMetallicRoughness.roughnessFactor, "frosting_roughness"); return materialDesc; } void loadMaterials(const tinygltf::Model& model, oka::Scene& scene) { for (const tinygltf::Material& material : model.materials) { if (material.alphaMode == "OPAQUE") { scene.addMaterial(convertToOmniPBR(model, material)); } else { scene.addMaterial(convertToOmniGlass(model, material)); } } } void loadCameras(const tinygltf::Model& model, oka::Scene& scene) { for (uint32_t i = 0; i < model.cameras.size(); ++i) { const tinygltf::Camera& cameraGltf = model.cameras[i]; if (strcmp(cameraGltf.type.c_str(), "perspective") == 0) { oka::Camera camera; camera.fov = cameraGltf.perspective.yfov * (180.0f / 3.1415926f); camera.znear = cameraGltf.perspective.znear; camera.zfar = cameraGltf.perspective.zfar; camera.name = cameraGltf.name; scene.addCamera(camera); } else { // not supported } } if (scene.getCameraCount() == 0) { // add default camera Camera camera; camera.updateViewMatrix(); scene.addCamera(camera); } } void loadAnimation(const tinygltf::Model& model, oka::Scene& scene) { std::vector<oka::Scene::Animation> animations; using namespace std; for (const tinygltf::Animation& animation : model.animations) { oka::Scene::Animation anim{}; cout << "Animation name: " << animation.name << endl; for (const tinygltf::AnimationSampler& sampler : animation.samplers) { oka::Scene::AnimationSampler samp{}; { const tinygltf::Accessor& accessor = model.accessors[sampler.input]; const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; assert(accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT); const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset]; const float* buf = static_cast<const float*>(dataPtr); for (size_t index = 0; index < accessor.count; index++) { samp.inputs.push_back(buf[index]); } for (auto input : samp.inputs) { if (input < anim.start) { anim.start = input; }; if (input > anim.end) { anim.end = input; } } } { const tinygltf::Accessor& accessor = model.accessors[sampler.output]; const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; assert(accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT); const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset]; switch (accessor.type) { case TINYGLTF_TYPE_VEC3: { const glm::vec3* buf = static_cast<const glm::vec3*>(dataPtr); for (size_t index = 0; index < accessor.count; index++) { samp.outputsVec4.push_back(glm::vec4(buf[index], 0.0f)); } break; } case TINYGLTF_TYPE_VEC4: { const glm::vec4* buf = static_cast<const glm::vec4*>(dataPtr); for (size_t index = 0; index < accessor.count; index++) { samp.outputsVec4.push_back(buf[index]); } break; } default: { std::cout << "unknown type" << std::endl; break; } } anim.samplers.push_back(samp); } } for (const tinygltf::AnimationChannel& channel : animation.channels) { oka::Scene::AnimationChannel chan{}; if (channel.target_path == "rotation") { chan.path = oka::Scene::AnimationChannel::PathType::ROTATION; } if (channel.target_path == "translation") { chan.path = oka::Scene::AnimationChannel::PathType::TRANSLATION; } if (channel.target_path == "scale") { chan.path = oka::Scene::AnimationChannel::PathType::SCALE; } if (channel.target_path == "weights") { std::cout << "weights not yet supported, skipping channel" << std::endl; continue; } chan.samplerIndex = channel.sampler; chan.node = channel.target_node; if (chan.node < 0) { std::cout << "skipping channel" << std::endl; continue; } anim.channels.push_back(chan); } animations.push_back(anim); } scene.mAnimations = animations; } void loadNodes(const tinygltf::Model& model, oka::Scene& scene, const float globalScale = 1.0f) { for (const auto& node : model.nodes) { oka::Scene::Node n{}; n.name = node.name; n.children = node.children; glm::float3 scale{ 1.0f }; if (!node.scale.empty()) { scale = glm::float3((float)node.scale[0], (float)node.scale[1], (float)node.scale[2]); // check that scale is uniform, otherwise we have to support it in shader // assert(scale.x == scale.y && scale.y == scale.z); } n.scale = scale; //glm::quat rotation = glm::quat(1.0f, 0.0f, 0.0f, 0.0f); glm::quat rotation = glm::quat_cast(glm::float4x4(1.0f)); if (!node.rotation.empty()) { const float floatRotation[4] = { (float)node.rotation[3], (float)node.rotation[0], (float)node.rotation[1], (float)node.rotation[2], }; rotation = glm::make_quat(floatRotation); } n.rotation = rotation; glm::float3 translation{ 0.0f }; if (!node.translation.empty()) { translation = glm::float3((float)node.translation[0], (float)node.translation[1], (float)node.translation[2]); translation *= globalScale; } n.translation = translation; scene.mNodes.push_back(n); } } oka::Scene::UniformLightDesc parseFromJson(const json& light) { oka::Scene::UniformLightDesc desc{}; const auto position = light["position"]; desc.position = glm::float3(position[0], position[1], position[2]); const auto orientation = light["orientation"]; desc.orientation = glm::float3(orientation[0], orientation[1], orientation[2]); desc.width = float(light["width"]); desc.height = light["height"]; const auto color = light["color"]; desc.color = glm::float3(color[0], color[1], color[2]); desc.intensity = float(light["intensity"]); desc.useXform = false; desc.type = 0; return desc; } bool loadLightsFromJson(const std::string& modelPath, oka::Scene& scene) { std::string fileName = modelPath.substr(0, modelPath.rfind('.')); // w/o extension std::string jsonPath = fileName + "_light" + ".json"; if (fs::exists(jsonPath)) { STRELKA_INFO("Found light file, loading lights from it"); std::ifstream i(jsonPath); json light; i >> light; for (const auto& light : light["lights"]) { Scene::UniformLightDesc desc = parseFromJson(light); scene.createLight(desc); } return true; } return false; } bool GltfLoader::loadGltf(const std::string& modelPath, oka::Scene& scene) { if (modelPath.empty()) { return false; } using namespace std; tinygltf::Model model; tinygltf::TinyGLTF gltf_ctx; std::string err; std::string warn; bool res = gltf_ctx.LoadASCIIFromFile(&model, &err, &warn, modelPath.c_str()); if (!res) { STRELKA_ERROR("Unable to load file: {}", modelPath); return res; } int sceneId = model.defaultScene; loadMaterials(model, scene); if (loadLightsFromJson(modelPath, scene) == false) { STRELKA_WARNING("No light is scene, adding default distant light"); oka::Scene::UniformLightDesc lightDesc {}; // lightDesc.xform = glm::mat4(1.0f); // lightDesc.useXform = true; lightDesc.useXform = false; lightDesc.position = glm::float3(0.0f, 0.0f, 0.0f); lightDesc.orientation = glm::float3(-45.0f, 15.0f, 0.0f); lightDesc.type = 3; // distant light lightDesc.halfAngle = 10.0f * 0.5f * (M_PI / 180.0f); lightDesc.intensity = 100000; lightDesc.color = glm::float3(1.0); scene.createLight(lightDesc); } loadCameras(model, scene); const float globalScale = 1.0f; loadNodes(model, scene, globalScale); for (int i = 0; i < model.scenes[sceneId].nodes.size(); ++i) { const int rootNodeIdx = model.scenes[sceneId].nodes[i]; processNode(model, scene, model.nodes[rootNodeIdx], rootNodeIdx, glm::float4x4(1.0f), globalScale); } loadAnimation(model, scene); return res; } } // namespace oka
25,554
C++
35.982634
184
0.604406
arhix52/Strelka/src/display/DisplayFactory.cpp
#ifdef __APPLE__ #include "metal/glfwdisplay.h" #else #include "opengl/glfwdisplay.h" #endif using namespace oka; Display* DisplayFactory::createDisplay() { return new glfwdisplay(); }
191
C++
13.76923
40
0.727749
arhix52/Strelka/src/display/Display.cpp
#include "Display.h" #include "imgui.h" #include "imgui_impl_glfw.h" using namespace oka; void Display::framebufferResizeCallback(GLFWwindow* window, int width, int height) { assert(window); if (width == 0 || height == 0) { return; } auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window)); // app->framebufferResized = true; ResizeHandler* handler = app->getResizeHandler(); if (handler) { handler->framebufferResize(width, height); } } void Display::keyCallback(GLFWwindow* window, [[maybe_unused]] int key, [[maybe_unused]] int scancode, [[maybe_unused]] int action, [[maybe_unused]] int mods) { assert(window); auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window)); InputHandler* handler = app->getInputHandler(); assert(handler); handler->keyCallback(key, scancode, action, mods); } void Display::mouseButtonCallback(GLFWwindow* window, [[maybe_unused]] int button, [[maybe_unused]] int action, [[maybe_unused]] int mods) { assert(window); auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window)); InputHandler* handler = app->getInputHandler(); if (handler) { handler->mouseButtonCallback(button, action, mods); } } void Display::handleMouseMoveCallback(GLFWwindow* window, [[maybe_unused]] double xpos, [[maybe_unused]] double ypos) { assert(window); auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window)); InputHandler* handler = app->getInputHandler(); if (handler) { handler->handleMouseMoveCallback(xpos, ypos); } } void Display::scrollCallback(GLFWwindow* window, [[maybe_unused]] double xoffset, [[maybe_unused]] double yoffset) { assert(window); } void Display::drawUI() { ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGuiIO& io = ImGui::GetIO(); const char* debugItems[] = { "None", "Normals", "Diffuse AOV", "Specular AOV" }; static int currentDebugItemId = 0; /* bool openFD = false; static uint32_t showPropertiesId = -1; static uint32_t lightId = -1; static bool isLight = false; static bool openInspector = false; const char* stratifiedSamplingItems[] = { "None", "Random", "Stratified", "Optimized" }; static int currentSamplingItemId = 1; */ ImGui::Begin("Menu:"); // begin window if (ImGui::BeginCombo("Debug view", debugItems[currentDebugItemId])) { for (int n = 0; n < IM_ARRAYSIZE(debugItems); n++) { bool is_selected = (currentDebugItemId == n); if (ImGui::Selectable(debugItems[n], is_selected)) { currentDebugItemId = n; } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } mCtx->mSettingsManager->setAs<uint32_t>("render/pt/debug", currentDebugItemId); if (ImGui::TreeNode("Path Tracer")) { const char* rectlightSamplingMethodItems[] = { "Uniform", "Advanced" }; static int currentRectlightSamplingMethodItemId = 0; if (ImGui::BeginCombo("Rect Light Sampling", rectlightSamplingMethodItems[currentRectlightSamplingMethodItemId])) { for (int n = 0; n < IM_ARRAYSIZE(rectlightSamplingMethodItems); n++) { bool is_selected = (currentRectlightSamplingMethodItemId == n); if (ImGui::Selectable(rectlightSamplingMethodItems[n], is_selected)) { currentRectlightSamplingMethodItemId = n; } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } mCtx->mSettingsManager->setAs<uint32_t>( "render/pt/rectLightSamplingMethod", currentRectlightSamplingMethodItemId); uint32_t maxDepth = mCtx->mSettingsManager->getAs<uint32_t>("render/pt/depth"); ImGui::SliderInt("Max Depth", (int*)&maxDepth, 1, 16); mCtx->mSettingsManager->setAs<uint32_t>("render/pt/depth", maxDepth); uint32_t sppTotal = mCtx->mSettingsManager->getAs<uint32_t>("render/pt/sppTotal"); ImGui::SliderInt("SPP Total", (int*)&sppTotal, 1, 10000); mCtx->mSettingsManager->setAs<uint32_t>("render/pt/sppTotal", sppTotal); uint32_t sppSubframe = mCtx->mSettingsManager->getAs<uint32_t>("render/pt/spp"); ImGui::SliderInt("SPP Subframe", (int*)&sppSubframe, 1, 32); mCtx->mSettingsManager->setAs<uint32_t>("render/pt/spp", sppSubframe); bool enableAccumulation = mCtx->mSettingsManager->getAs<bool>("render/pt/enableAcc"); ImGui::Checkbox("Enable Path Tracer Acc", &enableAccumulation); mCtx->mSettingsManager->setAs<bool>("render/pt/enableAcc", enableAccumulation); /* if (ImGui::BeginCombo("Stratified Sampling", stratifiedSamplingItems[currentSamplingItemId])) { for (int n = 0; n < IM_ARRAYSIZE(stratifiedSamplingItems); n++) { bool is_selected = (currentSamplingItemId == n); if (ImGui::Selectable(stratifiedSamplingItems[n], is_selected)) { currentSamplingItemId = n; } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } mCtx->mSettingsManager->setAs<uint32_t>("render/pt/stratifiedSamplingType", currentSamplingItemId); */ ImGui::TreePop(); } if (ImGui::Button("Capture Screen")) { mCtx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", true); } float cameraSpeed = mCtx->mSettingsManager->getAs<float>("render/cameraSpeed"); ImGui::InputFloat("Camera Speed", (float*)&cameraSpeed, 0.5); mCtx->mSettingsManager->setAs<float>("render/cameraSpeed", cameraSpeed); const char* tonemapItems[] = { "None", "Reinhard", "ACES", "Filmic" }; static int currentTonemapItemId = 1; if (ImGui::BeginCombo("Tonemap", tonemapItems[currentTonemapItemId])) { for (int n = 0; n < IM_ARRAYSIZE(tonemapItems); n++) { bool is_selected = (currentTonemapItemId == n); if (ImGui::Selectable(tonemapItems[n], is_selected)) { currentTonemapItemId = n; } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } mCtx->mSettingsManager->setAs<uint32_t>("render/pt/tonemapperType", currentTonemapItemId); float gamma = mCtx->mSettingsManager->getAs<float>("render/post/gamma"); ImGui::InputFloat("Gamma", (float*)&gamma, 0.5); mCtx->mSettingsManager->setAs<float>("render/post/gamma", gamma); float materialRayTmin = mCtx->mSettingsManager->getAs<float>("render/pt/dev/materialRayTmin"); ImGui::InputFloat("Material ray T min", (float*)&materialRayTmin, 0.1); mCtx->mSettingsManager->setAs<float>("render/pt/dev/materialRayTmin", materialRayTmin); float shadowRayTmin = mCtx->mSettingsManager->getAs<float>("render/pt/dev/shadowRayTmin"); ImGui::InputFloat("Shadow ray T min", (float*)&shadowRayTmin, 0.1); mCtx->mSettingsManager->setAs<float>("render/pt/dev/shadowRayTmin", shadowRayTmin); /* bool enableUpscale = mCtx->mSettingsManager->getAs<bool>("render/pt/enableUpscale"); ImGui::Checkbox("Enable Upscale", &enableUpscale); mCtx->mSettingsManager->setAs<bool>("render/pt/enableUpscale", enableUpscale); float upscaleFactor = 0.0f; if (enableUpscale) { upscaleFactor = 0.5f; } else { upscaleFactor = 1.0f; } mCtx->mSettingsManager->setAs<float>("render/pt/upscaleFactor", upscaleFactor); if (ImGui::Button("Capture Screen")) { mCtx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", true); } // bool isRecreate = ImGui::Button("Recreate BVH"); // renderConfig.recreateBVH = isRecreate ? true : false; */ ImGui::End(); // end window // Rendering ImGui::Render(); }
8,486
C++
34.3625
121
0.603936
arhix52/Strelka/src/display/metal/metalcpphelp.cpp
#define NS_PRIVATE_IMPLEMENTATION #define MTL_PRIVATE_IMPLEMENTATION // #define MTK_PRIVATE_IMPLEMENTATION #define CA_PRIVATE_IMPLEMENTATION #include <Metal/Metal.hpp> #include <QuartzCore/QuartzCore.hpp>
205
C++
28.428567
37
0.819512
arhix52/Strelka/src/display/metal/glfwdisplay.h
#pragma once #define GLFW_INCLUDE_NONE #define GLFW_EXPOSE_NATIVE_COCOA #include "Display.h" #include <Metal/Metal.hpp> #include <QuartzCore/QuartzCore.hpp> namespace oka { class glfwdisplay : public Display { public: glfwdisplay() { } virtual ~glfwdisplay() { } virtual void init(int width, int height, oka::SharedContext* ctx) override; virtual void destroy() override; virtual void onBeginFrame() override; virtual void onEndFrame() override; virtual void drawFrame(ImageBuffer& result) override; virtual void drawUI() override; private: static constexpr size_t kMaxFramesInFlight = 3; MTL::Device* _pDevice; MTL::CommandQueue* _pCommandQueue; MTL::Library* _pShaderLibrary; MTL::RenderPipelineState* _pPSO; MTL::Texture* mTexture; uint32_t mTexWidth = 32; uint32_t mTexHeight = 32; dispatch_semaphore_t _semaphore; CA::MetalLayer* layer; MTL::RenderPassDescriptor *renderPassDescriptor; MTL::Texture* buildTexture(uint32_t width, uint32_t heigth); void buildShaders(); MTL::CommandBuffer* commandBuffer; MTL::RenderCommandEncoder* renderEncoder; CA::MetalDrawable* drawable; }; } // namespace oka
1,226
C
22.596153
79
0.700653
arhix52/Strelka/src/display/opengl/glfwdisplay.h
#pragma once #include <glad/glad.h> #include "Display.h" namespace oka { class glfwdisplay : public Display { private: /* data */ GLuint m_render_tex = 0u; GLuint m_program = 0u; GLint m_render_tex_uniform_loc = -1; GLuint m_quad_vertex_buffer = 0; GLuint m_dislpayPbo = 0; static const std::string s_vert_source; static const std::string s_frag_source; public: glfwdisplay(/* args */); virtual ~glfwdisplay(); public: virtual void init(int width, int height, oka::SharedContext* ctx) override; void destroy(); void onBeginFrame(); void onEndFrame(); void drawFrame(ImageBuffer& result); void drawUI(); void display(const int32_t screen_res_x, const int32_t screen_res_y, const int32_t framebuf_res_x, const int32_t framebuf_res_y, const uint32_t pbo) const; }; } // namespace oka
927
C
20.090909
79
0.618123
arhix52/Strelka/src/display/opengl/glfwdisplay.cpp
#include "glfwdisplay.h" #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #define GL_SILENCE_DEPRECATION #include <sstream> using namespace oka; inline const char* getGLErrorString(GLenum error) { switch (error) { case GL_NO_ERROR: return "No error"; case GL_INVALID_ENUM: return "Invalid enum"; case GL_INVALID_VALUE: return "Invalid value"; case GL_INVALID_OPERATION: return "Invalid operation"; // case GL_STACK_OVERFLOW: return "Stack overflow"; // case GL_STACK_UNDERFLOW: return "Stack underflow"; case GL_OUT_OF_MEMORY: return "Out of memory"; // case GL_TABLE_TOO_LARGE: return "Table too large"; default: return "Unknown GL error"; } } inline void glCheck(const char* call, const char* file, unsigned int line) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { std::stringstream ss; ss << "GL error " << getGLErrorString(err) << " at " << file << "(" << line << "): " << call << '\n'; std::cerr << ss.str() << std::endl; // throw Exception(ss.str().c_str()); assert(0); } } #define GL_CHECK(call) \ do \ { \ call; \ glCheck(#call, __FILE__, __LINE__); \ } while (false) const std::string glfwdisplay::s_vert_source = R"( #version 330 core layout(location = 0) in vec3 vertexPosition_modelspace; out vec2 UV; void main() { gl_Position = vec4(vertexPosition_modelspace,1); UV = (vec2( vertexPosition_modelspace.x, vertexPosition_modelspace.y )+vec2(1,1))/2.0; } )"; const std::string glfwdisplay::s_frag_source = R"( #version 330 core in vec2 UV; out vec3 color; uniform sampler2D render_tex; uniform bool correct_gamma; void main() { color = texture( render_tex, UV ).xyz; } )"; GLuint createGLShader(const std::string& source, GLuint shader_type) { GLuint shader = glCreateShader(shader_type); { const GLchar* source_data = reinterpret_cast<const GLchar*>(source.data()); glShaderSource(shader, 1, &source_data, nullptr); glCompileShader(shader); GLint is_compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &is_compiled); if (is_compiled == GL_FALSE) { GLint max_length = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_length); std::string info_log(max_length, '\0'); GLchar* info_log_data = reinterpret_cast<GLchar*>(&info_log[0]); glGetShaderInfoLog(shader, max_length, nullptr, info_log_data); glDeleteShader(shader); std::cerr << "Compilation of shader failed: " << info_log << std::endl; return 0; } } // GL_CHECK_ERRORS(); return shader; } GLuint createGLProgram(const std::string& vert_source, const std::string& frag_source) { GLuint vert_shader = createGLShader(vert_source, GL_VERTEX_SHADER); if (vert_shader == 0) return 0; GLuint frag_shader = createGLShader(frag_source, GL_FRAGMENT_SHADER); if (frag_shader == 0) { glDeleteShader(vert_shader); return 0; } GLuint program = glCreateProgram(); glAttachShader(program, vert_shader); glAttachShader(program, frag_shader); glLinkProgram(program); GLint is_linked = 0; glGetProgramiv(program, GL_LINK_STATUS, &is_linked); if (is_linked == GL_FALSE) { GLint max_length = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &max_length); std::string info_log(max_length, '\0'); GLchar* info_log_data = reinterpret_cast<GLchar*>(&info_log[0]); glGetProgramInfoLog(program, max_length, nullptr, info_log_data); std::cerr << "Linking of program failed: " << info_log << std::endl; glDeleteProgram(program); glDeleteShader(vert_shader); glDeleteShader(frag_shader); return 0; } glDetachShader(program, vert_shader); glDetachShader(program, frag_shader); // GL_CHECK_ERRORS(); return program; } GLint getGLUniformLocation(GLuint program, const std::string& name) { GLint loc = glGetUniformLocation(program, name.c_str()); return loc; } glfwdisplay::glfwdisplay(/* args */) { } glfwdisplay::~glfwdisplay() { } void glfwdisplay::init(int width, int height, oka::SharedContext* ctx) { mWindowWidth = width; mWindowHeight = height; mCtx = ctx; glfwInit(); const char* glsl_version = "#version 130"; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); mWindow = glfwCreateWindow(mWindowWidth, mWindowHeight, "Strelka", nullptr, nullptr); glfwSetWindowUserPointer(mWindow, this); glfwSetFramebufferSizeCallback(mWindow, framebufferResizeCallback); glfwSetKeyCallback(mWindow, keyCallback); glfwSetMouseButtonCallback(mWindow, mouseButtonCallback); glfwSetCursorPosCallback(mWindow, handleMouseMoveCallback); glfwSetScrollCallback(mWindow, scrollCallback); glfwMakeContextCurrent(mWindow); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; assert(0); } GLuint m_vertex_array; GL_CHECK(glGenVertexArrays(1, &m_vertex_array)); GL_CHECK(glBindVertexArray(m_vertex_array)); m_program = createGLProgram(s_vert_source, s_frag_source); m_render_tex_uniform_loc = getGLUniformLocation(m_program, "render_tex"); GL_CHECK(glGenTextures(1, &m_render_tex)); GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_render_tex)); GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; GL_CHECK(glGenBuffers(1, &m_quad_vertex_buffer)); GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_quad_vertex_buffer)); GL_CHECK(glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW)); // GL_CHECK_ERRORS(); // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; // io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); // ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(mWindow, true); ImGui_ImplOpenGL3_Init(glsl_version); } void glfwdisplay::display(const int32_t screen_res_x, const int32_t screen_res_y, const int32_t framebuf_res_x, const int32_t framebuf_res_y, const uint32_t pbo) const { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); GL_CHECK(glViewport(0, 0, framebuf_res_x, framebuf_res_y)); GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); GL_CHECK(glUseProgram(m_program)); // Bind our texture in Texture Unit 0 GL_CHECK(glActiveTexture(GL_TEXTURE0)); GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_render_tex)); GL_CHECK(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo)); GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 4)); // TODO!!!!!! size_t elmt_size = 4 * sizeof(float); // pixelFormatSize(m_image_format); if (elmt_size % 8 == 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 8); else if (elmt_size % 4 == 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 4); else if (elmt_size % 2 == 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 2); else glPixelStorei(GL_UNPACK_ALIGNMENT, 1); bool convertToSrgb = true; // if (m_image_format == BufferImageFormat::UNSIGNED_BYTE4) // { // // input is assumed to be in srgb since it is only 1 byte per channel in // // size // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, screen_res_x, screen_res_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); // convertToSrgb = false; // } // else if (m_image_format == BufferImageFormat::FLOAT3) // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, screen_res_x, screen_res_y, 0, GL_RGB, GL_FLOAT, nullptr); // else if (m_image_format == BufferImageFormat::FLOAT4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, screen_res_x, screen_res_y, 0, GL_RGBA, GL_FLOAT, nullptr); convertToSrgb = false; // else // throw Exception("Unknown buffer format"); GL_CHECK(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0)); GL_CHECK(glUniform1i(m_render_tex_uniform_loc, 0)); // 1st attribute buffer : vertices GL_CHECK(glEnableVertexAttribArray(0)); GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_quad_vertex_buffer)); GL_CHECK(glVertexAttribPointer(0, // attribute 0. No particular reason for 0, // but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset )); if (convertToSrgb) GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB)); else GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB)); // Draw the triangles ! GL_CHECK(glDrawArrays(GL_TRIANGLES, 0, 6)); // 2*3 indices starting at 0 -> 2 triangles GL_CHECK(glDisableVertexAttribArray(0)); GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB)); // GL_CHECK_ERRORS(); } void glfwdisplay::drawFrame(ImageBuffer& result) { glClear(GL_COLOR_BUFFER_BIT); int framebuf_res_x = 0, framebuf_res_y = 0; glfwGetFramebufferSize(mWindow, &framebuf_res_x, &framebuf_res_y); if (m_dislpayPbo == 0) { GL_CHECK(glGenBuffers(1, &m_dislpayPbo)); } GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_dislpayPbo)); GL_CHECK(glBufferData(GL_ARRAY_BUFFER, result.dataSize, result.data, GL_STREAM_DRAW)); GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0)); display(result.width, result.height, framebuf_res_x, framebuf_res_y, m_dislpayPbo); } void glfwdisplay::destroy() { } void glfwdisplay::onBeginFrame() { } void glfwdisplay::onEndFrame() { glfwSwapBuffers(mWindow); } void glfwdisplay::drawUI() { ImGui_ImplOpenGL3_NewFrame(); Display::drawUI(); int display_w, display_h; glfwGetFramebufferSize(mWindow, &display_w, &display_h); glViewport(0, 0, display_w, display_h); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); }
11,703
C++
31.065753
122
0.604375
arhix52/Strelka/include/HdStrelka/RendererPlugin.h
#pragma once #include <pxr/imaging/hd/rendererPlugin.h> #include <memory> #include <log/logmanager.h> #include "MaterialNetworkTranslator.h" PXR_NAMESPACE_OPEN_SCOPE class HdStrelkaRendererPlugin final : public HdRendererPlugin { public: HdStrelkaRendererPlugin(); ~HdStrelkaRendererPlugin() override; public: HdRenderDelegate* CreateRenderDelegate() override; HdRenderDelegate* CreateRenderDelegate(const HdRenderSettingsMap& settingsMap) override; void DeleteRenderDelegate(HdRenderDelegate* renderDelegate) override; bool IsSupported(bool gpuEnabled = true) const override; private: oka::Logmanager mLoggerManager; std::unique_ptr<MaterialNetworkTranslator> m_translator; bool m_isSupported; }; PXR_NAMESPACE_CLOSE_SCOPE
772
C
21.085714
92
0.782383
arhix52/Strelka/include/materialmanager/mdlLogger.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include <mi/base/interface_implement.h> #include <mi/base/ilogger.h> #include <mi/neuraylib/imdl_execution_context.h> namespace oka { class MdlLogger : public mi::base::Interface_implement<mi::base::ILogger> { public: void message(mi::base::Message_severity level, const char* moduleCategory, const mi::base::Message_details& details, const char* message) override; void message(mi::base::Message_severity level, const char* moduleCategory, const char* message) override; void message(mi::base::Message_severity level, const char* message); void flushContextMessages(mi::neuraylib::IMdl_execution_context* context); }; }
1,561
C
36.190475
106
0.647662
arhix52/Strelka/include/materialmanager/materialmanager.h
#pragma once #include <memory> #include <stdint.h> #include <string> #include <vector> namespace oka { class MaterialManager { class Context; std::unique_ptr<Context> mContext; public: struct Module; struct MaterialInstance; struct CompiledMaterial; struct TargetCode; struct TextureDescription; bool addMdlSearchPath(const char* paths[], uint32_t numPaths); Module* createModule(const char* file); Module* createMtlxModule(const char* file); void destroyModule(Module* module); MaterialInstance* createMaterialInstance(Module* module, const char* materialName); void destroyMaterialInstance(MaterialInstance* material); struct Param { enum class Type : uint32_t { eFloat = 0, eInt, eBool, eFloat2, eFloat3, eFloat4, eTexture }; Type type; std::string name; std::vector<uint8_t> value; }; void dumpParams(const TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material); bool setParam(TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material, const Param& param); TextureDescription* createTextureDescription(const char* name, const char* gamma); const char* getTextureDbName(TextureDescription* texDesc); CompiledMaterial* compileMaterial(MaterialInstance* matInstance); void destroyCompiledMaterial(CompiledMaterial* compMaterial); const char* getName(CompiledMaterial* compMaterial); TargetCode* generateTargetCode(CompiledMaterial** materials, const uint32_t numMaterials); const char* getShaderCode(const TargetCode* targetCode, uint32_t materialId); uint32_t getReadOnlyBlockSize(const TargetCode* targetCode); const uint8_t* getReadOnlyBlockData(const TargetCode* targetCode); uint32_t getArgBufferSize(const TargetCode* targetCode); const uint8_t* getArgBufferData(const TargetCode* targetCode); uint32_t getResourceInfoSize(const TargetCode* targetCode); const uint8_t* getResourceInfoData(const TargetCode* targetCode); int registerResource(TargetCode* targetCode, int index); uint32_t getMdlMaterialSize(const TargetCode* targetCode); const uint8_t* getMdlMaterialData(const TargetCode* targetCode); uint32_t getArgBlockOffset(const TargetCode* targetCode, uint32_t materialId); uint32_t getReadOnlyOffset(const TargetCode* targetCode, uint32_t materialId); uint32_t getTextureCount(const TargetCode* targetCode, uint32_t materialId); const char* getTextureName(const TargetCode* targetCode, uint32_t materialId, uint32_t index); const float* getTextureData(const TargetCode* targetCode, uint32_t materialId, uint32_t index); const char* getTextureType(const TargetCode* targetCode, uint32_t materialId, uint32_t index); uint32_t getTextureWidth(const TargetCode* targetCode, uint32_t materialId, uint32_t index); uint32_t getTextureHeight(const TargetCode* targetCode, uint32_t materialId, uint32_t index); uint32_t getTextureBytesPerTexel(const TargetCode* targetCode, uint32_t materialId, uint32_t index); MaterialManager(); ~MaterialManager(); }; } // namespace oka
3,244
C
34.65934
112
0.733046
arhix52/Strelka/include/materialmanager/mdlPtxCodeGen.h
#pragma once #include "mdlLogger.h" #include "mdlRuntime.h" #include <MaterialXCore/Document.h> #include <MaterialXFormat/File.h> #include <MaterialXGenShader/ShaderGenerator.h> #include <mi/mdl_sdk.h> namespace oka { class MdlPtxCodeGen { public: explicit MdlPtxCodeGen(){}; bool init(MdlRuntime& runtime); struct InternalMaterialInfo { mi::Size argument_block_index; }; bool setOptionBinary(const char* name, const char* data, size_t size); mi::base::Handle<const mi::neuraylib::ITarget_code> translate( const mi::neuraylib::ICompiled_material* material, std::string& ptxSrc, InternalMaterialInfo& internalsInfo); mi::base::Handle<const mi::neuraylib::ITarget_code> translate( const std::vector<const mi::neuraylib::ICompiled_material*>& materials, std::string& ptxSrc, std::vector<InternalMaterialInfo>& internalsInfo); private: bool appendMaterialToLinkUnit(uint32_t idx, const mi::neuraylib::ICompiled_material* compiledMaterial, mi::neuraylib::ILink_unit* linkUnit, mi::Size& argBlockIndex); std::unique_ptr<MdlNeurayLoader> mLoader; mi::base::Handle<MdlLogger> mLogger; mi::base::Handle<mi::neuraylib::IMdl_backend> mBackend; mi::base::Handle<mi::neuraylib::IDatabase> mDatabase; mi::base::Handle<mi::neuraylib::ITransaction> mTransaction; mi::base::Handle<mi::neuraylib::IMdl_execution_context> mContext; }; } // namespace oka
1,564
C
29.096153
92
0.663683
arhix52/Strelka/include/materialmanager/mdlNeurayLoader.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include <mi/base/handle.h> #include <mi/neuraylib/ineuray.h> namespace oka { class MdlNeurayLoader { public: MdlNeurayLoader(); ~MdlNeurayLoader(); public: bool init(const char* resourcePath, const char* imagePluginPath); mi::base::Handle<mi::neuraylib::INeuray> getNeuray() const; private: bool loadDso(const char* resourcePath); bool loadNeuray(); bool loadPlugin(const char* imagePluginPath); void unloadDso(); private: void* mDsoHandle; mi::base::Handle<mi::neuraylib::INeuray> mNeuray; }; }
1,359
C
29.222222
106
0.668138
arhix52/Strelka/include/materialmanager/mdlMaterialCompiler.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include <string> #include <mi/base/handle.h> #include <mi/neuraylib/icompiled_material.h> #include <mi/neuraylib/idatabase.h> #include <mi/neuraylib/itransaction.h> #include <mi/neuraylib/imaterial_instance.h> #include <mi/neuraylib/imdl_impexp_api.h> #include <mi/neuraylib/imdl_execution_context.h> #include <mi/neuraylib/imdl_factory.h> #include "mdlRuntime.h" namespace oka { class MdlMaterialCompiler { public: MdlMaterialCompiler(MdlRuntime& runtime); public: bool createModule(const std::string& identifier, std::string& moduleName); bool createMaterialInstace(const char* moduleName, const char* identifier, mi::base::Handle<mi::neuraylib::IFunction_call>& matInstance); bool compileMaterial(mi::base::Handle<mi::neuraylib::IFunction_call>& instance, mi::base::Handle<mi::neuraylib::ICompiled_material>& compiledMaterial); mi::base::Handle<mi::neuraylib::IMdl_factory>& getFactory(); mi::base::Handle<mi::neuraylib::ITransaction>& getTransaction(); private: mi::base::Handle<MdlLogger> mLogger; mi::base::Handle<mi::neuraylib::IDatabase> mDatabase; mi::base::Handle<mi::neuraylib::ITransaction> mTransaction; mi::base::Handle<mi::neuraylib::IMdl_factory> mFactory; mi::base::Handle<mi::neuraylib::IMdl_impexp_api> mImpExpApi; }; }
2,165
C
35.711864
106
0.687298
arhix52/Strelka/include/materialmanager/mdlRuntime.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include "mdlLogger.h" #include "mdlNeurayLoader.h" #include <mi/base/handle.h> #include <mi/neuraylib/idatabase.h> #include <mi/neuraylib/itransaction.h> #include <mi/neuraylib/imdl_backend_api.h> #include <mi/neuraylib/imdl_impexp_api.h> #include <mi/neuraylib/imdl_factory.h> #include <mi/mdl_sdk.h> #include <memory> #include <vector> namespace oka { class MdlRuntime { public: MdlRuntime(); ~MdlRuntime(); public: bool init(const char* paths[], uint32_t numPaths, const char* neurayPath, const char* imagePluginPath); mi::base::Handle<MdlLogger> getLogger(); mi::base::Handle<mi::neuraylib::IDatabase> getDatabase(); mi::base::Handle<mi::neuraylib::ITransaction> getTransaction(); mi::base::Handle<mi::neuraylib::IMdl_factory> getFactory(); mi::base::Handle<mi::neuraylib::IMdl_impexp_api> getImpExpApi(); mi::base::Handle<mi::neuraylib::IMdl_backend_api> getBackendApi(); mi::base::Handle<mi::neuraylib::INeuray> getNeuray(); mi::base::Handle<mi::neuraylib::IMdl_configuration> getConfig(); std::unique_ptr<MdlNeurayLoader> mLoader; private: mi::base::Handle<MdlLogger> mLogger; mi::base::Handle<mi::neuraylib::IDatabase> mDatabase; mi::base::Handle<mi::neuraylib::ITransaction> mTransaction; mi::base::Handle<mi::neuraylib::IMdl_factory> mFactory; mi::base::Handle<mi::neuraylib::IMdl_backend_api> mBackendApi; mi::base::Handle<mi::neuraylib::IMdl_impexp_api> mImpExpApi; mi::base::Handle<mi::neuraylib::IMdl_configuration> mConfig; }; } // namespace oka
2,369
C
34.373134
107
0.68721
arhix52/Strelka/include/materialmanager/mtlxMdlCodeGen.h
// Copyright (C) 2021 Pablo Delgado Krämer // // 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 <https://www.gnu.org/licenses/>. #pragma once #include <stdint.h> #include <string> #include <MaterialXCore/Document.h> #include <MaterialXFormat/File.h> #include <MaterialXGenShader/ShaderGenerator.h> #include "mdlRuntime.h" namespace oka { class MtlxMdlCodeGen { public: explicit MtlxMdlCodeGen(const char* mtlxlibPath, MdlRuntime* mdlRuntime); public: bool translate(const char* mtlxSrc, std::string& mdlSrc, std::string& subIdentifier); private: const MaterialX::FileSearchPath mMtlxlibPath; MaterialX::DocumentPtr mStdLib; MaterialX::ShaderGeneratorPtr mShaderGen; MdlRuntime* mMdlRuntime; }; }
1,400
C
30.840908
106
0.695714
arhix52/Strelka/include/render/buffer.h
#pragma once #include "common.h" #include <stdint.h> #include <vector> namespace oka { enum class BufferFormat : char { UNSIGNED_BYTE4, FLOAT4, FLOAT3 }; struct BufferDesc { uint32_t width; uint32_t height; BufferFormat format; }; class Buffer { public: virtual ~Buffer() = default; virtual void resize(uint32_t width, uint32_t height) = 0; virtual void* map() = 0; virtual void unmap() = 0; uint32_t width() const { return mWidth; } uint32_t height() const { return mHeight; } // Get output buffer virtual void* getHostPointer() { return mHostData.data(); } virtual size_t getHostDataSize() { return mHostData.size(); } static size_t getElementSize(BufferFormat format) { switch (format) { case BufferFormat::FLOAT4: return 4 * sizeof(float); break; case BufferFormat::FLOAT3: return 3 * sizeof(float); break; case BufferFormat::UNSIGNED_BYTE4: return 4 * sizeof(char); break; default: break; } assert(0); return 0; } size_t getElementSize() const { return Buffer::getElementSize(mFormat); } BufferFormat getFormat() const { return mFormat; } protected: uint32_t mWidth = 0u; uint32_t mHeight = 0u; BufferFormat mFormat; std::vector<char> mHostData; }; struct ImageBuffer { void* data = nullptr; size_t dataSize = 0; unsigned int width = 0; unsigned int height = 0; BufferFormat pixel_format; }; } // namespace oka
1,699
C
16
61
0.567393
arhix52/Strelka/include/render/Lights.h
#pragma once #include <vector_types.h> #include <sutil/vec_math.h> struct UniformLight { float4 points[4]; float4 color; float4 normal; int type; float halfAngle; float pad0; float pad1; }; struct LightSampleData { float3 pointOnLight; float pdf; float3 normal; float area; float3 L; float distToLight; }; __forceinline__ __device__ float misWeightBalance(const float a, const float b) { return 1.0f / ( 1.0f + (b / a) ); } static __inline__ __device__ float calcLightArea(const UniformLight& l) { float area = 0.0f; if (l.type == 0) // rectangle area { float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]); float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]); area = length(cross(e1, e2)); } else if (l.type == 1) // disc area { area = M_PIf * l.points[0].x * l.points[0].x; // pi * radius^2 } else if (l.type == 2) // sphere area { area = 4.0f * M_PIf * l.points[0].x * l.points[0].x; // 4 * pi * radius^2 } return area; } static __inline__ __device__ float3 calcLightNormal(const UniformLight& l, const float3 hitPoint) { float3 norm = make_float3(0.0f); if (l.type == 0) { float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]); float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]); norm = -normalize(cross(e1, e2)); } else if (l.type == 1) { norm = make_float3(l.normal); } else if (l.type == 2) { norm = normalize(hitPoint - make_float3(l.points[1])); } return norm; } static __inline__ __device__ void fillLightData(const UniformLight& l, const float3 hitPoint, LightSampleData& lightSampleData) { lightSampleData.area = calcLightArea(l); lightSampleData.normal = calcLightNormal(l, hitPoint); const float3 toLight = lightSampleData.pointOnLight - hitPoint; const float lenToLight = length(toLight); lightSampleData.L = toLight / lenToLight; lightSampleData.distToLight = lenToLight; } struct SphQuad { float3 o, x, y, z; float z0, z0sq; float x0, y0, y0sq; // rectangle coords in ’R’ float x1, y1, y1sq; float b0, b1, b0sq, k; float S; }; // Precomputation of constants for the spherical rectangle Q. static __device__ SphQuad init(const UniformLight& l, const float3 o) { SphQuad squad; float3 ex = make_float3(l.points[1]) - make_float3(l.points[0]); float3 ey = make_float3(l.points[3]) - make_float3(l.points[0]); float3 s = make_float3(l.points[0]); float exl = length(ex); float eyl = length(ey); squad.o = o; squad.x = ex / exl; squad.y = ey / eyl; squad.z = cross(squad.x, squad.y); // compute rectangle coords in local reference system float3 d = s - o; squad.z0 = dot(d, squad.z); // flip ’z’ to make it point against ’Q’ if (squad.z0 > 0) { squad.z *= -1; squad.z0 *= -1; } squad.z0sq = squad.z0 * squad.z0; squad.x0 = dot(d, squad.x); squad.y0 = dot(d, squad.y); squad.x1 = squad.x0 + exl; squad.y1 = squad.y0 + eyl; squad.y0sq = squad.y0 * squad.y0; squad.y1sq = squad.y1 * squad.y1; // create vectors to four vertices float3 v00 = { squad.x0, squad.y0, squad.z0 }; float3 v01 = { squad.x0, squad.y1, squad.z0 }; float3 v10 = { squad.x1, squad.y0, squad.z0 }; float3 v11 = { squad.x1, squad.y1, squad.z0 }; // compute normals to edges float3 n0 = normalize(cross(v00, v10)); float3 n1 = normalize(cross(v10, v11)); float3 n2 = normalize(cross(v11, v01)); float3 n3 = normalize(cross(v01, v00)); // compute internal angles (gamma_i) float g0 = acos(-dot(n0, n1)); float g1 = acos(-dot(n1, n2)); float g2 = acos(-dot(n2, n3)); float g3 = acos(-dot(n3, n0)); // compute predefined constants squad.b0 = n0.z; squad.b1 = n2.z; squad.b0sq = squad.b0 * squad.b0; squad.k = 2.0f * M_PIf - g2 - g3; // compute solid angle from internal angles squad.S = g0 + g1 - squad.k; return squad; } static __device__ float3 SphQuadSample(const SphQuad& squad, const float2 uv) { float u = uv.x; float v = uv.y; // 1. compute cu float au = u * squad.S + squad.k; float fu = (cosf(au) * squad.b0 - squad.b1) / sinf(au); float cu = 1.0f / sqrtf(fu * fu + squad.b0sq) * (fu > 0.0f ? 1.0f : -1.0f); cu = clamp(cu, -1.0f, 1.0f); // avoid NaNs // 2. compute xu float xu = -(cu * squad.z0) / sqrtf(1.0f - cu * cu); xu = clamp(xu, squad.x0, squad.x1); // avoid Infs // 3. compute yv float d = sqrtf(xu * xu + squad.z0sq); float h0 = squad.y0 / sqrtf(d * d + squad.y0sq); float h1 = squad.y1 / sqrtf(d * d + squad.y1sq); float hv = h0 + v * (h1 - h0); float hv2 = hv * hv; float eps = 1e-5f; float yv = (hv < 1.0f - eps) ? (hv * d) / sqrtf(1 - hv2) : squad.y1; // 4. transform (xu, yv, z0) to world coords return (squad.o + xu * squad.x + yv * squad.y + squad.z0 * squad.z); } static __inline__ __device__ float getLightPdf(const UniformLight& l, const float3 hitPoint) { SphQuad quad = init(l, hitPoint); if (quad.S <= 0.0f) { return 0.0f; } return 1.0f / quad.S; } static __inline__ __device__ float getRectLightPdf(const UniformLight& l, const float3 lightHitPoint, const float3 surfaceHitPoint) { LightSampleData lightSampleData {}; lightSampleData.pointOnLight = lightHitPoint; fillLightData(l, surfaceHitPoint, lightSampleData); lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight / (dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area); return lightSampleData.pdf; } static __inline__ __device__ float getDirectLightPdf(float angle) { return 1.0f / (2.0f * M_PIf * (1.0f - cos(angle))); } static __inline__ __device__ float getSphereLightPdf() { return 1.0f / (4.0f * M_PIf); } static __inline__ __device__ float getLightPdf(const UniformLight& l, const float3 lightHitPoint, const float3 surfaceHitPoint) { switch (l.type) { case 0: // Rect return getRectLightPdf(l, lightHitPoint, surfaceHitPoint); break; case 2: // sphere return getSphereLightPdf(); break; case 3: // Distant return getDirectLightPdf(l.halfAngle); break; default: break; } return 0.0f; } static __inline__ __device__ LightSampleData SampleRectLight(const UniformLight& l, const float2 u, const float3 hitPoint) { LightSampleData lightSampleData; float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]); float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]); // lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y; // https://www.arnoldrenderer.com/research/egsr2013_spherical_rectangle.pdf SphQuad quad = init(l, hitPoint); if (quad.S <= 0.0f) { lightSampleData.pdf = 0.0f; lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y; fillLightData(l, hitPoint, lightSampleData); return lightSampleData; } if (quad.S < 1e-3f) { // just use uniform, because rectangle too small lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y; fillLightData(l, hitPoint, lightSampleData); lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight / (-dot(lightSampleData.L, lightSampleData.normal) * lightSampleData.area); return lightSampleData; } lightSampleData.pointOnLight = SphQuadSample(quad, u); fillLightData(l, hitPoint, lightSampleData); lightSampleData.pdf = 1.0f / quad.S; return lightSampleData; } static __inline__ __device__ LightSampleData SampleRectLightUniform(const UniformLight& l, const float2 u, const float3 hitPoint) { LightSampleData lightSampleData; // // uniform sampling float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]); float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]); lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y; fillLightData(l, hitPoint, lightSampleData); // here is conversion from are to solid angle: dist2 / cos lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight / (-dot(lightSampleData.L, lightSampleData.normal) * lightSampleData.area); return lightSampleData; } static __device__ void createCoordinateSystem(const float3& N, float3& Nt, float3& Nb) { if (fabs(N.x) > fabs(N.y)) { float invLen = 1.0f / sqrt(N.x * N.x + N.z * N.z); Nt = make_float3(-N.z * invLen, 0.0f, N.x * invLen); } else { float invLen = 1.0f / sqrt(N.y * N.y + N.z * N.z); Nt = make_float3(0.0f, N.z * invLen, -N.y * invLen); } Nb = cross(N, Nt); } static __device__ float3 SampleCone(float2 uv, float angle, float3 direction, float& pdf) { float phi = 2.0 * M_PIf * uv.x; float cosTheta = 1.0 - uv.y * (1.0 - cos(angle)); // Convert spherical coordinates to 3D direction float sinTheta = sqrt(1.0 - cosTheta * cosTheta); float3 u, v; createCoordinateSystem(direction, u, v); float3 sampledDir = normalize(cos(phi) * sinTheta * u + sin(phi) * sinTheta * v + cosTheta * direction); // Calculate the PDF for the sampled direction pdf = 1.0 / (2.0 * M_PIf * (1.0 - cos(angle))); return sampledDir; } static __inline__ __device__ LightSampleData SampleDistantLight(const UniformLight& l, const float2 u, const float3 hitPoint) { LightSampleData lightSampleData; float pdf = 0.0f; float3 coneSample = SampleCone(u, l.halfAngle, -make_float3(l.normal), pdf); lightSampleData.area = 0.0f; lightSampleData.distToLight = 1e9; lightSampleData.L = coneSample; lightSampleData.normal = make_float3(l.normal); lightSampleData.pdf = pdf; lightSampleData.pointOnLight = coneSample; return lightSampleData; } static __inline__ __device__ LightSampleData SampleSphereLight(const UniformLight& l, const float2 u, const float3 hitPoint) { LightSampleData lightSampleData; // Generate a random direction on the sphere using solid angle sampling float cosTheta = 1.0f - 2.0f * u.x; // cosTheta is uniformly distributed between [-1, 1] float sinTheta = sqrt(1.0f - cosTheta * cosTheta); float phi = 2.0f * M_PIf * u.y; // phi is uniformly distributed between [0, 2*pi] const float radius = l.points[0].x; // Convert spherical coordinates to Cartesian coordinates float3 sphereDirection = make_float3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); // Scale the direction by the radius of the sphere and move it to the light position float3 lightPoint = make_float3(l.points[1]) + radius * sphereDirection; // Calculate the direction from the hit point to the sampled point on the light lightSampleData.L = normalize(lightPoint - hitPoint); // Calculate the distance to the light lightSampleData.distToLight = length(lightPoint - hitPoint); lightSampleData.area = 0.0f; lightSampleData.normal = sphereDirection; lightSampleData.pdf = 1.0f / (4.0f * M_PIf); lightSampleData.pointOnLight = lightPoint; return lightSampleData; }
11,611
C
30.988981
131
0.623374
arhix52/Strelka/include/render/Camera.h
#pragma once #include <glm/glm.hpp> #include <glm/gtx/compatibility.hpp> class Camera { public: Camera() : m_eye(glm::float3(1.0f)), m_lookat(glm::float3(0.0f)), m_up(glm::float3(0.0f, 1.0f, 0.0f)), m_fovY(35.0f), m_aspectRatio(1.0f) { } Camera(const glm::float3& eye, const glm::float3& lookat, const glm::float3& up, float fovY, float aspectRatio) : m_eye(eye), m_lookat(lookat), m_up(up), m_fovY(fovY), m_aspectRatio(aspectRatio) { } glm::float3 direction() const { return glm::normalize(m_lookat - m_eye); } void setDirection(const glm::float3& dir) { m_lookat = m_eye + glm::length(m_lookat - m_eye) * dir; } const glm::float3& eye() const { return m_eye; } void setEye(const glm::float3& val) { m_eye = val; } const glm::float3& lookat() const { return m_lookat; } void setLookat(const glm::float3& val) { m_lookat = val; } const glm::float3& up() const { return m_up; } void setUp(const glm::float3& val) { m_up = val; } const float& fovY() const { return m_fovY; } void setFovY(const float& val) { m_fovY = val; } const float& aspectRatio() const { return m_aspectRatio; } void setAspectRatio(const float& val) { m_aspectRatio = val; } // UVW forms an orthogonal, but not orthonormal basis! void UVWFrame(glm::float3& U, glm::float3& V, glm::float3& W) const { W = m_lookat - m_eye; // Do not normalize W -- it implies focal length float wlen = glm::length(W); U = glm::normalize(glm::cross(W, m_up)); V = glm::normalize(glm::cross(U, W)); float vlen = wlen * tanf(0.5f * m_fovY * M_PI / 180.0f); V *= vlen; float ulen = vlen * m_aspectRatio; U *= ulen; } private: glm::float3 m_eye; glm::float3 m_lookat; glm::float3 m_up; float m_fovY; float m_aspectRatio; };
2,098
C
21.329787
115
0.534795
arhix52/Strelka/include/render/render.h
#pragma once #include "common.h" #include "buffer.h" #include <scene/scene.h> namespace oka { enum class RenderType : int { eOptiX = 0, eMetal, eCompute, }; /** * Render interface */ class Render { public: virtual ~Render() = default; virtual void init() = 0; virtual void render(Buffer* output) = 0; virtual Buffer* createBuffer(const BufferDesc& desc) = 0; virtual void* getNativeDevicePtr() { return nullptr; } void setSharedContext(SharedContext* ctx) { mSharedCtx = ctx; } SharedContext& getSharedContext() { return *mSharedCtx; } void setScene(Scene* scene) { mScene = scene; } Scene* getScene() { return mScene; } protected: SharedContext* mSharedCtx = nullptr; oka::Scene* mScene = nullptr; }; class RenderFactory { public: static Render* createRender(RenderType type); }; } // namespace oka
954
C
13.692307
61
0.610063
arhix52/Strelka/include/render/common.h
#pragma once #include <glm/glm.hpp> #include <glm/gtx/compatibility.hpp> #include <settings/settings.h> namespace oka { static constexpr int MAX_FRAMES_IN_FLIGHT = 3; #ifdef __APPLE__ struct float3; struct float4; #else using Float3 = glm::float3; using Float4 = glm::float4; #endif class Render; struct SharedContext { size_t mFrameNumber = 0; size_t mSubframeIndex = 0; SettingsManager* mSettingsManager = nullptr; Render* mRender = nullptr; }; enum class Result : uint32_t { eOk, eFail, eOutOfMemory, }; } // namespace oka
562
C
13.815789
48
0.69395
arhix52/Strelka/include/render/materials.h
#pragma once #ifdef __cplusplus # define GLM_FORCE_SILENT_WARNINGS # define GLM_LANG_STL11_FORCED # define GLM_ENABLE_EXPERIMENTAL # define GLM_FORCE_CTOR_INIT # define GLM_FORCE_RADIANS # define GLM_FORCE_DEPTH_ZERO_TO_ONE # include <glm/glm.hpp> # include <glm/gtx/compatibility.hpp> # define float4 glm::float4 # define float3 glm::float3 # define uint glm::uint #endif struct MdlMaterial { int arg_block_offset = 0; // in bytes int ro_data_segment_offset = 0; // in bytes int functionId = 0; int pad1; }; /// Information passed to GPU for mapping id requested in the runtime functions to buffer /// views of the corresponding type. struct Mdl_resource_info { // index into the tex2d, tex3d, ... buffers, depending on the type requested uint gpu_resource_array_start; uint pad0; uint pad1; uint pad2; }; #ifdef __cplusplus # undef float4 # undef float3 # undef uint #endif
958
C
22.390243
89
0.679541
arhix52/Strelka/include/settings/settings.h
#pragma once #include <iostream> #include <string> #include <unordered_map> #include <cassert> namespace oka { class SettingsManager { private: /* data */ std::unordered_map<std::string, std::string> mMap; void isNameValid(const char* name) { if (mMap.find(name) == mMap.end()) { std::cerr << "The setting " << name << " does not exist" << std::endl; assert(0); } } public: SettingsManager(/* args */) = default; ~SettingsManager() = default; template <typename T> void setAs(const char* name, const T& value) { // mMap[name] = std::to_string(value); mMap[name] = toString(value); } template <typename T> T getAs(const char* name) { isNameValid(name); return convertValue<T>(mMap[name]); } private: template <typename T> T convertValue(const std::string& value) { // Default implementation for non-specialized types return T{}; } static std::string toString(const std::string& value) { return value; } template <typename T> std::string toString(const T& value) { // Default implementation for non-specialized types return std::to_string(value); } }; template<> inline void SettingsManager::setAs(const char* name, const std::string& value) { mMap[name] = value; } template <> inline bool SettingsManager::convertValue(const std::string& value) { return static_cast<bool>(atoi(value.c_str())); } template <> inline float SettingsManager::convertValue(const std::string& value) { return static_cast<float>(atof(value.c_str())); } template <> inline uint32_t SettingsManager::convertValue(const std::string& value) { return static_cast<uint32_t>(atoi(value.c_str())); } template <> inline std::string SettingsManager::convertValue(const std::string& value) { return value; } template <> inline std::string SettingsManager::toString(const std::string& value) { return value; } } // namespace oka
2,057
C
19.17647
82
0.628585
arhix52/Strelka/include/scene/camera.h
#pragma once #define GLM_FORCE_SILENT_WARNINGS #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/compatibility.hpp> #include <string> namespace oka { class Camera { public: std::string name = "Default camera"; int node = -1; enum class CameraType : uint32_t { lookat, firstperson }; CameraType type = CameraType::firstperson; float fov = 45.0f; float znear = 0.1f, zfar = 1000.0f; // View dir -Z glm::quat mOrientation = { 1.0f, 0.0f, 0.0f, 0.0f }; glm::float3 position = { 0.0f, 0.0f, 10.0f }; glm::float3 mWorldUp = {0.0, 1.0, 0.0}; glm::float3 mWorldForward = {0.0, 0.0, -1.0}; glm::quat getOrientation(); float rotationSpeed = 0.025f; float movementSpeed = 5.0f; bool updated = false; bool isDirty = true; struct MouseButtons { bool left = false; bool right = false; bool middle = false; } mouseButtons; glm::float2 mousePos; struct Matrices { glm::float4x4 perspective; glm::float4x4 invPerspective; glm::float4x4 view; }; Matrices matrices; void updateViewMatrix(); struct { bool left = false; bool right = false; bool up = false; bool down = false; bool forward = false; bool back = false; } keys; glm::float3 getFront() const; glm::float3 getUp() const; glm::float3 getRight() const; bool moving() const; float getNearClip() const; float getFarClip() const; void setFov(float fov); void setPerspective(float fov, float aspect, float znear, float zfar); void setWorldUp(const glm::float3 up); glm::float3 getWorldUp(); void setWorldForward(const glm::float3 forward); glm::float3 getWorldForward(); glm::float4x4& getPerspective(); glm::float4x4 getView(); void updateAspectRatio(float aspect); void setPosition(glm::float3 position); glm::float3 getPosition(); void setRotation(glm::quat rotation); void rotate(float, float); void setTranslation(glm::float3 translation); void translate(glm::float3 delta); void update(float deltaTime); }; } // namespace oka
2,328
C
23.010309
74
0.629725
arhix52/Strelka/include/scene/scene.h
#pragma once #include "camera.h" #include "glm-wrapper.hpp" // #include "materials.h" // #undef float4 // #undef float3 #include <cstdint> #include <mutex> #include <set> #include <stack> #include <unordered_map> #include <vector> #include <mutex> #include <materialmanager/materialmanager.h> namespace oka { struct Mesh { uint32_t mIndex; // Index of 1st index in index buffer uint32_t mCount; // amount of indices in mesh uint32_t mVbOffset; // start in vb uint32_t mVertexCount; // number of vertices in mesh }; struct Curve { enum class Type : uint8_t { eLinear, eCubic, }; uint32_t mVertexCountsStart; uint32_t mVertexCountsCount; uint32_t mPointsStart; uint32_t mPointsCount; uint32_t mWidthsStart; uint32_t mWidthsCount; }; struct Instance { glm::mat4 transform; enum class Type : uint8_t { eMesh, eLight, eCurve } type; union { uint32_t mMeshId; uint32_t mCurveId; }; uint32_t mMaterialId = 0; uint32_t mLightId = (uint32_t)-1; }; class Scene { public: struct MaterialDescription { enum class Type { eMdl, eMaterialX } type; std::string code; std::string file; std::string name; bool hasColor = false; glm::float3 color; std::vector<MaterialManager::Param> params; }; struct Vertex { glm::float3 pos; uint32_t tangent; uint32_t normal; uint32_t uv; float pad0; float pad1; }; struct Node { std::string name; glm::float3 translation; glm::float3 scale; glm::quat rotation; int parent = -1; std::vector<int> children; }; std::vector<Node> mNodes; enum class AnimationState : uint32_t { eStop, ePlay, eScroll, }; AnimationState mAnimState = AnimationState::eStop; struct AnimationSampler { enum class InterpolationType { LINEAR, STEP, CUBICSPLINE }; InterpolationType interpolation; std::vector<float> inputs; std::vector<glm::float4> outputsVec4; }; struct AnimationChannel { enum class PathType { TRANSLATION, ROTATION, SCALE }; PathType path; int node; uint32_t samplerIndex; }; struct Animation { std::string name; std::vector<AnimationSampler> samplers; std::vector<AnimationChannel> channels; float start = std::numeric_limits<float>::max(); float end = std::numeric_limits<float>::min(); }; std::vector<Animation> mAnimations; // GPU side structure struct Light { glm::float4 points[4]; glm::float4 color = glm::float4(1.0f); glm::float4 normal; int type; float halfAngle; float pad0; float pad1; }; // CPU side structure struct UniformLightDesc { int32_t type; glm::float4x4 xform{ 1.0 }; glm::float3 position; // world position glm::float3 orientation; // euler angles in degrees bool useXform; // OX - axis of light or normal glm::float3 color; float intensity; // rectangle light float width; // OY float height; // OZ // disc/sphere light float radius; // distant light float halfAngle; }; std::vector<UniformLightDesc> mLightDesc; enum class DebugView : uint32_t { eNone = 0, eNormals = 1, eShadows = 2, eLTC = 3, eMotion = 4, eCustomDebug = 5, ePTDebug = 11 }; DebugView mDebugViewSettings = DebugView::eNone; bool transparentMode = true; bool opaqueMode = true; glm::float4 mLightPosition{ 10.0, 10.0, 10.0, 1.0 }; std::mutex mMeshMutex; std::mutex mInstanceMutex; std::vector<Vertex> mVertices; std::vector<uint32_t> mIndices; std::vector<glm::float3> mCurvePoints; std::vector<float> mCurveWidths; std::vector<uint32_t> mCurveVertexCounts; std::string modelPath; std::string getSceneFileName(); std::string getSceneDir(); std::vector<Mesh> mMeshes; std::vector<Curve> mCurves; std::vector<Instance> mInstances; std::vector<Light> mLights; std::vector<uint32_t> mTransparentInstances; std::vector<uint32_t> mOpaqueInstances; Scene() = default; ~Scene() = default; std::unordered_map<uint32_t, uint32_t> mLightIdToInstanceId{}; std::unordered_map<int32_t, std::string> mTexIdToTexName{}; std::vector<Vertex>& getVertices() { return mVertices; } std::vector<uint32_t>& getIndices() { return mIndices; } std::vector<MaterialDescription>& getMaterials() { return mMaterialsDescs; } std::vector<Light>& getLights() { return mLights; } std::vector<UniformLightDesc>& getLightsDesc() { return mLightDesc; } uint32_t findCameraByName(const std::string& name) { std::scoped_lock lock(mCameraMutex); if (mNameToCamera.find(name) != mNameToCamera.end()) { return mNameToCamera[name]; } return (uint32_t)-1; } uint32_t addCamera(Camera& camera) { std::scoped_lock lock(mCameraMutex); mCameras.push_back(camera); // store camera index mNameToCamera[camera.name] = (uint32_t)mCameras.size() - 1; return (uint32_t)mCameras.size() - 1; } void updateCamera(Camera& camera, uint32_t index) { assert(index < mCameras.size()); std::scoped_lock lock(mCameraMutex); mCameras[index] = camera; } Camera& getCamera(uint32_t index) { assert(index < mCameras.size()); std::scoped_lock lock(mCameraMutex); return mCameras[index]; } const std::vector<Camera>& getCameras() { std::scoped_lock lock(mCameraMutex); return mCameras; } size_t getCameraCount() { std::scoped_lock lock(mCameraMutex); return mCameras.size(); } const std::vector<Instance>& getInstances() const { return mInstances; } const std::vector<Mesh>& getMeshes() const { return mMeshes; } const std::vector<Curve>& getCurves() const { return mCurves; } const std::vector<glm::float3>& getCurvesPoint() const { return mCurvePoints; } const std::vector<float>& getCurvesWidths() const { return mCurveWidths; } const std::vector<uint32_t>& getCurvesVertexCounts() const { return mCurveVertexCounts; } void updateCamerasParams(int width, int height) { for (Camera& camera : mCameras) { camera.updateAspectRatio((float)width / height); } } glm::float4x4 getTransform(const Scene::UniformLightDesc& desc) { const glm::float4x4 translationMatrix = glm::translate(glm::float4x4(1.0f), desc.position); glm::quat rotation = glm::quat(glm::radians(desc.orientation)); // to quaternion const glm::float4x4 rotationMatrix{ rotation }; glm::float3 scale = { desc.width, desc.height, 1.0f }; const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), scale); const glm::float4x4 localTransform = translationMatrix * rotationMatrix * scaleMatrix; return localTransform; } glm::float4x4 getTransformFromRoot(int nodeIdx) { std::stack<glm::float4x4> xforms; while (nodeIdx != -1) { const Node& n = mNodes[nodeIdx]; glm::float4x4 xform = glm::translate(glm::float4x4(1.0f), n.translation) * glm::float4x4(n.rotation) * glm::scale(glm::float4x4(1.0f), n.scale); xforms.push(xform); nodeIdx = n.parent; } glm::float4x4 xform = glm::float4x4(1.0); while (!xforms.empty()) { xform = xform * xforms.top(); xforms.pop(); } return xform; } glm::float4x4 getTransform(int nodeIdx) { glm::float4x4 xform = glm::float4x4(1.0); while (nodeIdx != -1) { const Node& n = mNodes[nodeIdx]; xform = glm::translate(glm::float4x4(1.0f), n.translation) * glm::float4x4(n.rotation) * glm::scale(glm::float4x4(1.0f), n.scale) * xform; nodeIdx = n.parent; } return xform; } glm::float4x4 getCameraTransform(int nodeIdx) { int child = mNodes[nodeIdx].children[0]; return getTransform(child); } void updateAnimation(const float dt); void updateLight(uint32_t lightId, const UniformLightDesc& desc); /// <summary> /// Create Mesh geometry /// </summary> /// <param name="vb">Vertices</param> /// <param name="ib">Indices</param> /// <returns>Mesh id in scene</returns> uint32_t createMesh(const std::vector<Vertex>& vb, const std::vector<uint32_t>& ib); /// <summary> /// Creates Instance /// </summary> /// <param name="meshId">valid mesh id</param> /// <param name="materialId">valid material id</param> /// <param name="transform">transform</param> /// <returns>Instance id in scene</returns> uint32_t createInstance(const Instance::Type type, const uint32_t geomId, const uint32_t materialId, const glm::mat4& transform, const uint32_t lightId = (uint32_t)-1); uint32_t addMaterial(const MaterialDescription& material); uint32_t createCurve(const Curve::Type type, const std::vector<uint32_t>& vertexCounts, const std::vector<glm::float3>& points, const std::vector<float>& widths); uint32_t createLight(const UniformLightDesc& desc); /// <summary> /// Removes instance/mesh/material /// </summary> /// <param name="meshId">valid mesh id</param> /// <param name="materialId">valid material id</param> /// <param name="instId">valid instance id</param> /// <returns>Nothing</returns> void removeInstance(uint32_t instId); void removeMesh(uint32_t meshId); void removeMaterial(uint32_t materialId); std::vector<uint32_t>& getOpaqueInstancesToRender(const glm::float3& camPos); std::vector<uint32_t>& getTransparentInstancesToRender(const glm::float3& camPos); /// <summary> /// Get set of DirtyInstances /// </summary> /// <returns>Set of instances</returns> std::set<uint32_t> getDirtyInstances(); /// <summary> /// Get Frame mode (bool) /// </summary> /// <returns>Bool</returns> bool getFrMod(); /// <summary> /// Updates Instance matrix(transform) /// </summary> /// <param name="instId">valid instance id</param> /// <param name="newTransform">new transformation matrix</param> /// <returns>Nothing</returns> void updateInstanceTransform(uint32_t instId, glm::float4x4 newTransform); /// <summary> /// Changes status of scene and cleans up mDirty* sets /// </summary> /// <returns>Nothing</returns> void beginFrame(); /// <summary> /// Changes status of scene /// </summary> /// <returns>Nothing</returns> void endFrame(); private: std::vector<Camera> mCameras; std::unordered_map<std::string, uint32_t> mNameToCamera; std::mutex mCameraMutex; std::stack<uint32_t> mDelInstances; std::stack<uint32_t> mDelMesh; std::stack<uint32_t> mDelMaterial; std::vector<MaterialDescription> mMaterialsDescs; uint32_t createRectLightMesh(); uint32_t createDiscLightMesh(); uint32_t createSphereLightMesh(); bool FrMod{}; std::set<uint32_t> mDirtyInstances; uint32_t mRectLightMeshId = (uint32_t)-1; uint32_t mDiskLightMeshId = (uint32_t)-1; uint32_t mSphereLightMeshId = (uint32_t)-1; }; } // namespace oka
12,324
C
24.256147
114
0.586498
arhix52/Strelka/include/scene/glm-wrapper.hpp
#pragma once #define GLM_FORCE_SILENT_WARNINGS #define GLM_LANG_STL11_FORCED #define GLM_ENABLE_EXPERIMENTAL #define GLM_FORCE_CTOR_INIT #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtx/hash.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/compatibility.hpp>
403
C++
24.249998
39
0.769231
arhix52/Strelka/include/log/logmanager.h
#pragma once #include <spdlog/spdlog.h> namespace oka { class Logmanager { public: Logmanager(/* args */); ~Logmanager(); void initialize(); void shutdown(); }; } // namespace oka
200
C
10.166666
27
0.625
arhix52/Strelka/include/log/log.h
#pragma once #include <spdlog/spdlog.h> #define STRELKA_DEFAULT_LOGGER_NAME "Strelka" #ifndef RELEASE #define STRELKA_TRACE(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->trace(__VA_ARGS__);} #define STRELKA_DEBUG(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->debug(__VA_ARGS__);} #define STRELKA_INFO(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->info(__VA_ARGS__);} #define STRELKA_WARNING(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->warn(__VA_ARGS__);} #define STRELKA_ERROR(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->error(__VA_ARGS__);} #define STRELKA_FATAL(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->critical(__VA_ARGS__);} #else define STRELKA_TRACE(...) void(0); define STRELKA_DEBUG(...) void(0); define STRELKA_INFO(...) void(0); define STRELKA_WARNING(...) void(0); define STRELKA_ERROR(...) void(0); define STRELKA_FATAL(...) void(0); #endif
1,219
C
54.454543
150
0.700574
arhix52/Strelka/include/sceneloader/gltfloader.h
#pragma once #include <scene/scene.h> #include <string> #include <vector> namespace oka { class GltfLoader { private: public: explicit GltfLoader(){} bool loadGltf(const std::string& modelPath, Scene& mScene); void computeTangent(std::vector<Scene::Vertex>& _vertices, const std::vector<uint32_t>& _indices) const; }; } // namespace oka
380
C
14.874999
69
0.655263
arhix52/Strelka/include/display/Display.h
#pragma once #include <render/common.h> #include <render/buffer.h> #include <GLFW/glfw3.h> namespace oka { class InputHandler { public: virtual void keyCallback(int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods) = 0; virtual void mouseButtonCallback(int button, int action, [[maybe_unused]] int mods) = 0; virtual void handleMouseMoveCallback([[maybe_unused]] double xpos, [[maybe_unused]] double ypos) = 0; }; class ResizeHandler { public: virtual void framebufferResize(int newWidth, int newHeight) = 0; }; class Display { public: Display() { } virtual ~Display() { } virtual void init(int width, int height, oka::SharedContext* ctx) = 0; virtual void destroy() = 0; void setWindowTitle(const char* title) { glfwSetWindowTitle(mWindow, title); } void setInputHandler(InputHandler* handler) { mInputHandler = handler; } InputHandler* getInputHandler() { return mInputHandler; } void setResizeHandler(ResizeHandler* handler) { mResizeHandler = handler; } ResizeHandler* getResizeHandler() { return mResizeHandler; } bool windowShouldClose() { return glfwWindowShouldClose(mWindow); } void pollEvents() { glfwPollEvents(); } virtual void onBeginFrame() = 0; virtual void onEndFrame() = 0; virtual void drawFrame(ImageBuffer& result) = 0; virtual void drawUI(); protected: static void framebufferResizeCallback(GLFWwindow* window, int width, int height); static void keyCallback( GLFWwindow* window, int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods); static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods); static void handleMouseMoveCallback(GLFWwindow* window, double xpos, double ypos); static void scrollCallback(GLFWwindow* window, double xoffset, double yoffset); int mWindowWidth = 800; int mWindowHeight = 600; InputHandler* mInputHandler = nullptr; ResizeHandler* mResizeHandler = nullptr; oka::SharedContext* mCtx = nullptr; GLFWwindow* mWindow; }; class DisplayFactory { public: static Display* createDisplay(); }; } // namespace oka
2,313
C
21.25
112
0.671855