Search Unity

Advanced foliage shader [released]

Discussion in 'Assets and Asset Store' started by larsbertram1, Apr 24, 2012.

  1. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    hmm, i just had a look at the demo scene in 5.6.1 and everything works fine: instanced ferns e.g. just bend nicely...

    that is not a good idea as phase variation is needed to create lively bending. it determines fBranchPhase which will make different branches slightly bend differently. so i guess this is the reason why enabling instancing gives you that boring look.

    if you turn off instancing the shader expects dynamically batched meshes which do not have unique pivots anymore.
    in this case you have to tweak the "Wave size" in the "Wind settings for foliage shaders" in the afs setup script to make bending look somewhat believable.
     
  2. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    I'm going to reimport the package and try to record same gif using the sample scene then.

    To clarify, making wind non-boring is not pressing to me, I just want to achieve consistent look first - making instanced materials bent by wind the same as non-instanced materials, which is not the case at the moment. What I'm wondering about is not uniformity of wind at all, it's the fact that enabling instancing makes wind wave size/frequency jump enormously, turning low-scale fluttering to gigantic waves. By switching off all forms of wind but one, I'm hoping to narrow down the source of the bug. :)

    Sorry, I'm not sure I follow. The problem occurs when instancing is turned on, not off (size of wind waves becomes enormous). I'm not sure how dynamic batching is relevant here either, since Unity never uses it for anything but very small meshes (since we're using multiple UV channels, positions and normals, dynamic batching can't even influence trees with vertex counts as low as 300) - trees I'm using are well above vertex counts putting them in range of dynamic batching. I can even disable dynamic batching entirely from the project with zero effect on my environments.
     
    Last edited: Jul 31, 2017
  3. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    Managed to capture the bug using sample assets shipping with AFS, specifically the wide bush made from Quixel materials. Here is the gif:

    To see the effect clearly, make a few copies of wide bush in the Cast demo scene, increase wind strength to 10 and flick instancing toggle on QuixelBush_afs material on and off. You'll see that with instancing on, every single vertex on each bush seems to be shifted very similarly, as if a huge wave was rolling over it; while with instancing off, each branch seems to flutter independently, as if fine-grained small waves of entirely different wind were rolling over it.

    It's as if turning instancing on makes some vertex offset calculations in AfsAnimateVertex function performed at a vastly different scale or perhaps with a wrong pivot.

    You can even see the bug very clearly from the orange selection outline in Unity Scene view. Since Unity Editor renders orange outlines of selected objects using a non-instanced replacement shader, you can immediately notice how outline breaks away from the instanced bush, receiving different wind.

    Non-instanced mode:


    Instanced mode:
     
  4. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    i did not say that dynamic batching IS used – i said that the shader EXPECTS to deal with dynamic batched geometry which would be just a vertex soup :)

    refereing to the picture below:
    http://i.imgur.com/qRBeF49.gifv

    when instancing is disabled the shader assumes to have to deal with a pure vertex soup and many instances. so it creates some wind variation based on the world position of each single vertex. if the "wave size" is set to a rather small value (i guess it was set to something around 1m) you will get that fancy wobbling, because the wind strength varies even on the different vertices of a single branch.

    when instancing is enabled you do not get any per branch variation because you did not assign any phase variation.
    so you have to add different shades of red to the vertex colors of your mesh: one shade for each branch. additionally you may assign vertex color green as well which will give you some edge fluttering.

    oh, it is not a bug at all. it is the desired behaviour.

    that is right: very similarly but not identically.

    so once again: when instancing is disabled wind strength gets calculates per vertex (not per mesh or instance). according to the "wave size" this might lead to rather strange bending.
    so please add vertex colors :) to make instanced trees look better.
     
  5. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    @bac9-flcl: you may send me your tree model and i could do a quick sketch on the vertex colors.
     
  6. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    Ah, interesting - so you intended non-instanced and instanced meshes to work very differently with wind and assumed each asset would be authored and tweaked for instanced or non-instanced case separately. :)

    The reason I immediately assumed that this discrepancy is a bug is pretty simple. New instancing system is exceptionally useful, but it has one significant limitation - the number of mesh types you can use with instancing is somewhat small. So using instancing is a bit of a balancing act - some meshes, like hero trees or fir trees in a broadleaf forest, which you never see more than once or twice per environment, would be better off with instancing disabled. This avoids stealing a limited instancing slot from some other tree type that is used 100+ times and therefore would benefit far more from access to instancing.

    So from that point, I somewhat reasonably expected both instanced and non-instanced vegetation to look exactly the same under wind, because it's not possible to guarantee blanket instancing for any given vegetation type - it might be on on one level and off on another, with same asset. It's obviously desirable to have a consistent vegetation production pipeline for vegetation, with one mesh working correctly in both cases. In scene A, tree X might be prevalent and tree Y might be rare, so you'd want to have tree X with instancing enabled and tree Y with instancing disabled - while in scene B, where object frequency is reversed, you might want the opposite instancing preference. :)

    I'm not against authoring vertex colors, but I'd prefer not to keep around two entirely separate versions of trees - one that looks good with instancing disabled, and one that looks good with instancing enabled. With that in mind:

    • Is there a wind mode in the AFS shader that looks identical with instancing on and off, assuming correctly authored inputs like vertex colors?
    • If there isn't (and every single mode of standard AFS shader assumes that vegetation model is either instanced or not forever and can therefore be authored differently), then where in your shaders can I find the point where instanced and non-instanced wind diverges? Looking at that, I'll be able to implement custom wind that would be consistent between instanced and non-instanced meshes, but I couldn't find any checks for instancing being on in the vertex offset code, at least in places I looked at so far.
    P.S.: Since having 100+ vegetation model types filling up instancing system isn't exactly a common situation, you might be wondering where I spent most of the instancing slots to make their conservation a concern. I'm using modular geometry similar to one in this demo from Oscar Stalberg rendered with instancing, which means that 100+ slots are already taken on most of my levels and vegetation is a second-class citizen that has to conserve instancing slots to avoid taking them from modular architecture blocks. That's where necessity of juggling the instancing flag to save 1000 draw calls on tree A vs. saving 10 draw calls from tree B comes from.
     
    Last edited: Jul 31, 2017
  7. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    i had to. afs has a very long history reaching back to unity 2.x. dynmaic batching then was the only way to reduce the number of draw calls back in that time.

    i never experienced this. do you have any official reference for this?
    this will also answer your next question or demand: i am not aware of a limited number of instancing shaders active at the same time. even if a tree only occurs only one or two times in your scene you may activate instancing.
    not to mention that we are talking about the foliage shader – which is not meant to be used on trees.
    it is designed to be used on foliage which occurs quite often – either drawn instanced, baked into patches using the combine children script or dynamically batched.

    if you can guarantee that none of your objects will ever be batched dynamically you could tweak the shader to produce exactly that behaviour.

    nope. instancing off and not having combined the meshes will make the shader assuming to have to deal with a vertex soup.

    it is all in this block of code in: AfsFoliageBendingInstanced.cginc
    // Phases (object, vertex, branch)
    #if defined(INSTANCING_ON) || defined(VERTEXLIT) || defined (INSTANCEDDEPTHPASSAFS) || defined (UNITY_PASS_FORWARDADD)
    float3 variations = abs( frac( wpos.xyz * _AfsFoliageWaveSize /* * float3(443.8975,397.2973, 491.1871) */ ) - 0.5 );
    float fObjPhase = dot(variations, float3(1,1,1) ) + variation;
    // This would be OpenGL or DX9
    #else
    // In order to handle dynamic batching...
    float fObjPhase = frac( (pos.x + pos.z) * _AfsFoliageWaveSize ) + variation;
    #endif

    look for "fObjPhase" which is handled for a) instancing and vertexlit and b) dynamic batching.
     
    bac9-flcl likes this.
  8. Hynopsis

    Hynopsis

    Joined:
    Oct 25, 2012
    Posts:
    60
    I just upgraded to version 5, which looks nice. I like how the bending and raindrops are all incorporated into one script. Anyway, I get these black spots through the foliage. I get this is version 4, and thought upgrading to 5 would solve it. It only happens when running in DX11. I am using linear and replaced the deferred and reflection shader like the instructions. It appears to do the same thing with the Unity Standard Shader set to cutout too. Any ideas?

    Also, it there any way to have the normal foliage shader fade out at a certain radial distance like the grass shader?

    Once last thing. Is the foliage setup script necessary if only using the foliage shader? Does this script have a newer version for 5.0? It looks like when importing it is still labeled v4. The script will not show on the Setup object, it says it has compilation errors, but there is nothing logged in the console about any kind of error. It may just be something wonky with my version of Unity. It would even let me build right now saying there are script errors (before AFS 5) and forcing me to restart even to run the game in editor mode.
     

    Attached Files:

  9. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    i can not confirm any black spots using version 5 running in dx11: it all looks fine on my side. the black grass is grass placed using the terrain engine, right? so you may check the vertex colors of your model andmake sure that they are set to rgb = white. please also check your dry and healthy colors and look for any grass shader which might overwrite the afs grass shader for the terrain.

    look for the LODgroup demo. there you will find a fern which "smoothly" fades out.

    hmm, it seems that simply updating from version 4 to version 5 did not really work in your case.
    so i suggest you remove the v4 folder and then reimport v5. that might also solve all other problems.

    it is needed by all afs shaders: grass, foliage and trees.
     
  10. JMeer

    JMeer

    Joined:
    Mar 3, 2017
    Posts:
    29
    I am having some trouble creating a windows build using Unity 2017.1

    Shader error in 'Hidden/AfsCamera-DepthNormalTexture': 'UnityApplyDitherCrossFade': cannot convert from 'struct v2f' to 'float2' at line 314 (on d3d9)

    Shader error in 'Hidden/AfsCamera-DepthNormalTexture': 'UnityApplyDitherCrossFade': cannot convert from 'struct v2f' to 'float2' at line 314 (on d3d11)

    Shader error in 'Hidden/AfsCamera-DepthNormalTexture': 'UnityApplyDitherCrossFade': cannot convert from 'struct v2f' to 'float2' at line 316 (on d3d11)

    Any idea's? Thanks!
     
  11. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    @larsbertram1
    Thanks, this is very useful info, I'll be able to tweak the shader to my needs armed with this :)

    It makes sense to me why two modes work differently now. Hadn't considered the history of Unity and earlier AFS versions having to accommodate dynamic batching as the olny way to save draw calls.

    On the subject of instancing limits on number of instanced material-mesh combinations, I vaguely remember this being mentioned in early docs around 5.4 and seeing instancing stopping past certain number of unique objects (which was easy to achieve for me, since there are 255 permutations of 8-point (2x2x2) block shapes I use - their number can be reduced to about 55 by eliminating rotations and flips, but tileset blocks still quickly use up more than 100 instancing slots once you account for mirrored versions and subtypes, especially with more than one tileset being in play). I should recheck this to establish exact limit value when I have the time, now I'm curious about it myself.

    ____

    Had a few more questions on a different subject, if you don't mind. I always used custom trees, but being pressed for time on some assets, I checked some Tree Creator assets yesterday. Previously I have only used Tree Creator assets a very, very long time ago with the standard Terrain system, so I apologize if the questions I have are obvious to you:

    • I'd like to configure the distance at which Tree Creator assets fade to billboards. Your docs mention that it's controlled by Fade Length setting, but I don't see such a setting anywhere in the graphics settings, in the shader properties, or on the Tree Creator asset. Where is it situated?
    • If that setting is situated in the Terrain system, then how can I override it without introducing any Terrains into a scene? I don't use the Terrain system in my game. Is overriding the value of _AfsTerrainTrees float4, which seems to store that setting, the correct way to achieve this? I guess I can write a method similar to afsUpdateGrassTreesBillboards from AFS setup class - unless I really missed some place already allowing me to set various fade-related values directly.
    • Are there any drawbacks to using Tree Creator assets as normal objects existing on their own in the scene, without the standard terrain system? Non-obvious hidden values not being set when terrain is absent, something like that?
     
    Last edited: Aug 1, 2017
  12. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    if you use deffered rendering you can just remove the AfsCamera-DepthNormalTexture shader.
    in case you use forward you may try the shader attached.
     

    Attached Files:

  13. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    you will find that in the "terrain settings" --> "billboard start" and "fade length". it is the same for all trees.
    in case you do not have any terrain it would be the right way. but you do not get any billboards in case you have no terrain!
    you may simply add one and uncheck: "Draw" (first checkbox in the terrain settings). so the terrain itself will not be drawn – only trees and grass. you can then add tree by script. having a look at the "RepositionTreesAFS" might be a good starting point.
    nevertheless you have to setup "billboard start" and "fade length" in the terrain settings as the terrain has to now when to output a mesh tree and when to output a billboard. _AfsTerrainTrees is only used by the afs tree shaders.
    - no billboards
    - a lot of gos --> a lot of overhead

    in case you want to chop a terrain tree: well you have positioned them from script. so it should be easy and fast to find the tree in "terrainData.treeInstances" in case you have a doubled buffer which might be a simple 2d grid.
    then remove the tree from the terrain (or push it somewhere in the orbit) and spawn a tree as gameobject at the same position.

    but unfortunately tree creator trees do not let you close the trunk.
     
  14. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    @larsbertram1
    Thanks for the info! I just implemented fade start, fade length and fade out length as another few customizable global properties and added a toggle disabling their override from AFS setup for now - seems to work correctly for tweaking the distance where shadow fade out and squishing begins.

    You were right to point out that billboards don't work at all - looking at rendering closer, those new trees seem to stay in the form of their full meshes, never fading to anything. I suppose that's fine for my needs, since I'm making a small-scale tactical game where tree counts per map are relatively small (under few hundreds), locations are small, and trees are usually viewed in limited shots where billboarding is undesirable anyway (it would've only been useful for cutscenes at low camera pitch showing whole map in a horizontal line).

    I guess I have few more questions then:

    • Can you guess why this weird artifact happens with the tree creator bark shader? It's as if at some distances, bark shader changes projection or coordinate space it's using, jumping further away from the camera and becoming glued to it's rotation. Hard to explain, check the gif I link to this sentence. This happens relatively close to the camera, seems unrelated to billboarding, and seems to occur at several distances, without a clear lone threshold.
    • Is there any reason to continue using the tree creator shader if I won't use the billboarding and any other terrain features like terrain-driven instance scaling? As far as I understand, tree creator shaders mostly differ from standard AFS shader through advanced billboarding fading and handling of terrain-related instance properties. If that's not used, then I suppose standard AFS shader is far more appropriate.
    • Since I'll need to randomly rotate and drop the tree objects (for destruction when walking tanks run through forests, and for manually created scenes) handling them as a traditional prop no different from part of a building or vehicle, I suppose current terrain-focused billboard fading implementation wouldn't work anyway, since it assumes absolutely identical vertical orientation with 0,0,0 rotation on every instance, right? At least, that's the impression I get from checking the fading code and seeing how terrain-tailored fading behaves under non-zero rotation (camera projection compensation goes wrong and so on).
    • What's your opinion on using a LOD Group component for custom trees, with a manually authored custom billboard faded in with it? If in the end I'll be forced to use billboarding out of performance concerns (e.g. if we'll end up needing 4x bigger maps than we use now?) - that seems like a reasonable route for any prop, be it a car or a bush or a street light pole. If it's a reasonable route for custom tree meshes unrelated to terrain/tree creator systems - is there anything special I can do in the custom variation of vegetation shader to accomodate better transitions, or LOD Group does stuff like dithering entirely independently from shaders used on faded objects?
    • I suppose one obstacle to using the standard AFS shader with tree creator assets is the set of requirements Unity places on naming and structure of shaders used with it. But instead of adding optimized shader dependency and all the other cruft into a derivative of your standard AFS shader, I had something else in mind. If I'm not leveraging anything in the terrain-related functionality of tree creator system anyway, we might as well throw away the whole tree system. No tree editor, no hidden optimized materials, no tree properties asset - since trees are still Meshes rendered with a MeshRenderer/MeshFilter, it should be easy to just reference the procedurally generated Mesh asset and completely sever the link to tree creator system. It wouldn't be that much different from using a tree manually created in Maya or Max, I suppose. It still has traditional structure, it still has proper UVs and vertex colors. If I do that, what settings on the standard AFS foliage shader do you recommend to use? Any particular wind mode and so on that would fit best for geometry ripped away from tree creator? Or maybe the CTI shader would be the closest fit?
     
    Last edited: Aug 1, 2017
  15. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    Ha, referencing the Mesh generated inside the tree asset by the Tree Creator and setting up your own MeshFilter/MeshRenderer object referencing that mesh and two custom materials with standard AFS shader worked nicely!

    http://i.imgur.com/x9lOTyT.gifv

    I guess LOD Group question still stands, and I'm wondering what shader to best use to set up a custom shadow caster, but otherwise the tree is in good shape.
     
    Last edited: Aug 1, 2017
  16. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    i would guess: squash. but if it happens very close to the camera this explanations gets quite unlikely...
    one reason: you can simply use it on tree generated using the tree creator without any further tweakings.
    that is correct.
    i do this with cti. although one could do better...
    the tree creator stores bending in uv2. the foliage shader supports vertex colors or vertex colors and uv4. you would have to remap that in the shader.
     
  17. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    @larsbertram1

    I was wondering what would be the best way to render custom billboards. AFS ships with a billboard shader, but it's designed to work with (obviously, most popular case) the standard terrain system, replacing default hidden billboard shader. I thought about that for a bit and realized some relatively recent Unity features can be leveraged to create a very nice distant LOD solution for vegetation. It would take just a small custom shader and some processing scripts. The general idea is this:

    • Use a single billboard Mesh, insert it into every vegetation prefab
    • Use a single billboard atlas texture, which is procedurally generated from every vegetation object in a scene and contains their shots with proper transparency and albedo. Alternatively, use a recently introduced TextureArray to stack low-resolution shots into a single array.
    • In the shader, map a single cell of an atlas or single slice of a texture array to the billboard quad using an instanced index property (using UNITY_DEFINE_INSTANCED_PROP, UNITY_ACCESS_INSTANCED_PROP and so on). In case of an atlas, you can easily generate UV coords with some frac and floor use, in case of a texture array, slice index is all you need.
    • Create only one billboard material without anything unique per vegetation object
    • Assign the appropriate atlas index/array slice property to each billboard using MaterialPropertyBlock to leverage property instancing
    • Leverage LOD Group component and LOD_FADE_CROSSFADE feature, swap the full meshes and billboards in and out
    • Voila, now you can draw literal half a thousand of tree billboards with a single draw call while keeping them scaled, positioned, rotated and textured appropriately for any number of unique vegetation objects. For example, you can have a scene with 50 tree types, 500 tree instances spawned using those types - but if they are far enough, the CPU cost is just one draw call. Bonus points if you draw everything using specialized instanced draw methods instead of using separate gameobjects, but in my case the difference isn't that big.
    So, I've got everything described above working already, but my shader is fairly basic - no fancy fading, no proper lighting and so on. I suppose your replacement billboard shader is full of very valuable tricks and insights, and it would be smart for me not to invent a bicycle - instead, I should just lift them into my custom billboard shader. :)

    I'd appreciate it if you could provide some context about some parts of your billboard shader, enabling me to do so. I'll go in the order the shader is written.

    • 1. What is the purpose of the AFSTreeBillboard render type?
    • 2. Why is a special property called _AfsAmbientBillboardLight being used to pass ambient light information when (last I recall) Unity provides a way to retrieve it using some globals? I suppose it contains ambient lighting data somehow tweaked to work better with billboards?
    • 3. What is the purpose of the property called _AfsBillboardBorder? I don't think I see it being used directly in the vertex and fragment shaders.
    • 4. What is the purpose of the function called AFSShadeSH9 which performs polynomial (?) calculations using the vertex normal and seven other 4d vectors? I mean, I see that it's used to calculate ambient intensity, but I'm not sure how any of the elements used in it are derived, so I'd appreciate some context about it. :)
    • 5. What is "border fixing" operation accomplishing in the fragment shader? The one where some factor is calculated by blowing up the alpha channel (power of 2 and multiplication by 100) and then used to lerp between proper surface color and it's darkened version. I'd imagine darkening would do the opposite of hiding the border of improperly authored (undilated) textures with bad backgrounds, so I'm probably missing some context and that snippet has some other purpose rather than fixing undilated texture edges.
    • 6. What is the purpose of the shadow pass on a billboard when, if I recall correctly, billboards do not ever cast shadows with standard terrain system? The pass is preceded by the comment saying "This pass is a shadow caster pass but we use it to write to depth only" - can you elaborate a bit more on that, since the pass is pretty long and complex, doing curious things like calling SHADOW_CASTER functions?
    Sorry for the number of questions, hopefully it's not too much of a bother to answer them. I'd hate to let the lovely tricks in your package to go unused due to custom tree system, that's why I'm so curious about every detail - so that I'll be able to port everything correctly. :)
     
    Last edited: Aug 5, 2017
  18. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    in case you are doing your own billboard solution you can fully ignore any code in the afs billboard shader, as it is fully related to unity's off screen rendered a prelit billboards.
    unity does not know the actual ambient lighting when rendering the billboard textures. the built in shader uses ambient color whereas you might have setup skybox.
    that is a bad hack to get rid of bright borders around the billboards at night: billboards are rendered in front of a 50% gray.
    that allows you to have proper ambient lighting in case you use the skybox to provide al.
    forward... forward needs this to do proper depth pass. surface shaders...
     
  19. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    Thanks, that's very useful information!

    Last but not least - what would be the best way, in your opinion, to handle the world rotation of a mesh breaking correct billboard orientation? I notice that all vertex shader code for billboarding that I came across so far breaks when rotation of an object is not 0,0,0. Instancing has no issues with rendering freely rotated objects, in contrast with terrain system which demands fixed rotation, which is why I'm curious about making the shader handle rotations correctly.
     
  20. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    well, neither the built in nor the speedtree billboard shader can handle rotated "inputs" or meshes.
    and usually you do not want to have them as the billboard shader should rotate the billboards toward the camera.

    so in case you rotate the billboard towards the camera in your vertex function (speaking about a surface shader) the final transformation into clip space would add the original rotation of the mesh using the MVP or PV matrix --> the billboard will not face the camera anymore.
    i guess you would have to assume no rotation in the vertex function, orient the billboard towards the camera and apply the inverse rotation – before the original rotation finally gets applied.
    talking about billboards the inverse rotation should be just a rotation around the y-axis, which seems to be doable.
    but do not forget scaling...
     
  21. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
  22. silentslack

    silentslack

    Joined:
    Apr 5, 2013
    Posts:
    394
    When I import into 2017.1.0f3 I get:



    With error:
    Shader error in 'AFS/Foliage Shader': Unexpected token usertype. Expected one of: ',' ';' at line 152
     
  23. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
  24. RPowers

    RPowers

    Joined:
    May 14, 2015
    Posts:
    122
    Hi. I apologize ahead of time for my lack of knowledge in this area, but I have a couple questions.

    1. Does AFS fix the vr tree billboard issue?
    2. Can AFS be applied to manually placed tree gameobjects? I need to place trees manually, without unity terrain.

    Looking forward to responses.
    Thanks!
     
  25. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    hi there,
    i do not think so...
    that has always been possible with or without afs – but you will not get any billboards then.
    trick: USE a terrain but uncheck "Draw": you still will get the trees including the billboards but the terrain itself will not be rendered.
    alternatives would be Alttrees or my Custom tree importer – letter only in case you do not have tree creator trees but manually modeled ones.
     
  26. RPowers

    RPowers

    Joined:
    May 14, 2015
    Posts:
    122
    Ok thanks
     
  27. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    @larsbertram1
    Can you please recheck the tree model flattening code in AFS Foliage Tool component? It seems to do something incorrectly while saving a modified mesh, resulting in this error:

    Code (csharp):
    1.  
    2. ArgumentException: Invalid path
    3. System.IO.Path.GetDirectoryName (System.String path) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/Path.cs:215)
    4. AfsFoliageToolEditor.mergeTextureTree () (at Assets/Packages/AFS/Scripts/Foliage Tool/Editor/AfsFoliageToolEditor.cs:991)
    5. AfsFoliageToolEditor.OnInspectorGUI () (at Assets/Packages/AFS/Scripts/Foliage Tool/Editor/AfsFoliageToolEditor.cs:256)
    6. UnityEditor.InspectorWindow.DrawEditor (UnityEditor.Editor editor, Int32 editorIndex, Boolean rebuildOptimizedGUIBlock, System.Boolean& showImportedObjectBarNext, UnityEngine.Rect& importedObjectBarRect) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1240)
    7. UnityEditor.DockArea:OnGUI()
    Since exactly the same path with a slightly different filename worked fine for saving the first mesh asset (required to get access to other foliage tool options), I suspect it's some additional IO operation specific to tree flattening process going wrong, while mesh saving itself is fine. MergeTextureTree method seems to be the problem, going to look into it in a bit.

    By the way, why is it necessary to merge any textures when tree creator trees already have fully merged single set of textures? You know, those:



    I imagined that the only step needed for flattening was submesh collapse within Mesh object, no texture operations involved.
     
    Last edited: Aug 11, 2017
  28. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    hmm, works fine for me.

    the translucency channel on the bark has to be filled with black as it usually is (or was: it is a quite old script) filled with white -> full translucency.
     
  29. AcornBringer

    AcornBringer

    Joined:
    Mar 22, 2015
    Posts:
    70
    Hello!

    Is their any documentation on the intended workflow for using the AFS on custom made tree meshes instead of the Unity tree creator with Unity terrain?

    I would like to take the tree and plant prefabs I made using my own tree meshs and the AFS and paint them onto a terrain but I think I'm missing a few things. When I try this it paints only the trunk mesh with out the leaves which were using the AFS. It also does not apply random height or rotation to these meshs. Using the Geometry Brush tool seems to give me the intended results I need but I'm not sure how optimal that is for creating a forest.

    Because I'm not using the Unity tree creator, I'm also unsure about how I can create paintable prefabs with LOD. I understand how LODs are usually made but the Unity terrain seems to need a different setup.

    Thank you!
     
  30. bac9-flcl

    bac9-flcl

    Joined:
    Dec 5, 2012
    Posts:
    829
    @larsbertram1 Thanks, that makes sense, I'll double check translucency channel on bark side from now on. Ended up writing a custom tool to do some things specific to my project, but nevertheless, thanks for the foliage tool, it's a valuable reference.

    One thing that caught my attention in it, by the way, was complex method you used to save mesh assets. I assume you went through fetching existing files, deleting existing files, clearing them, assigning mesh arrays and so on to sidestep a Unity bug where Editor refuses to reload a Mesh which content was updated, right? If so, I have a lot shorter implementation which has worked well for me for a while. Check this extension method:

    Code (csharp):
    1.  
    2. public static T CreateAssetSafely<T> (T savedAsset, string path) where T : Object
    3. {
    4.     string[] pathSplit = path.Split (slash);
    5.     ValidateFolderRecursively (pathSplit, pathSplit.Length - 1);
    6.  
    7.     T existingAsset = AssetDatabase.LoadAssetAtPath (path, typeof (T)) as T;
    8.     if (existingAsset == null)
    9.     {
    10.         // if asset is not present, it's safe to use CreateAsset method without risking broken references
    11.         AssetDatabase.CreateAsset (savedAsset, path);
    12.         existingAsset = AssetDatabase.LoadAssetAtPath (path, typeof (T)) as T;
    13.     }
    14.     else
    15.     {
    16.         // if asset is present, we can use serialized copy method to gracefully replace it's content
    17.         if (typeof (T) == typeof (Mesh))
    18.         {
    19.             // if the saved asset is Mesh, we need to clear it before writing to sidestep Unity bug with Mesh reloading
    20.             Mesh existingMesh = (Mesh)(object)existingAsset;
    21.             Mesh savedMesh = (Mesh)(object)savedAsset;
    22.  
    23.             // we have to be careful not to apply this workaround to the saved data if saved and existing asset are the same
    24.             // in that case, we have to create a copy and preserve it to avoid clearing saved data
    25.             if (existingMesh == savedMesh)
    26.             {
    27.                 Mesh savedMeshCopy = Object.Instantiate (savedMesh);
    28.                 savedMeshCopy.name = savedMesh.name;
    29.                 savedAsset = savedMeshCopy as T;
    30.             }
    31.             existingMesh.Clear ();
    32.         }
    33.         EditorUtility.CopySerialized (savedAsset, existingAsset);
    34.     }
    35.     return existingAsset;
    36. }
    It works for any asset. Meshes are a bit unique due to that bug, but otherwise nothing stops us from using a generic method for asset saving. No need to overwrite vertices/normals/uvs and so on directly, no need to rely on cached strings to determine whether we're overwriting an asset and so on. :)
     
    Last edited: Aug 11, 2017
  31. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    please have a look at the LOD demo. it only shows fading out ferns, but you should be able to add LOD1 and LOD2 as well. billboards however are not supported.

    if it comes to complex tree models i always recommend to use my custom tree importer which gives you way more control over bending and support billboards.
     
  32. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    thanks a lot for sharing. saving out the stuff really wasn't anything i spent much time on, but simply wanted to work. somehow.
     
  33. AcornBringer

    AcornBringer

    Joined:
    Mar 22, 2015
    Posts:
    70
    After creating some LODs and properly sizing the mesh, it seems that all is working well! However, I ran into a new problem with the way my meshs and materials were set up because I'm unable to use the Afs Foliage Tool (Script).

    My tree mesh is set like so with two materials per mesh - one for leaves and one for wood:

    Tree_Pine
    > Tree_Pine_LOD0
    > Tree_Pine_LOD1
    > Tree_Pine_LOD2

    The wood is a standard material and the leaves are using the AFS foliage material. I'm keeping them separate so I can easily interchange the textures to create various trees. Unfortunately, because the leaves and the wood geometry are combined, when I save the mesh in the Afs Foliage Tool (Script) the mesh disappears and I get an error:

    "This renderer has more materials than the Mesh has sumbeshes. Multiple materials will be applied to the same submesh, which costs performance. Consider using multiple shader passes."

    To work around this, I thought I could just separate the leaves from the wood for LOD0 and make it a group but that doesn't work with the terrain tool and causes Unity to crash.

    Is there a way for me to use the Afs Foliage Tool (Script) with the way I'm set up or will I need to combine my wood and leave textures to one map and use a single material for each of my assets?

    Thanks for the help!
     
  34. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    unfortunately i think the foliage tool will not handle meshes with submeshes without massive modifications...
     
  35. AcornBringer

    AcornBringer

    Joined:
    Mar 22, 2015
    Posts:
    70
    I would rather adjust my workflow than ask anyone to re-work their plugin. There is clearly an intended procedure for using the tool that works great.

    The setup I'm using was something I went with before adding this plugin so there was a bit of a clash. I'll find a middle ground because their are benefits to both in my case.
     
  36. Game-Armada

    Game-Armada

    Joined:
    Apr 29, 2013
    Posts:
    66
    Hi,

    I have just started using AFS: https://assetstore.unity.com/packages/vfx/shaders/advanced-foliage-shaders-v-5-68907
    Bought the package because of this: Lighting is physically based driven by Unity's BRDF and supports deferred translucency.

    When I use deferred rendering, I loose all my translucency. Tried this on the demo scene too, but same happens.
    Could you help me setup the shader and/or unity to make it work?
    (images attached, using Unity 5.6.2f1)

    afs_forward.jpg afs_deferred.jpg
     
    Last edited: Aug 17, 2017
  37. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    you have to assign the custom deferred lighting and deferred reflection shaders. please look into the documentation to find out more.
     
  38. Game-Armada

    Game-Armada

    Joined:
    Apr 29, 2013
    Posts:
    66
    Oh, thx... sorry, had no time to read the document...
    Now everything works just fine: afs_test.jpg afs_test2.jpg
     
    Last edited: Aug 17, 2017
  39. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
  40. mukki014

    mukki014

    Joined:
    Jul 30, 2017
    Posts:
    164
    Hi can someone tell me how to use it? just a basic setup
     
  41. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    that a very generic question...
     
  42. AndyNeoman

    AndyNeoman

    Joined:
    Sep 28, 2014
    Posts:
    938
    Hi @larsbertram1 , do you plan on supporting Adam goodrich's World manager in AFS5? I'm looking to unify the wind/rain settings with about 5 different assets and this looks like the perfect tool to do it.
     
  43. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    nope. it does not do anything relevant – but setting global shader variables. his variables.
    it does not support lux, it does not support uber, it does not support afs. so what for?
    if you want to use it you can always copy paste the revant code from the afs setup script and add it as "custom function" or extension.
     
    AndyNeoman likes this.
  44. AndyNeoman

    AndyNeoman

    Joined:
    Sep 28, 2014
    Posts:
    938
    Argh OK, my idea was to use it to control wetness on AFS and wind settings, something that can take these settings from my unistorm asset for weather and then change the foliage to match. I will have to take a look at the AFS setup and work out how to change the global variables for wind and rain from there. Any advice on the best way to link up AFS, RTP and Unistorm so they match.
     
  45. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    not really, afs is biased using unity wind zone and a standard tree creator tree.
    wetness of e.g. lux is 6 times more complex than what that managers offers.
     
  46. silentslack

    silentslack

    Joined:
    Apr 5, 2013
    Posts:
    394
    Hi,

    Thanks for the update to 2017, looks like things are working for the most part.

    I'm trying to get my grass solution working. I'm using a grass mesh with the grass shader and hoping to get baked lightmapping and wind with best possible performance.

    I'm separating the grass into chunks around my mesh terrain (I'm guessing this will help with frustrum culling?). I'm using the CombineChildrenAFS for each chunk. I would like the combine to happen on Play so I can continue to tweak. However when I hit play my grass children meshes disappear and the combined mesh doesn't appear to be created. Do I need to switch something on to get the combine on play to work? If I hit 'Combine Statically' before hitting play it looks like it works but I have to manually remove the combined mesh, unhide the children etc.

    Also, is there really no way to get spec into the grass, even when using meshes and not the Unity Terrain System?

    Thanks! Jake
     
  47. AndyNeoman

    AndyNeoman

    Joined:
    Sep 28, 2014
    Posts:
    938
    Hi Lars, How do I change the wetness of AFS with code. Cant see any info in the docs on api calls.
     
  48. silentslack

    silentslack

    Joined:
    Apr 5, 2013
    Posts:
    394
    Apologies, I have just double checked and it looks to be working - not sure why it didn't work or I thought it didn't work correctly. It is combining on Play successfully.

    However, I have noticed another issue, certain faces of the grass appear to be black.
     
  49. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    i do not have an api for that. but just have a look into the afs setup script.
    remove the code there and copy it to your own script.

    AfsRainamountPID = Shader.PropertyToID("_AfsRainamount");
    ...
    // Update Rain Settings
    void afsUpdateRain() {
    Shader.SetGlobalFloat(AfsRainamountPID, RainAmount);
    }
     
    AndyNeoman likes this.
  50. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,902
    do you have a screen shoot for me?